title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
Python program to print even numbers in a list | 23 Jun, 2022
Given a list of numbers, write a Python program to print all even numbers in the given list.
Example:
Input: list1 = [2, 7, 5, 64, 14]
Output: [2, 64, 14]
Input: list2 = [12, 14, 95, 3]
Output: [12, 14]
Iterate each element in the list using for loop and check if num % 2 == 0. If the condition satisfies, then only print the number.
Python3
# Python program to print Even Numbers in a List # list of numberslist1 = [10, 21, 4, 45, 66, 93] # iterating each number in listfor num in list1: # checking condition if num % 2 == 0: print(num, end=" ")
Output:
10, 4, 66
Python3
# Python program to print Even Numbers in a List # list of numberslist1 = [10, 24, 4, 45, 66, 93]num = 0 # using while loopwhile(num < len(list1)): # checking condition if list1[num] % 2 == 0: print(list1[num], end=" ") # increment num num += 1
Output:
10, 4, 66
Python3
# Python program to print even Numbers in a List # list of numberslist1 = [10, 21, 4, 45, 66, 93] # using list comprehensioneven_nos = [num for num in list1 if num % 2 == 0] print("Even numbers in the list: ", even_nos)
Output:
Even numbers in the list: [10, 4, 66]
Python3
# Python program to print Even Numbers in a List # list of numberslist1 = [10, 21, 4, 45, 66, 93, 11] # we can also print even no's using lambda exp.even_nos = list(filter(lambda x: (x % 2 == 0), list1)) print("Even numbers in the list: ", even_nos)
Output:
Even numbers in the list: [10, 4, 66]
Method 5: Using Recursion
Python3
#Python program to print#even numbers in a list using recursiondef evennumbers(list, n=0): #base case if n==len(list): exit() if list[n]%2==0: print(list[n], end=" ") #calling function recursively evennumbers(list, n+1)list1 = [10, 21, 4, 45, 66, 93]print("Even numbers in the list:", end=" ")evennumbers(list1)#this code is contributed by Shivesh Kumar Dwivedi
Even numbers in the list: 10 4 66
aveekdas1
cpdwivedi916
Python list-programs
python-list
Python
Python Programs
School Programming
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n23 Jun, 2022"
},
{
"code": null,
"e": 145,
"s": 52,
"text": "Given a list of numbers, write a Python program to print all even numbers in the given list."
},
{
"code": null,
"e": 155,
"s": 145,
"text": "Example: "
},
{
"code": null,
"e": 257,
"s": 155,
"text": "Input: list1 = [2, 7, 5, 64, 14]\nOutput: [2, 64, 14]\n\nInput: list2 = [12, 14, 95, 3]\nOutput: [12, 14]"
},
{
"code": null,
"e": 389,
"s": 257,
"text": "Iterate each element in the list using for loop and check if num % 2 == 0. If the condition satisfies, then only print the number. "
},
{
"code": null,
"e": 397,
"s": 389,
"text": "Python3"
},
{
"code": "# Python program to print Even Numbers in a List # list of numberslist1 = [10, 21, 4, 45, 66, 93] # iterating each number in listfor num in list1: # checking condition if num % 2 == 0: print(num, end=\" \")",
"e": 616,
"s": 397,
"text": null
},
{
"code": null,
"e": 625,
"s": 616,
"text": "Output: "
},
{
"code": null,
"e": 635,
"s": 625,
"text": "10, 4, 66"
},
{
"code": null,
"e": 643,
"s": 635,
"text": "Python3"
},
{
"code": "# Python program to print Even Numbers in a List # list of numberslist1 = [10, 24, 4, 45, 66, 93]num = 0 # using while loopwhile(num < len(list1)): # checking condition if list1[num] % 2 == 0: print(list1[num], end=\" \") # increment num num += 1",
"e": 909,
"s": 643,
"text": null
},
{
"code": null,
"e": 918,
"s": 909,
"text": "Output: "
},
{
"code": null,
"e": 928,
"s": 918,
"text": "10, 4, 66"
},
{
"code": null,
"e": 936,
"s": 928,
"text": "Python3"
},
{
"code": "# Python program to print even Numbers in a List # list of numberslist1 = [10, 21, 4, 45, 66, 93] # using list comprehensioneven_nos = [num for num in list1 if num % 2 == 0] print(\"Even numbers in the list: \", even_nos)",
"e": 1156,
"s": 936,
"text": null
},
{
"code": null,
"e": 1165,
"s": 1156,
"text": "Output: "
},
{
"code": null,
"e": 1204,
"s": 1165,
"text": "Even numbers in the list: [10, 4, 66]"
},
{
"code": null,
"e": 1212,
"s": 1204,
"text": "Python3"
},
{
"code": "# Python program to print Even Numbers in a List # list of numberslist1 = [10, 21, 4, 45, 66, 93, 11] # we can also print even no's using lambda exp.even_nos = list(filter(lambda x: (x % 2 == 0), list1)) print(\"Even numbers in the list: \", even_nos)",
"e": 1463,
"s": 1212,
"text": null
},
{
"code": null,
"e": 1472,
"s": 1463,
"text": "Output: "
},
{
"code": null,
"e": 1511,
"s": 1472,
"text": "Even numbers in the list: [10, 4, 66]"
},
{
"code": null,
"e": 1537,
"s": 1511,
"text": "Method 5: Using Recursion"
},
{
"code": null,
"e": 1545,
"s": 1537,
"text": "Python3"
},
{
"code": "#Python program to print#even numbers in a list using recursiondef evennumbers(list, n=0): #base case if n==len(list): exit() if list[n]%2==0: print(list[n], end=\" \") #calling function recursively evennumbers(list, n+1)list1 = [10, 21, 4, 45, 66, 93]print(\"Even numbers in the list:\", end=\" \")evennumbers(list1)#this code is contributed by Shivesh Kumar Dwivedi",
"e": 1936,
"s": 1545,
"text": null
},
{
"code": null,
"e": 1971,
"s": 1936,
"text": "Even numbers in the list: 10 4 66 "
},
{
"code": null,
"e": 1981,
"s": 1971,
"text": "aveekdas1"
},
{
"code": null,
"e": 1994,
"s": 1981,
"text": "cpdwivedi916"
},
{
"code": null,
"e": 2015,
"s": 1994,
"text": "Python list-programs"
},
{
"code": null,
"e": 2027,
"s": 2015,
"text": "python-list"
},
{
"code": null,
"e": 2034,
"s": 2027,
"text": "Python"
},
{
"code": null,
"e": 2050,
"s": 2034,
"text": "Python Programs"
},
{
"code": null,
"e": 2069,
"s": 2050,
"text": "School Programming"
},
{
"code": null,
"e": 2081,
"s": 2069,
"text": "python-list"
},
{
"code": null,
"e": 2179,
"s": 2081,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2221,
"s": 2179,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2243,
"s": 2221,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2269,
"s": 2243,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2301,
"s": 2269,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2330,
"s": 2301,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2352,
"s": 2330,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2391,
"s": 2352,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2429,
"s": 2391,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 2478,
"s": 2429,
"text": "Python | Convert string dictionary to dictionary"
}
]
|
Ethical Hacking - Exploitation | Exploitation is a piece of programmed software or script which can allow hackers to take control over a system, exploiting its vulnerabilities. Hackers normally use vulnerability scanners like Nessus, Nexpose, OpenVAS, etc. to find these vulnerabilities.
Metasploit is a powerful tool to locate vulnerabilities in a system.
Based on the vulnerabilities, we find exploits. Here, we will discuss some of the best vulnerability search engines that you can use.
www.exploit-db.com is the place where you can find all the exploits related to a vulnerability.
Common Vulnerabilities and Exposures (CVE) is the standard for information security vulnerability names. CVE is a dictionary of publicly known information security vulnerabilities and exposures. It’s free for public use. https://cve.mitre.org
National Vulnerability Database (NVD) is the U.S. government repository of standards based vulnerability management data. This data enables automation of vulnerability management, security measurement, and compliance. You can locate this database at − https://nvd.nist.gov
NVD includes databases of security checklists, security-related software flaws, misconfigurations, product names, and impact metrics.
In general, you will see that there are two types of exploits −
Remote Exploits − These are the type of exploits where you don’t have access to a remote system or network. Hackers use remote exploits to gain access to systems that are located at remote places.
Remote Exploits − These are the type of exploits where you don’t have access to a remote system or network. Hackers use remote exploits to gain access to systems that are located at remote places.
Local Exploits − Local exploits are generally used by a system user having access to a local system, but who wants to overpass his rights.
Local Exploits − Local exploits are generally used by a system user having access to a local system, but who wants to overpass his rights.
Vulnerabilities generally arise due to missing updates, so it is recommended that you update your system on a regular basis, for example, once a week.
In Windows environment, you can activate automatic updates by using the options available in the Control Panel → System and Security → Windows Updates.
In Linux Centos, you can use the following command to install automatic update package.
yum -y install yum-cron
36 Lectures
5 hours
Sharad Kumar
31 Lectures
3.5 hours
Abhilash Nelson
22 Lectures
3 hours
Blair Cook
74 Lectures
4.5 hours
199courses
75 Lectures
4.5 hours
199courses
148 Lectures
28.5 hours
Joseph Delgadillo
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2734,
"s": 2479,
"text": "Exploitation is a piece of programmed software or script which can allow hackers to take control over a system, exploiting its vulnerabilities. Hackers normally use vulnerability scanners like Nessus, Nexpose, OpenVAS, etc. to find these vulnerabilities."
},
{
"code": null,
"e": 2803,
"s": 2734,
"text": "Metasploit is a powerful tool to locate vulnerabilities in a system."
},
{
"code": null,
"e": 2937,
"s": 2803,
"text": "Based on the vulnerabilities, we find exploits. Here, we will discuss some of the best vulnerability search engines that you can use."
},
{
"code": null,
"e": 3033,
"s": 2937,
"text": "www.exploit-db.com is the place where you can find all the exploits related to a vulnerability."
},
{
"code": null,
"e": 3276,
"s": 3033,
"text": "Common Vulnerabilities and Exposures (CVE) is the standard for information security vulnerability names. CVE is a dictionary of publicly known information security vulnerabilities and exposures. It’s free for public use. https://cve.mitre.org"
},
{
"code": null,
"e": 3549,
"s": 3276,
"text": "National Vulnerability Database (NVD) is the U.S. government repository of standards based vulnerability management data. This data enables automation of vulnerability management, security measurement, and compliance. You can locate this database at − https://nvd.nist.gov"
},
{
"code": null,
"e": 3683,
"s": 3549,
"text": "NVD includes databases of security checklists, security-related software flaws, misconfigurations, product names, and impact metrics."
},
{
"code": null,
"e": 3747,
"s": 3683,
"text": "In general, you will see that there are two types of exploits −"
},
{
"code": null,
"e": 3944,
"s": 3747,
"text": "Remote Exploits − These are the type of exploits where you don’t have access to a remote system or network. Hackers use remote exploits to gain access to systems that are located at remote places."
},
{
"code": null,
"e": 4141,
"s": 3944,
"text": "Remote Exploits − These are the type of exploits where you don’t have access to a remote system or network. Hackers use remote exploits to gain access to systems that are located at remote places."
},
{
"code": null,
"e": 4280,
"s": 4141,
"text": "Local Exploits − Local exploits are generally used by a system user having access to a local system, but who wants to overpass his rights."
},
{
"code": null,
"e": 4419,
"s": 4280,
"text": "Local Exploits − Local exploits are generally used by a system user having access to a local system, but who wants to overpass his rights."
},
{
"code": null,
"e": 4570,
"s": 4419,
"text": "Vulnerabilities generally arise due to missing updates, so it is recommended that you update your system on a regular basis, for example, once a week."
},
{
"code": null,
"e": 4722,
"s": 4570,
"text": "In Windows environment, you can activate automatic updates by using the options available in the Control Panel → System and Security → Windows Updates."
},
{
"code": null,
"e": 4810,
"s": 4722,
"text": "In Linux Centos, you can use the following command to install automatic update package."
},
{
"code": null,
"e": 4835,
"s": 4810,
"text": "yum -y install yum-cron\n"
},
{
"code": null,
"e": 4868,
"s": 4835,
"text": "\n 36 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 4882,
"s": 4868,
"text": " Sharad Kumar"
},
{
"code": null,
"e": 4917,
"s": 4882,
"text": "\n 31 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 4934,
"s": 4917,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 4967,
"s": 4934,
"text": "\n 22 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 4979,
"s": 4967,
"text": " Blair Cook"
},
{
"code": null,
"e": 5014,
"s": 4979,
"text": "\n 74 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 5026,
"s": 5014,
"text": " 199courses"
},
{
"code": null,
"e": 5061,
"s": 5026,
"text": "\n 75 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 5073,
"s": 5061,
"text": " 199courses"
},
{
"code": null,
"e": 5110,
"s": 5073,
"text": "\n 148 Lectures \n 28.5 hours \n"
},
{
"code": null,
"e": 5129,
"s": 5110,
"text": " Joseph Delgadillo"
},
{
"code": null,
"e": 5136,
"s": 5129,
"text": " Print"
},
{
"code": null,
"e": 5147,
"s": 5136,
"text": " Add Notes"
}
]
|
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 use <mat-chip-list> and <mat-chip> in Angular Material ?
Angular PrimeNG Dropdown Component
How to make a Bootstrap Modal Popup in Angular 9/8 ?
Angular 10 (blur) Event
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 25175,
"s": 25144,
"text": " \n03 Jun, 2021\n"
},
{
"code": null,
"e": 25345,
"s": 25175,
"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 or not."
},
{
"code": null,
"e": 25353,
"s": 25345,
"text": "Syntax:"
},
{
"code": null,
"e": 25364,
"s": 25353,
"text": "form.valid"
},
{
"code": null,
"e": 25378,
"s": 25364,
"text": "Return Value:"
},
{
"code": null,
"e": 25446,
"s": 25378,
"text": "boolean: the boolean value to check whether a form is valid or not."
},
{
"code": null,
"e": 25494,
"s": 25446,
"text": "NgModule: Module used by the valid property is:"
},
{
"code": null,
"e": 25506,
"s": 25494,
"text": "FormsModule"
},
{
"code": null,
"e": 25519,
"s": 25508,
"text": "Approach: "
},
{
"code": null,
"e": 25554,
"s": 25519,
"text": "Create the Angular app to be used."
},
{
"code": null,
"e": 25612,
"s": 25554,
"text": "In app.component.html make a form using ngForm directive."
},
{
"code": null,
"e": 25678,
"s": 25612,
"text": "In app.component.ts get the information using the valid property."
},
{
"code": null,
"e": 25734,
"s": 25678,
"text": "Serve the angular app using ng serve to see the output."
},
{
"code": null,
"e": 25743,
"s": 25734,
"text": "Example:"
},
{
"code": null,
"e": 25754,
"s": 25743,
"text": "Javascript"
},
{
"code": "\n\n\n\n\n\n\nimport { Component } from '@angular/core'; \nimport { FormGroup, FormControl, \n FormArray, Validators } from '@angular/forms'\n \n@Component({ \n selector: 'app-root', \n templateUrl: './app.component.html'\n}) \n \nexport class AppComponent { \n form = new FormGroup({ \n name: new FormControl( \n \n ), \n rollno: new FormControl() \n }); \n \n get name(): any { \n return this.form.get('name'); \n } \n \n onSubmit(): void { \n console.log(\"Form is valid : \", this.form.valid); \n } \n} \n\n\n\n\n\n",
"e": 26313,
"s": 25764,
"text": null
},
{
"code": null,
"e": 26332,
"s": 26313,
"text": "app.component.html"
},
{
"code": "\n\n\n\n\n\n\n<form [formGroup]=\"form\" (ngSubmit)=\"onSubmit()\"> \n <input formControlName=\"name\" placeholder=\"Name\"> \n <br> \n \n <button type='submit'>Submit</button> \n <br><br> \n</form> \n\n\n\n\n\n",
"e": 26544,
"s": 26342,
"text": null
},
{
"code": null,
"e": 26552,
"s": 26544,
"text": "Output:"
},
{
"code": null,
"e": 26624,
"s": 26552,
"text": "Reference: >https://angular.io/api/forms/AbstractControlDirective#valid"
},
{
"code": null,
"e": 26636,
"s": 26624,
"text": "\nAngular10\n"
},
{
"code": null,
"e": 26658,
"s": 26636,
"text": "\nAngularJS-Questions\n"
},
{
"code": null,
"e": 26670,
"s": 26658,
"text": "\nAngularJS\n"
},
{
"code": null,
"e": 26689,
"s": 26670,
"text": "\nWeb Technologies\n"
},
{
"code": null,
"e": 26894,
"s": 26689,
"text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n "
},
{
"code": null,
"e": 26938,
"s": 26894,
"text": "Top 10 Angular Libraries For Web Developers"
},
{
"code": null,
"e": 27002,
"s": 26938,
"text": "How to use <mat-chip-list> and <mat-chip> in Angular Material ?"
},
{
"code": null,
"e": 27037,
"s": 27002,
"text": "Angular PrimeNG Dropdown Component"
},
{
"code": null,
"e": 27090,
"s": 27037,
"text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?"
},
{
"code": null,
"e": 27114,
"s": 27090,
"text": "Angular 10 (blur) Event"
},
{
"code": null,
"e": 27156,
"s": 27114,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 27189,
"s": 27156,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27251,
"s": 27189,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 27294,
"s": 27251,
"text": "How to fetch data from an API in ReactJS ?"
}
]
|
ReactJS Blueprint DateRangePicker Component - GeeksforGeeks | 09 Jul, 2021
BlueprintJS is a React-based UI toolkit for the web. This library is very optimized and popular for building interfaces that are complex data-dense for desktop applications. DateRangePicker Component helps the user to select a single range of days, and it shows two sequential month calendars. We can use the following approach in ReactJS to use the ReactJS Blueprint DateRangePicker Component.
DateRangeShortcut Props:
dateRange: It is used to denote the date range represented by this shortcut.
includeTime: It is used to allow this shortcut to change the selected times as well as the dates if this prop is set to true.
label: It is used to denote the shortcut label that appears in the list.
DateRangePicker Props:
allowSingleDayRange: It is used to indicate whether the start and end dates of range can be the same day.
boundaryToModify: It is used to denote the date-range boundary that the next click should modify.
className: It is used to denote a space-delimited list of class names to pass along to a child element.
contiguousCalendarMonths: It is used to indicate whether displayed months in the calendar are contiguous.
dayPickerProps: It is used to denote the props to pass to ReactDayPicker.
defaultValue: It is used to denote the initial DateRange the calendar will display as selected.
highlightCurrentDay: It is used to indicate whether the current day should be highlighted in the calendar.
initialMonth: It is used to denote the initial month the calendar displays.
locale: It is used to denote the locale name that is passed to the functions in localeUtils.
localeUtils: It is used to denote the collection of functions that provide internationalization support.
maxDate: It is used to denote the latest date the user can select.
minDate: It is used to denote the earliest date the user can select.
modifiers: It is used to denote the collection of functions that determine which modifier classes get applied to which days.
onChange: It is a callback function that is triggered when the user selects a day.
onHoverChange: It is a callback function that is triggered when the user changes the hovered date range.
onShortcutChange: It is a callback function that is triggered when the shortcuts props are enabled and the user changes the shortcut.
reverseMonthAndYearMenus: The month menu will appear to the left of the year menu if this is set to true.
selectedShortcutIndex: It is used to denote the currently selected shortcut.
shortcuts: It is used to indicate whether shortcuts to quickly select a range of dates are displayed or not.
singleMonthOnly: It is used to indicate whether to show only a single month calendar.
timePickerProps: It is used to further configure the TimePicker that appears beneath the calendar.
timePrecision: It is used to denote the precision of time selection that accompanies the calendar.
value: It is used to denote the currently selected DateRange.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:npx create-react-app foldername
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Step 3: After creating the ReactJS application, Install the required module using the following command:npm install @blueprintjs/core
npm install @blueprintjs/popover2
Step 3: After creating the ReactJS application, Install the required module using the following command:
npm install @blueprintjs/core
npm install @blueprintjs/popover2
Project Structure: It will look like the following.
Project Structure
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
App.js
import React from 'react'import '@blueprintjs/datetime/lib/css/blueprint-datetime.css';import '@blueprintjs/core/lib/css/blueprint.css';import { DateRangePicker } from "@blueprintjs/datetime"; function App() { return ( <div style={{ display: 'block', width: 400, padding: 30 }}> <h4>ReactJS Blueprint DateRangePicker Component</h4> <DateRangePicker /> </div > );} export default App;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
Reference: https://blueprintjs.com/docs/#datetime/daterangepicker
React-Blueprint
JavaScript
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
How to fetch data from an API in ReactJS ?
How to redirect to another page in ReactJS ?
How to pass data from child component to its parent in ReactJS ?
How to pass data from one component to other component in ReactJS ?
ReactJS Functional Components | [
{
"code": null,
"e": 25410,
"s": 25382,
"text": "\n09 Jul, 2021"
},
{
"code": null,
"e": 25805,
"s": 25410,
"text": "BlueprintJS is a React-based UI toolkit for the web. This library is very optimized and popular for building interfaces that are complex data-dense for desktop applications. DateRangePicker Component helps the user to select a single range of days, and it shows two sequential month calendars. We can use the following approach in ReactJS to use the ReactJS Blueprint DateRangePicker Component."
},
{
"code": null,
"e": 25830,
"s": 25805,
"text": "DateRangeShortcut Props:"
},
{
"code": null,
"e": 25907,
"s": 25830,
"text": "dateRange: It is used to denote the date range represented by this shortcut."
},
{
"code": null,
"e": 26033,
"s": 25907,
"text": "includeTime: It is used to allow this shortcut to change the selected times as well as the dates if this prop is set to true."
},
{
"code": null,
"e": 26106,
"s": 26033,
"text": "label: It is used to denote the shortcut label that appears in the list."
},
{
"code": null,
"e": 26129,
"s": 26106,
"text": "DateRangePicker Props:"
},
{
"code": null,
"e": 26235,
"s": 26129,
"text": "allowSingleDayRange: It is used to indicate whether the start and end dates of range can be the same day."
},
{
"code": null,
"e": 26333,
"s": 26235,
"text": "boundaryToModify: It is used to denote the date-range boundary that the next click should modify."
},
{
"code": null,
"e": 26437,
"s": 26333,
"text": "className: It is used to denote a space-delimited list of class names to pass along to a child element."
},
{
"code": null,
"e": 26543,
"s": 26437,
"text": "contiguousCalendarMonths: It is used to indicate whether displayed months in the calendar are contiguous."
},
{
"code": null,
"e": 26617,
"s": 26543,
"text": "dayPickerProps: It is used to denote the props to pass to ReactDayPicker."
},
{
"code": null,
"e": 26713,
"s": 26617,
"text": "defaultValue: It is used to denote the initial DateRange the calendar will display as selected."
},
{
"code": null,
"e": 26820,
"s": 26713,
"text": "highlightCurrentDay: It is used to indicate whether the current day should be highlighted in the calendar."
},
{
"code": null,
"e": 26896,
"s": 26820,
"text": "initialMonth: It is used to denote the initial month the calendar displays."
},
{
"code": null,
"e": 26989,
"s": 26896,
"text": "locale: It is used to denote the locale name that is passed to the functions in localeUtils."
},
{
"code": null,
"e": 27094,
"s": 26989,
"text": "localeUtils: It is used to denote the collection of functions that provide internationalization support."
},
{
"code": null,
"e": 27161,
"s": 27094,
"text": "maxDate: It is used to denote the latest date the user can select."
},
{
"code": null,
"e": 27230,
"s": 27161,
"text": "minDate: It is used to denote the earliest date the user can select."
},
{
"code": null,
"e": 27355,
"s": 27230,
"text": "modifiers: It is used to denote the collection of functions that determine which modifier classes get applied to which days."
},
{
"code": null,
"e": 27438,
"s": 27355,
"text": "onChange: It is a callback function that is triggered when the user selects a day."
},
{
"code": null,
"e": 27543,
"s": 27438,
"text": "onHoverChange: It is a callback function that is triggered when the user changes the hovered date range."
},
{
"code": null,
"e": 27677,
"s": 27543,
"text": "onShortcutChange: It is a callback function that is triggered when the shortcuts props are enabled and the user changes the shortcut."
},
{
"code": null,
"e": 27783,
"s": 27677,
"text": "reverseMonthAndYearMenus: The month menu will appear to the left of the year menu if this is set to true."
},
{
"code": null,
"e": 27860,
"s": 27783,
"text": "selectedShortcutIndex: It is used to denote the currently selected shortcut."
},
{
"code": null,
"e": 27969,
"s": 27860,
"text": "shortcuts: It is used to indicate whether shortcuts to quickly select a range of dates are displayed or not."
},
{
"code": null,
"e": 28055,
"s": 27969,
"text": "singleMonthOnly: It is used to indicate whether to show only a single month calendar."
},
{
"code": null,
"e": 28154,
"s": 28055,
"text": "timePickerProps: It is used to further configure the TimePicker that appears beneath the calendar."
},
{
"code": null,
"e": 28253,
"s": 28154,
"text": "timePrecision: It is used to denote the precision of time selection that accompanies the calendar."
},
{
"code": null,
"e": 28315,
"s": 28253,
"text": "value: It is used to denote the currently selected DateRange."
},
{
"code": null,
"e": 28367,
"s": 28317,
"text": "Creating React Application And Installing Module:"
},
{
"code": null,
"e": 28462,
"s": 28367,
"text": "Step 1: Create a React application using the following command:npx create-react-app foldername"
},
{
"code": null,
"e": 28526,
"s": 28462,
"text": "Step 1: Create a React application using the following command:"
},
{
"code": null,
"e": 28558,
"s": 28526,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 28671,
"s": 28558,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername"
},
{
"code": null,
"e": 28771,
"s": 28671,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:"
},
{
"code": null,
"e": 28785,
"s": 28771,
"text": "cd foldername"
},
{
"code": null,
"e": 28953,
"s": 28785,
"text": "Step 3: After creating the ReactJS application, Install the required module using the following command:npm install @blueprintjs/core\nnpm install @blueprintjs/popover2"
},
{
"code": null,
"e": 29058,
"s": 28953,
"text": "Step 3: After creating the ReactJS application, Install the required module using the following command:"
},
{
"code": null,
"e": 29122,
"s": 29058,
"text": "npm install @blueprintjs/core\nnpm install @blueprintjs/popover2"
},
{
"code": null,
"e": 29174,
"s": 29122,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 29192,
"s": 29174,
"text": "Project Structure"
},
{
"code": null,
"e": 29322,
"s": 29192,
"text": "Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code."
},
{
"code": null,
"e": 29329,
"s": 29322,
"text": "App.js"
},
{
"code": "import React from 'react'import '@blueprintjs/datetime/lib/css/blueprint-datetime.css';import '@blueprintjs/core/lib/css/blueprint.css';import { DateRangePicker } from \"@blueprintjs/datetime\"; function App() { return ( <div style={{ display: 'block', width: 400, padding: 30 }}> <h4>ReactJS Blueprint DateRangePicker Component</h4> <DateRangePicker /> </div > );} export default App;",
"e": 29775,
"s": 29329,
"text": null
},
{
"code": null,
"e": 29888,
"s": 29775,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 29898,
"s": 29888,
"text": "npm start"
},
{
"code": null,
"e": 29997,
"s": 29898,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:"
},
{
"code": null,
"e": 30063,
"s": 29997,
"text": "Reference: https://blueprintjs.com/docs/#datetime/daterangepicker"
},
{
"code": null,
"e": 30079,
"s": 30063,
"text": "React-Blueprint"
},
{
"code": null,
"e": 30090,
"s": 30079,
"text": "JavaScript"
},
{
"code": null,
"e": 30098,
"s": 30090,
"text": "ReactJS"
},
{
"code": null,
"e": 30115,
"s": 30098,
"text": "Web Technologies"
},
{
"code": null,
"e": 30213,
"s": 30115,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30253,
"s": 30213,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 30314,
"s": 30253,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 30355,
"s": 30314,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 30377,
"s": 30355,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 30431,
"s": 30377,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 30474,
"s": 30431,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 30519,
"s": 30474,
"text": "How to redirect to another page in ReactJS ?"
},
{
"code": null,
"e": 30584,
"s": 30519,
"text": "How to pass data from child component to its parent in ReactJS ?"
},
{
"code": null,
"e": 30652,
"s": 30584,
"text": "How to pass data from one component to other component in ReactJS ?"
}
]
|
Missing characters to make a string Pangram - GeeksforGeeks | 10 Mar, 2022
Pangram is a sentence containing every letter in the English alphabet. Given a string, find all characters that are missing from the string, i.e., the characters that can make the string a Pangram. We need to print output in alphabetic order.
Examples:
Input : welcome to geeksforgeeks
Output : abdhijnpquvxyz
Input : The quick brown fox jumps
Output : adglvyz
We have discussed Pangram Checking. The idea is similar, we traverse a given string and mark all visited characters. In the end, we print all those characters which are not visited.
Lowercase and Uppercase characters are considered the same.
C++
Java
Python3
C#
Javascript
// C++ program to find characters that needs// to be added to make Pangram#include<bits/stdc++.h>using namespace std;const int MAX_CHAR = 26; // Returns characters that needs to be added// to make strstring missingChars(string str){ // A boolean array to store characters // present in string. bool present[MAX_CHAR] = {false}; // Traverse string and mark characters // present in string. for (int i=0; i<str.length(); i++) { if (str[i] >= 'a' && str[i] <= 'z') present[str[i]-'a'] = true; else if (str[i] >= 'A' && str[i] <= 'Z') present[str[i]-'A'] = true; } // Store missing characters in alphabetic // order. string res = ""; for (int i=0; i<MAX_CHAR; i++) if (present[i] == false) res.push_back((char)(i+'a')); return res;} // Driver programint main(){ string str = "The quick brown fox jumps " "over the dog"; cout << missingChars(str); return 0;}
// Java program to find characters that// needs to be added to make Pangramimport java.io.*;import java.util.ArrayList; class GFG{ private static ArrayList<Character>missingChars( String str, int strLength){ final int MAX_CHARS = 26; // A boolean array to store characters // present in string. boolean[] present = new boolean[MAX_CHARS]; ArrayList<Character> charsList = new ArrayList<>(); // Traverse string and mark characters // present in string. for(int i = 0; i < strLength; i++) { if ('A' <= str.charAt(i) && str.charAt(i) <= 'Z') present[str.charAt(i) - 'A'] = true; else if ('a' <= str.charAt(i) && str.charAt(i) <= 'z') present[str.charAt(i) - 'a'] = true; } // Store missing characters in alphabetic // order. for(int i = 0; i < MAX_CHARS; i++) { if (present[i] == false) charsList.add((char)(i + 'a')); } return charsList;} // Driver Codepublic static void main(String[] args){ String str = "The quick brown fox jumps " + "over the dog"; ArrayList<Character> missing = GFG.missingChars( str, str.length()); if (missing.size() >= 1) { for(Character character : missing) { System.out.print(character); } }}} // This code is contributed by theSardul
# Python3 program to find characters# that needs to be added to make PangramMAX_CHAR = 26 # Returns characters that needs# to be added to make strdef missingChars(Str): # A boolean array to store characters # present in string. present = [False for i in range(MAX_CHAR)] # Traverse string and mark characters # present in string. for i in range(len(Str)): if (Str[i] >= 'a' and Str[i] <= 'z'): present[ord(Str[i]) - ord('a')] = True else if (Str[i] >= 'A' and Str[i] <= 'Z'): present[ord(Str[i]) - ord('A')] = True # Store missing characters in alphabetic # order. res = "" for i in range(MAX_CHAR): if (present[i] == False): res += chr(i + ord('a')) return res # Driver codeStr = "The quick brown fox jumps over the dog" print(missingChars(Str)) # This code is contributed by avanitrachhadiya2155
// C# program to find characters that// needs to be added to make Pangramusing System.Collections.Generic;using System;class GFG{ static List<char>missingChars (String str, int strLength){ int MAX_CHARS = 26; // A boolean array to store // characters present in string. bool[] present = new bool[MAX_CHARS]; List<char>charsList = new List<char>(); // Traverse string and mark // characters present in string. for(int i = 0; i < strLength; i++) { if ('A' <= str[i] && str[i] <= 'Z') present[str[i] - 'A'] = true; else if ('a' <= str[i] && str[i] <= 'z') present[str[i] - 'a'] = true; } // Store missing characters // in alphabetic order. for(int i = 0; i < 26; i++) { if (present[i] == false) { charsList.Add((char)(i + 'a')); } } return charsList;} // Driver Codepublic static void Main(){ String str = "The quick brown fox jumps over the dog"; List<char> missing = missingChars(str, str.Length); if (missing.Count >= 1) { foreach (var i in missing) { Console.Write(i); } }}} // This code is contributed by Stream_Cipher
<script> // Javascript program to find characters that // needs to be added to make Pangram function missingChars (str, strLength) { let MAX_CHARS = 26; // A boolean array to store // characters present in string. let present = new Array(MAX_CHARS); present.fill(false); let charsList = []; // Traverse string and mark // characters present in string. for(let i = 0; i < strLength; i++) { if ('A'.charCodeAt() <= str[i].charCodeAt() && str[i].charCodeAt() <= 'Z'.charCodeAt()) present[str[i].charCodeAt() - 'A'.charCodeAt()] = true; else if ('a'.charCodeAt() <= str[i].charCodeAt() && str[i].charCodeAt() <= 'z'.charCodeAt()) present[str[i].charCodeAt() - 'a'.charCodeAt()] = true; } // Store missing characters // in alphabetic order. for(let i = 0; i < 26; i++) { if (present[i] == false) { charsList.push(String.fromCharCode(i + 'a'.charCodeAt())); } } return charsList; } let str = "The quick brown fox jumps over the dog"; let missing = missingChars(str, str.length); if (missing.length >= 1) { for(let i = 0; i < missing.length; i++) { document.write(missing[i]); } } // This code is contributed by mukesh07.</script>
Output:
alyz
Time Complexity: O(n) Auxiliary Space: O(1)
https://youtu.be/VqGOxv8Fb1E
theSardul
avanitrachhadiya2155
Stream_Cipher
mukesh07
surinderdawra388
School Programming
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Interfaces in Java
Operator Overloading in C++
C++ Classes and Objects
Constructors in C++
Copy Constructor in C++
Write a program to reverse an array or string
Longest Common Subsequence | DP-4
C++ Data Types
Write a program to print all permutations of a given string
Check for Balanced Brackets in an expression (well-formedness) using Stack | [
{
"code": null,
"e": 24683,
"s": 24655,
"text": "\n10 Mar, 2022"
},
{
"code": null,
"e": 24926,
"s": 24683,
"text": "Pangram is a sentence containing every letter in the English alphabet. Given a string, find all characters that are missing from the string, i.e., the characters that can make the string a Pangram. We need to print output in alphabetic order."
},
{
"code": null,
"e": 24937,
"s": 24926,
"text": "Examples: "
},
{
"code": null,
"e": 25046,
"s": 24937,
"text": "Input : welcome to geeksforgeeks\nOutput : abdhijnpquvxyz\n\nInput : The quick brown fox jumps\nOutput : adglvyz"
},
{
"code": null,
"e": 25228,
"s": 25046,
"text": "We have discussed Pangram Checking. The idea is similar, we traverse a given string and mark all visited characters. In the end, we print all those characters which are not visited."
},
{
"code": null,
"e": 25289,
"s": 25228,
"text": "Lowercase and Uppercase characters are considered the same. "
},
{
"code": null,
"e": 25293,
"s": 25289,
"text": "C++"
},
{
"code": null,
"e": 25298,
"s": 25293,
"text": "Java"
},
{
"code": null,
"e": 25306,
"s": 25298,
"text": "Python3"
},
{
"code": null,
"e": 25309,
"s": 25306,
"text": "C#"
},
{
"code": null,
"e": 25320,
"s": 25309,
"text": "Javascript"
},
{
"code": "// C++ program to find characters that needs// to be added to make Pangram#include<bits/stdc++.h>using namespace std;const int MAX_CHAR = 26; // Returns characters that needs to be added// to make strstring missingChars(string str){ // A boolean array to store characters // present in string. bool present[MAX_CHAR] = {false}; // Traverse string and mark characters // present in string. for (int i=0; i<str.length(); i++) { if (str[i] >= 'a' && str[i] <= 'z') present[str[i]-'a'] = true; else if (str[i] >= 'A' && str[i] <= 'Z') present[str[i]-'A'] = true; } // Store missing characters in alphabetic // order. string res = \"\"; for (int i=0; i<MAX_CHAR; i++) if (present[i] == false) res.push_back((char)(i+'a')); return res;} // Driver programint main(){ string str = \"The quick brown fox jumps \" \"over the dog\"; cout << missingChars(str); return 0;} ",
"e": 26302,
"s": 25320,
"text": null
},
{
"code": "// Java program to find characters that// needs to be added to make Pangramimport java.io.*;import java.util.ArrayList; class GFG{ private static ArrayList<Character>missingChars( String str, int strLength){ final int MAX_CHARS = 26; // A boolean array to store characters // present in string. boolean[] present = new boolean[MAX_CHARS]; ArrayList<Character> charsList = new ArrayList<>(); // Traverse string and mark characters // present in string. for(int i = 0; i < strLength; i++) { if ('A' <= str.charAt(i) && str.charAt(i) <= 'Z') present[str.charAt(i) - 'A'] = true; else if ('a' <= str.charAt(i) && str.charAt(i) <= 'z') present[str.charAt(i) - 'a'] = true; } // Store missing characters in alphabetic // order. for(int i = 0; i < MAX_CHARS; i++) { if (present[i] == false) charsList.add((char)(i + 'a')); } return charsList;} // Driver Codepublic static void main(String[] args){ String str = \"The quick brown fox jumps \" + \"over the dog\"; ArrayList<Character> missing = GFG.missingChars( str, str.length()); if (missing.size() >= 1) { for(Character character : missing) { System.out.print(character); } }}} // This code is contributed by theSardul",
"e": 27724,
"s": 26302,
"text": null
},
{
"code": "# Python3 program to find characters# that needs to be added to make PangramMAX_CHAR = 26 # Returns characters that needs# to be added to make strdef missingChars(Str): # A boolean array to store characters # present in string. present = [False for i in range(MAX_CHAR)] # Traverse string and mark characters # present in string. for i in range(len(Str)): if (Str[i] >= 'a' and Str[i] <= 'z'): present[ord(Str[i]) - ord('a')] = True else if (Str[i] >= 'A' and Str[i] <= 'Z'): present[ord(Str[i]) - ord('A')] = True # Store missing characters in alphabetic # order. res = \"\" for i in range(MAX_CHAR): if (present[i] == False): res += chr(i + ord('a')) return res # Driver codeStr = \"The quick brown fox jumps over the dog\" print(missingChars(Str)) # This code is contributed by avanitrachhadiya2155",
"e": 28630,
"s": 27724,
"text": null
},
{
"code": "// C# program to find characters that// needs to be added to make Pangramusing System.Collections.Generic;using System;class GFG{ static List<char>missingChars (String str, int strLength){ int MAX_CHARS = 26; // A boolean array to store // characters present in string. bool[] present = new bool[MAX_CHARS]; List<char>charsList = new List<char>(); // Traverse string and mark // characters present in string. for(int i = 0; i < strLength; i++) { if ('A' <= str[i] && str[i] <= 'Z') present[str[i] - 'A'] = true; else if ('a' <= str[i] && str[i] <= 'z') present[str[i] - 'a'] = true; } // Store missing characters // in alphabetic order. for(int i = 0; i < 26; i++) { if (present[i] == false) { charsList.Add((char)(i + 'a')); } } return charsList;} // Driver Codepublic static void Main(){ String str = \"The quick brown fox jumps over the dog\"; List<char> missing = missingChars(str, str.Length); if (missing.Count >= 1) { foreach (var i in missing) { Console.Write(i); } }}} // This code is contributed by Stream_Cipher",
"e": 29807,
"s": 28630,
"text": null
},
{
"code": "<script> // Javascript program to find characters that // needs to be added to make Pangram function missingChars (str, strLength) { let MAX_CHARS = 26; // A boolean array to store // characters present in string. let present = new Array(MAX_CHARS); present.fill(false); let charsList = []; // Traverse string and mark // characters present in string. for(let i = 0; i < strLength; i++) { if ('A'.charCodeAt() <= str[i].charCodeAt() && str[i].charCodeAt() <= 'Z'.charCodeAt()) present[str[i].charCodeAt() - 'A'.charCodeAt()] = true; else if ('a'.charCodeAt() <= str[i].charCodeAt() && str[i].charCodeAt() <= 'z'.charCodeAt()) present[str[i].charCodeAt() - 'a'.charCodeAt()] = true; } // Store missing characters // in alphabetic order. for(let i = 0; i < 26; i++) { if (present[i] == false) { charsList.push(String.fromCharCode(i + 'a'.charCodeAt())); } } return charsList; } let str = \"The quick brown fox jumps over the dog\"; let missing = missingChars(str, str.length); if (missing.length >= 1) { for(let i = 0; i < missing.length; i++) { document.write(missing[i]); } } // This code is contributed by mukesh07.</script>",
"e": 31143,
"s": 29807,
"text": null
},
{
"code": null,
"e": 31152,
"s": 31143,
"text": "Output: "
},
{
"code": null,
"e": 31157,
"s": 31152,
"text": "alyz"
},
{
"code": null,
"e": 31202,
"s": 31157,
"text": "Time Complexity: O(n) Auxiliary Space: O(1) "
},
{
"code": null,
"e": 31232,
"s": 31202,
"text": "https://youtu.be/VqGOxv8Fb1E "
},
{
"code": null,
"e": 31242,
"s": 31232,
"text": "theSardul"
},
{
"code": null,
"e": 31263,
"s": 31242,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 31277,
"s": 31263,
"text": "Stream_Cipher"
},
{
"code": null,
"e": 31286,
"s": 31277,
"text": "mukesh07"
},
{
"code": null,
"e": 31303,
"s": 31286,
"text": "surinderdawra388"
},
{
"code": null,
"e": 31322,
"s": 31303,
"text": "School Programming"
},
{
"code": null,
"e": 31330,
"s": 31322,
"text": "Strings"
},
{
"code": null,
"e": 31338,
"s": 31330,
"text": "Strings"
},
{
"code": null,
"e": 31436,
"s": 31338,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31445,
"s": 31436,
"text": "Comments"
},
{
"code": null,
"e": 31458,
"s": 31445,
"text": "Old Comments"
},
{
"code": null,
"e": 31477,
"s": 31458,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 31505,
"s": 31477,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 31529,
"s": 31505,
"text": "C++ Classes and Objects"
},
{
"code": null,
"e": 31549,
"s": 31529,
"text": "Constructors in C++"
},
{
"code": null,
"e": 31573,
"s": 31549,
"text": "Copy Constructor in C++"
},
{
"code": null,
"e": 31619,
"s": 31573,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 31653,
"s": 31619,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 31668,
"s": 31653,
"text": "C++ Data Types"
},
{
"code": null,
"e": 31728,
"s": 31668,
"text": "Write a program to print all permutations of a given string"
}
]
|
divisibleBy() function over array in JavaScript | We are required to write a JavaScript function that takes in an array of numbers and a single number as two arguments.
Our function should filter the array to contain only those numbers that are divisible by the number provided as second argument and return the filtered array.
Following is the code −
Live Demo
const arr = [56, 33, 2, 4, 9, 78, 12, 18];
const num = 3;
const divisibleBy = (arr = [], num = 1) => {
const canDivide = (a, b) => a % b === 0;
const res = arr.filter(el => {
return canDivide(el, num);
});
return res;
};
console.log(divisibleBy(arr, num));
[ 33, 9, 78, 12, 18 ] | [
{
"code": null,
"e": 1181,
"s": 1062,
"text": "We are required to write a JavaScript function that takes in an array of numbers and a single number as two arguments."
},
{
"code": null,
"e": 1340,
"s": 1181,
"text": "Our function should filter the array to contain only those numbers that are divisible by the number provided as second argument and return the filtered array."
},
{
"code": null,
"e": 1364,
"s": 1340,
"text": "Following is the code −"
},
{
"code": null,
"e": 1375,
"s": 1364,
"text": " Live Demo"
},
{
"code": null,
"e": 1650,
"s": 1375,
"text": "const arr = [56, 33, 2, 4, 9, 78, 12, 18];\nconst num = 3;\nconst divisibleBy = (arr = [], num = 1) => {\n const canDivide = (a, b) => a % b === 0;\n const res = arr.filter(el => {\n return canDivide(el, num);\n });\n return res;\n};\nconsole.log(divisibleBy(arr, num));"
},
{
"code": null,
"e": 1672,
"s": 1650,
"text": "[ 33, 9, 78, 12, 18 ]"
}
]
|
Bootstrap | Tables | Set-2 - GeeksforGeeks | 15 Jul, 2021
Bootstrap provides us series of classes that can be used to apply various styling to tables such as changing the heading appearance, making the rows striped, adding or removing borders, making rows hoverable. Bootstrap also provides classes for making tables responsive.
Borderless table: To make the table borderless use the class table-borderless along with the class table class within the <table> tag. We can also make the dark table borderless by using the combination of classes table, table-dark and table-borderless within the <table> tag. See the example below for illustration.Example:
html
<!DOCTYPE html><html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> <title>Bootstrap | Tables</title> <style> h1{ color: green; text-align: center; } div{ margin-top: 10px; } </style> </head> <body> <div class="container"> <h1>GeeksForGeeks</h1> <!-- table, table-borderless --> <table class="table table-borderless"> <thead> <tr> <th scope="col">S. No.</td> <th scope="col">Name</td> <th scope="col">City</td> <th scope="col">Age</td> </tr> </thead> <tbody> <tr> <th scope="row">1</td> <td>Ajay</td> <td>Patna</td> <td>20</td> </tr> <tr> <th scope="row">2</td> <td>Rahul</td> <td>Chandigarh</td> <td>17</td> </tr> <tr> <th scope="row">3</td> <td>Parush</td> <td>Kolkata</td> <td>22</td> </tr> </tbody> </table> <!-- table, table-borderless, table-dark --> <table class="table table-borderless table-dark"> <thead> <tr> <th scope="col">S. No.</td> <th scope="col">Name</td> <th scope="col">City</td> <th scope="col">Age</td> </tr> </thead> <tbody> <tr> <th scope="row">1</td> <td>Ajay</td> <td>Patna</td> <td>20</td> </tr> <tr> <th scope="row">2</td> <td>Rahul</td> <td>Chandigarh</td> <td>17</td> </tr> <tr> <th scope="row">3</td> <td>Parush</td> <td>Kolkata</td> <td>22</td> </tr> </tbody> </table> </div> </body></html>
Output:
Hoverable table: To make the rows of table hoverable use the class table-hover along with the class table within the <table> tag. We can also make the rows of dark table hoverable using the combination of classes table, table-hover, and table-dark within the <table> tag. See the example below for illustration.Example:
html
<!DOCTYPE html><html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> <title>Bootstrap | Tables</title> <style> h1{ color: green; text-align: center; } div{ margin-top: 10px; } </style> </head> <body> <div class="container"> <h1>GeeksForGeeks</h1> <!-- table, table-hover --> <table class="table table-hover"> <thead> <tr> <th scope="col">S. No.</td> <th scope="col">Name</td> <th scope="col">City</td> <th scope="col">Age</td> </tr> </thead> <tbody> <tr> <th scope="row">1</td> <td>Ajay</td> <td>Patna</td> <td>20</td> </tr> <tr> <th scope="row">2</td> <td>Rahul</td> <td>Chandigarh</td> <td>17</td> </tr> <tr> <th scope="row">3</td> <td>Parush</td> <td>Kolkata</td> <td>22</td> </tr> </tbody> </table> <!-- table, table-hover, table-dark --> <table class="table table-hover table-dark"> <thead> <tr> <th scope="col">S. No.</td> <th scope="col">Name</td> <th scope="col">City</td> <th scope="col">Age</td> </tr> </thead> <tbody> <tr> <th scope="row">1</td> <td>Ajay</td> <td>Patna</td> <td>20</td> </tr> <tr> <th scope="row">2</td> <td>Rahul</td> <td>Chandigarh</td> <td>17</td> </tr> <tr> <th scope="row">3</td> <td>Parush</td> <td>Kolkata</td> <td>22</td> </tr> </tbody> </table> </div> </body></html>
Output:
Small table: To make the table smaller in size use the class table-sm along with the class table within the <table> tag. This reduces the cell padding to half. To make the dark table smaller in size use the combination of classes table, table-sm, and table-dark within the <table> tag. See the example below for illustration.Example:
html
<!DOCTYPE html><html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> <title>Bootstrap | Tables</title> <style> h1{ color: green; text-align: center; } div{ margin-top: 10px; } </style> </head> <body> <div class="container"> <h1>GeeksForGeeks</h1> <!-- table, table-sm --> <table class="table table-sm"> <thead> <tr> <th scope="col">S. No.</td> <th scope="col">Name</td> <th scope="col">City</td> <th scope="col">Age</td> </tr> </thead> <tbody> <tr> <th scope="row">1</td> <td>Ajay</td> <td>Patna</td> <td>20</td> </tr> <tr> <th scope="row">2</td> <td>Rahul</td> <td>Chandigarh</td> <td>17</td> </tr> <tr> <th scope="row">3</td> <td>Parush</td> <td>Kolkata</td> <td>22</td> </tr> </tbody> </table> <!-- table, table-sm, table-dark --> <table class="table table-sm table-dark"> <thead> <tr> <th scope="col">S. No.</td> <th scope="col">Name</td> <th scope="col">City</td> <th scope="col">Age</td> </tr> </thead> <tbody> <tr> <th scope="row">1</td> <td>Ajay</td> <td>Patna</td> <td>20</td> </tr> <tr> <th scope="row">2</td> <td>Rahul</td> <td>Chandigarh</td> <td>17</td> </tr> <tr> <th scope="row">3</td> <td>Parush</td> <td>Kolkata</td> <td>22</td> </tr> </tbody> </table> </div> </body></html>
Output:
Colored table: Bootstrap provides us a number of contextual classes that can be used to color the entire row or a single cell of table. These classes should be used with the light table and not with the dark table for better appearance. To color dark tables, we can use the background color classes of Bootstrap. The contextual classes are given below. See the example for illustration.
html
<!DOCTYPE html><html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> <title>Bootstrap | Tables</title> <style> h1{ color: green; text-align: center; } div{ margin-top: 10px; } </style> </head> <body> <div class="container"> <h1>GeeksForGeeks</h1> <!-- table, table-primary, table-warning, table-danger --> <table class="table"> <thead> <tr> <th scope="col">S. No.</td> <th scope="col">Name</td> <th scope="col">City</td> <th scope="col">Age</td> </tr> </thead> <tbody> <tr class="table-primary"> <th scope="row">1</td> <td>Ajay</td> <td>Patna</td> <td>20</td> </tr> <tr class="table-warning"> <th scope="row">2</td> <td>Rahul</td> <td>Chandigarh</td> <td>17</td> </tr> <tr class="table-danger"> <th scope="row">3</td> <td>Parush</td> <td>Kolkata</td> <td>22</td> </tr> </tbody> </table> <!-- table, bg-danger, bg-primary, table-dark --> <table class="table table-dark"> <thead> <tr> <th scope="col">S. No.</td> <th scope="col">Name</td> <th scope="col">City</td> <th scope="col">Age</td> </tr> </thead> <tbody> <tr class="bg-danger"> <th scope="row">1</td> <td>Ajay</td> <td>Patna</td> <td>20</td> </tr> <tr> <th scope="row">2</td> <td>Rahul</td> <td>Chandigarh</td> <td>17</td> </tr> <tr class="bg-primary"> <th scope="row">3</td> <td>Parush</td> <td>Kolkata</td> <td>22</td> </tr> </tbody> </table> </div> </body></html>
Output:
Responsive tables: To make the table responsive on all viewport size, wrap the table within a opening and closing <div> tags, having class table-responsive within the opening <div> tag. Similarly, to make the table responsive depending upon the viewport size, we use the class table-responsive{-sm|-md|-lg|-xl}, according to the viewport size according to which we want to make our table responsive.In responsive tables, a horizontal scroll bar will appear if the table does not fit within the viewport of current size.In case of viewport specific responsive table, table will become responsive if the viewport size is less than the viewport specified by the class table-responsive{-sm|-md|-lg|-xl}. See the examples below for illustration.Example 1: table-responsive
html
<!DOCTYPE html><html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> <title>Bootstrap | Tables</title> <style> h1{ color: green; text-align: center; } div{ margin-top: 10px; } </style> </head> <body> <div class="container"> <h1>GeeksForGeeks</h1> <!-- table-responsive --> <div class="table-responsive"> <!-- table --> <table class="table"> <thead> <tr> <th scope="col">Head</td> <th scope="col">Head</td> <th scope="col">Head</td> <th scope="col">Head</td> <th scope="col">Head</td> <th scope="col">Head</td> <th scope="col">Head</td> <th scope="col">Head</td> <th scope="col">Head</td> <th scope="col">Head</td> <th scope="col">Head</td> <th scope="col">Head</td> </tr> </thead> <tbody> <tr> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> </tr> <tr> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> </tr> <tr> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> </tr> </tbody> </table> </div> </div> </body></html>
Output:
Example 2: table-responsive-md
html
<!DOCTYPE html><html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> <title>Bootstrap | Tables</title> <style> h1{ color: green; text-align: center; } div{ margin-top: 10px; } </style> </head> <body> <div class="container"> <h1>GeeksForGeeks</h1> <!-- table-responsive-md --> <div class="table-responsive-md"> <!-- table --> <table class="table"> <thead> <tr> <th scope="col">Head</td> <th scope="col">Head</td> <th scope="col">Head</td> <th scope="col">Head</td> <th scope="col">Head</td> <th scope="col">Head</td> <th scope="col">Head</td> <th scope="col">Head</td> <th scope="col">Head</td> <th scope="col">Head</td> <th scope="col">Head</td> <th scope="col">Head</td> </tr> </thead> <tbody> <tr> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> </tr> <tr> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> </tr> <tr> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> </tr> </tbody> </table> </div> </div> </body></html>
Output:
Supported Browser:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
ysachin2314
Bootstrap
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to change navigation bar color in Bootstrap ?
Form validation using jQuery
How to pass data into a bootstrap modal?
How to align navbar items to the right in Bootstrap 4 ?
How to Show Images on Click using HTML ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 28440,
"s": 28412,
"text": "\n15 Jul, 2021"
},
{
"code": null,
"e": 28712,
"s": 28440,
"text": "Bootstrap provides us series of classes that can be used to apply various styling to tables such as changing the heading appearance, making the rows striped, adding or removing borders, making rows hoverable. Bootstrap also provides classes for making tables responsive. "
},
{
"code": null,
"e": 29037,
"s": 28712,
"text": "Borderless table: To make the table borderless use the class table-borderless along with the class table class within the <table> tag. We can also make the dark table borderless by using the combination of classes table, table-dark and table-borderless within the <table> tag. See the example below for illustration.Example:"
},
{
"code": null,
"e": 29042,
"s": 29037,
"text": "html"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <!-- Required meta tags --> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\"> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css\" integrity=\"sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS\" crossorigin=\"anonymous\"> <title>Bootstrap | Tables</title> <style> h1{ color: green; text-align: center; } div{ margin-top: 10px; } </style> </head> <body> <div class=\"container\"> <h1>GeeksForGeeks</h1> <!-- table, table-borderless --> <table class=\"table table-borderless\"> <thead> <tr> <th scope=\"col\">S. No.</td> <th scope=\"col\">Name</td> <th scope=\"col\">City</td> <th scope=\"col\">Age</td> </tr> </thead> <tbody> <tr> <th scope=\"row\">1</td> <td>Ajay</td> <td>Patna</td> <td>20</td> </tr> <tr> <th scope=\"row\">2</td> <td>Rahul</td> <td>Chandigarh</td> <td>17</td> </tr> <tr> <th scope=\"row\">3</td> <td>Parush</td> <td>Kolkata</td> <td>22</td> </tr> </tbody> </table> <!-- table, table-borderless, table-dark --> <table class=\"table table-borderless table-dark\"> <thead> <tr> <th scope=\"col\">S. No.</td> <th scope=\"col\">Name</td> <th scope=\"col\">City</td> <th scope=\"col\">Age</td> </tr> </thead> <tbody> <tr> <th scope=\"row\">1</td> <td>Ajay</td> <td>Patna</td> <td>20</td> </tr> <tr> <th scope=\"row\">2</td> <td>Rahul</td> <td>Chandigarh</td> <td>17</td> </tr> <tr> <th scope=\"row\">3</td> <td>Parush</td> <td>Kolkata</td> <td>22</td> </tr> </tbody> </table> </div> </body></html>",
"e": 31278,
"s": 29042,
"text": null
},
{
"code": null,
"e": 31287,
"s": 31278,
"text": "Output: "
},
{
"code": null,
"e": 31607,
"s": 31287,
"text": "Hoverable table: To make the rows of table hoverable use the class table-hover along with the class table within the <table> tag. We can also make the rows of dark table hoverable using the combination of classes table, table-hover, and table-dark within the <table> tag. See the example below for illustration.Example:"
},
{
"code": null,
"e": 31612,
"s": 31607,
"text": "html"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <!-- Required meta tags --> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\"> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css\" integrity=\"sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS\" crossorigin=\"anonymous\"> <title>Bootstrap | Tables</title> <style> h1{ color: green; text-align: center; } div{ margin-top: 10px; } </style> </head> <body> <div class=\"container\"> <h1>GeeksForGeeks</h1> <!-- table, table-hover --> <table class=\"table table-hover\"> <thead> <tr> <th scope=\"col\">S. No.</td> <th scope=\"col\">Name</td> <th scope=\"col\">City</td> <th scope=\"col\">Age</td> </tr> </thead> <tbody> <tr> <th scope=\"row\">1</td> <td>Ajay</td> <td>Patna</td> <td>20</td> </tr> <tr> <th scope=\"row\">2</td> <td>Rahul</td> <td>Chandigarh</td> <td>17</td> </tr> <tr> <th scope=\"row\">3</td> <td>Parush</td> <td>Kolkata</td> <td>22</td> </tr> </tbody> </table> <!-- table, table-hover, table-dark --> <table class=\"table table-hover table-dark\"> <thead> <tr> <th scope=\"col\">S. No.</td> <th scope=\"col\">Name</td> <th scope=\"col\">City</td> <th scope=\"col\">Age</td> </tr> </thead> <tbody> <tr> <th scope=\"row\">1</td> <td>Ajay</td> <td>Patna</td> <td>20</td> </tr> <tr> <th scope=\"row\">2</td> <td>Rahul</td> <td>Chandigarh</td> <td>17</td> </tr> <tr> <th scope=\"row\">3</td> <td>Parush</td> <td>Kolkata</td> <td>22</td> </tr> </tbody> </table> </div> </body></html>",
"e": 33828,
"s": 31612,
"text": null
},
{
"code": null,
"e": 33837,
"s": 33828,
"text": "Output: "
},
{
"code": null,
"e": 34171,
"s": 33837,
"text": "Small table: To make the table smaller in size use the class table-sm along with the class table within the <table> tag. This reduces the cell padding to half. To make the dark table smaller in size use the combination of classes table, table-sm, and table-dark within the <table> tag. See the example below for illustration.Example:"
},
{
"code": null,
"e": 34176,
"s": 34171,
"text": "html"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <!-- Required meta tags --> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\"> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css\" integrity=\"sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS\" crossorigin=\"anonymous\"> <title>Bootstrap | Tables</title> <style> h1{ color: green; text-align: center; } div{ margin-top: 10px; } </style> </head> <body> <div class=\"container\"> <h1>GeeksForGeeks</h1> <!-- table, table-sm --> <table class=\"table table-sm\"> <thead> <tr> <th scope=\"col\">S. No.</td> <th scope=\"col\">Name</td> <th scope=\"col\">City</td> <th scope=\"col\">Age</td> </tr> </thead> <tbody> <tr> <th scope=\"row\">1</td> <td>Ajay</td> <td>Patna</td> <td>20</td> </tr> <tr> <th scope=\"row\">2</td> <td>Rahul</td> <td>Chandigarh</td> <td>17</td> </tr> <tr> <th scope=\"row\">3</td> <td>Parush</td> <td>Kolkata</td> <td>22</td> </tr> </tbody> </table> <!-- table, table-sm, table-dark --> <table class=\"table table-sm table-dark\"> <thead> <tr> <th scope=\"col\">S. No.</td> <th scope=\"col\">Name</td> <th scope=\"col\">City</td> <th scope=\"col\">Age</td> </tr> </thead> <tbody> <tr> <th scope=\"row\">1</td> <td>Ajay</td> <td>Patna</td> <td>20</td> </tr> <tr> <th scope=\"row\">2</td> <td>Rahul</td> <td>Chandigarh</td> <td>17</td> </tr> <tr> <th scope=\"row\">3</td> <td>Parush</td> <td>Kolkata</td> <td>22</td> </tr> </tbody> </table> </div> </body></html>",
"e": 36380,
"s": 34176,
"text": null
},
{
"code": null,
"e": 36388,
"s": 36380,
"text": "Output:"
},
{
"code": null,
"e": 36776,
"s": 36388,
"text": "Colored table: Bootstrap provides us a number of contextual classes that can be used to color the entire row or a single cell of table. These classes should be used with the light table and not with the dark table for better appearance. To color dark tables, we can use the background color classes of Bootstrap. The contextual classes are given below. See the example for illustration. "
},
{
"code": null,
"e": 36781,
"s": 36776,
"text": "html"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <!-- Required meta tags --> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\"> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css\" integrity=\"sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS\" crossorigin=\"anonymous\"> <title>Bootstrap | Tables</title> <style> h1{ color: green; text-align: center; } div{ margin-top: 10px; } </style> </head> <body> <div class=\"container\"> <h1>GeeksForGeeks</h1> <!-- table, table-primary, table-warning, table-danger --> <table class=\"table\"> <thead> <tr> <th scope=\"col\">S. No.</td> <th scope=\"col\">Name</td> <th scope=\"col\">City</td> <th scope=\"col\">Age</td> </tr> </thead> <tbody> <tr class=\"table-primary\"> <th scope=\"row\">1</td> <td>Ajay</td> <td>Patna</td> <td>20</td> </tr> <tr class=\"table-warning\"> <th scope=\"row\">2</td> <td>Rahul</td> <td>Chandigarh</td> <td>17</td> </tr> <tr class=\"table-danger\"> <th scope=\"row\">3</td> <td>Parush</td> <td>Kolkata</td> <td>22</td> </tr> </tbody> </table> <!-- table, bg-danger, bg-primary, table-dark --> <table class=\"table table-dark\"> <thead> <tr> <th scope=\"col\">S. No.</td> <th scope=\"col\">Name</td> <th scope=\"col\">City</td> <th scope=\"col\">Age</td> </tr> </thead> <tbody> <tr class=\"bg-danger\"> <th scope=\"row\">1</td> <td>Ajay</td> <td>Patna</td> <td>20</td> </tr> <tr> <th scope=\"row\">2</td> <td>Rahul</td> <td>Chandigarh</td> <td>17</td> </tr> <tr class=\"bg-primary\"> <th scope=\"row\">3</td> <td>Parush</td> <td>Kolkata</td> <td>22</td> </tr> </tbody> </table> </div> </body></html>",
"e": 39116,
"s": 36781,
"text": null
},
{
"code": null,
"e": 39124,
"s": 39116,
"text": "Output:"
},
{
"code": null,
"e": 39892,
"s": 39124,
"text": "Responsive tables: To make the table responsive on all viewport size, wrap the table within a opening and closing <div> tags, having class table-responsive within the opening <div> tag. Similarly, to make the table responsive depending upon the viewport size, we use the class table-responsive{-sm|-md|-lg|-xl}, according to the viewport size according to which we want to make our table responsive.In responsive tables, a horizontal scroll bar will appear if the table does not fit within the viewport of current size.In case of viewport specific responsive table, table will become responsive if the viewport size is less than the viewport specified by the class table-responsive{-sm|-md|-lg|-xl}. See the examples below for illustration.Example 1: table-responsive"
},
{
"code": null,
"e": 39897,
"s": 39892,
"text": "html"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <!-- Required meta tags --> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\"> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css\" integrity=\"sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS\" crossorigin=\"anonymous\"> <title>Bootstrap | Tables</title> <style> h1{ color: green; text-align: center; } div{ margin-top: 10px; } </style> </head> <body> <div class=\"container\"> <h1>GeeksForGeeks</h1> <!-- table-responsive --> <div class=\"table-responsive\"> <!-- table --> <table class=\"table\"> <thead> <tr> <th scope=\"col\">Head</td> <th scope=\"col\">Head</td> <th scope=\"col\">Head</td> <th scope=\"col\">Head</td> <th scope=\"col\">Head</td> <th scope=\"col\">Head</td> <th scope=\"col\">Head</td> <th scope=\"col\">Head</td> <th scope=\"col\">Head</td> <th scope=\"col\">Head</td> <th scope=\"col\">Head</td> <th scope=\"col\">Head</td> </tr> </thead> <tbody> <tr> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> </tr> <tr> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> </tr> <tr> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> </tr> </tbody> </table> </div> </div> </body></html>",
"e": 42408,
"s": 39897,
"text": null
},
{
"code": null,
"e": 42416,
"s": 42408,
"text": "Output:"
},
{
"code": null,
"e": 42447,
"s": 42416,
"text": "Example 2: table-responsive-md"
},
{
"code": null,
"e": 42452,
"s": 42447,
"text": "html"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <!-- Required meta tags --> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\"> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css\" integrity=\"sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS\" crossorigin=\"anonymous\"> <title>Bootstrap | Tables</title> <style> h1{ color: green; text-align: center; } div{ margin-top: 10px; } </style> </head> <body> <div class=\"container\"> <h1>GeeksForGeeks</h1> <!-- table-responsive-md --> <div class=\"table-responsive-md\"> <!-- table --> <table class=\"table\"> <thead> <tr> <th scope=\"col\">Head</td> <th scope=\"col\">Head</td> <th scope=\"col\">Head</td> <th scope=\"col\">Head</td> <th scope=\"col\">Head</td> <th scope=\"col\">Head</td> <th scope=\"col\">Head</td> <th scope=\"col\">Head</td> <th scope=\"col\">Head</td> <th scope=\"col\">Head</td> <th scope=\"col\">Head</td> <th scope=\"col\">Head</td> </tr> </thead> <tbody> <tr> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> </tr> <tr> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> </tr> <tr> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> <td>Data</td> </tr> </tbody> </table> </div> </div> </body></html>",
"e": 44969,
"s": 42452,
"text": null
},
{
"code": null,
"e": 44977,
"s": 44969,
"text": "Output:"
},
{
"code": null,
"e": 44996,
"s": 44977,
"text": "Supported Browser:"
},
{
"code": null,
"e": 45010,
"s": 44996,
"text": "Google Chrome"
},
{
"code": null,
"e": 45028,
"s": 45010,
"text": "Internet Explorer"
},
{
"code": null,
"e": 45036,
"s": 45028,
"text": "Firefox"
},
{
"code": null,
"e": 45042,
"s": 45036,
"text": "Opera"
},
{
"code": null,
"e": 45050,
"s": 45042,
"text": "Safari "
},
{
"code": null,
"e": 45064,
"s": 45052,
"text": "ysachin2314"
},
{
"code": null,
"e": 45074,
"s": 45064,
"text": "Bootstrap"
},
{
"code": null,
"e": 45091,
"s": 45074,
"text": "Web Technologies"
},
{
"code": null,
"e": 45189,
"s": 45091,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 45198,
"s": 45189,
"text": "Comments"
},
{
"code": null,
"e": 45211,
"s": 45198,
"text": "Old Comments"
},
{
"code": null,
"e": 45261,
"s": 45211,
"text": "How to change navigation bar color in Bootstrap ?"
},
{
"code": null,
"e": 45290,
"s": 45261,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 45331,
"s": 45290,
"text": "How to pass data into a bootstrap modal?"
},
{
"code": null,
"e": 45387,
"s": 45331,
"text": "How to align navbar items to the right in Bootstrap 4 ?"
},
{
"code": null,
"e": 45428,
"s": 45387,
"text": "How to Show Images on Click using HTML ?"
},
{
"code": null,
"e": 45470,
"s": 45428,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 45503,
"s": 45470,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 45565,
"s": 45503,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 45608,
"s": 45565,
"text": "How to fetch data from an API in ReactJS ?"
}
]
|
Convert.ToInt16 Method in C# | Convert a specified value to a 16-bit signed integer using the Convert.ToInt16 method in C#.
We have a double variable with a value initialized to it.
double doubleNum = 3.456;
Now, let us convert it to Int16 i.e. short.
short shortNum;
shortNum = Convert.ToInt16(doubleNum);
Here is the complete example −
Live Demo
using System;
public class Demo {
public static void Main() {
double doubleNum = 3.456;
short shortNum;
shortNum = Convert.ToInt16(doubleNum);
Console.WriteLine("Converted {0} to {1}", doubleNum, shortNum);
}
}
Converted 3.456 to 3 | [
{
"code": null,
"e": 1155,
"s": 1062,
"text": "Convert a specified value to a 16-bit signed integer using the Convert.ToInt16 method in C#."
},
{
"code": null,
"e": 1213,
"s": 1155,
"text": "We have a double variable with a value initialized to it."
},
{
"code": null,
"e": 1239,
"s": 1213,
"text": "double doubleNum = 3.456;"
},
{
"code": null,
"e": 1283,
"s": 1239,
"text": "Now, let us convert it to Int16 i.e. short."
},
{
"code": null,
"e": 1338,
"s": 1283,
"text": "short shortNum;\nshortNum = Convert.ToInt16(doubleNum);"
},
{
"code": null,
"e": 1369,
"s": 1338,
"text": "Here is the complete example −"
},
{
"code": null,
"e": 1380,
"s": 1369,
"text": " Live Demo"
},
{
"code": null,
"e": 1621,
"s": 1380,
"text": "using System;\npublic class Demo {\n public static void Main() {\n double doubleNum = 3.456;\n short shortNum;\n shortNum = Convert.ToInt16(doubleNum);\n Console.WriteLine(\"Converted {0} to {1}\", doubleNum, shortNum);\n }\n}"
},
{
"code": null,
"e": 1642,
"s": 1621,
"text": "Converted 3.456 to 3"
}
]
|
“MRMR” Explained Exactly How You Wished Someone Explained to You | by Samuele Mazzanti | Towards Data Science | MRMR (acronym for Maximum Relevance — Minimum Redundancy) is a feature selection algorithm that has gained new popularity after the pubblication — in 2019 — of this paper by Uber engineers:
The authors show how — thanks to MRMR — they achieved great results in automating feature selection in various marketing applications, among which:
user acquisition,
cross/up-selling,
user churn and reactivation.
However, MRMR is not a recent discovery. It was first proposed in this paper published in 2005 by two Berkeley researchers:
The authors claim that, out of tens of thousands of genes, selecting just few of them (for instance 50) is sufficient for achieving the maximum level of accuracy for the task (predicting a disease). So the point is: how do we find the 50 lucky ones? This is exactly what MRMR was originally designed for.
From these first two examples, it’s evident how flexible is MRMR, which can prove useful in completely different domains, from marketing to genomics.
In this article we will see how MRMR works, and how it is different from other popular feature selection algorithms like Boruta (if you want to know more about Boruta, I’ve written a dedicated post: Boruta Explained Exactly How You Wished Someone Explained to You)
Feature selection algorithms can be broadly classified in two categories:
minimal-optimal (such as MRMR);
all-relevant (such as Boruta).
Minimal-optimal methods seek to identify a small set of features that — put together — have the maximum possible predictive power. On the other hand, all-relevant algorithms are designed to select all the features that — individually — have any predictive power at all.
Thus, if feature A and feature B are both relevant, but they bring more or less the same information, an all-relevant method will select them both, whereas a minimal-optimal method will select only one of them and discard the other one.
This may seem a suble distinction, but it makes a huge difference in practice. Imagine a scenario in which we have 10 thousand features. You use Boruta and you find out that 5 thousand of them have some kind of relationship with the target variable. But 5 thousand is still an unmanageable number of features.
In the example brought by Ding and Peng, you could likely achieve the same (or often higher) accuracy with a far smaller model, for instance 50 features. But, how to choose them? Taking the top 50 features from Boruta doesn’t work. In fact, many of them may be highly correlated with each other: they wouldn’t add much information.
MRMR was developed to overcome this issue.
Let’s take a toy example. Say that our task is to predict the income of some people, knowing some of their (or their relatives’) characteristics. We dispose of these features:
Let’s also imagine that we know the causal relationships between the variables (this is a privilege that we don’t have often in real life, however it’s useful for understanding the logic behind MRMR).
Knowing the causal network would make feature selection ridiculously easy: we would choose {Age, IQ, Height}, since these are the only ones that have a direct causal relationship with the target variable. Adding any of the others would throw in unnecessary noise.
However, these are not necessarily the features that — taken individually — have the strongest predictive value with respect to the target variable. This is summarised by saying that:
“The best K features are not the K best features.” (Adapted from T. M. Cover).
What does this mean?
For instance, take Mother’s IQ: it’s not directly linked to Income, but it’s linked with IQ that is, in turn, heavily linked to Income. So, if you test it, you will find a quite strong relationship between Mother’s IQ and Income. But since we have already IQ in our model, there’s no point in keeping also Mother’s IQ.
In general terms, this implies that it’s not enough to look at individual measures of association between each feature and the target variable.
We wish to find the best K features, not the K best features!
This is exactly the problem with Boruta: it provides an individual evaluation for each feature. Indeed, in our example, Boruta would select all the 7 features, since all of them have some statistical dependence with Income.
And this could make sense in cases where we don’t have too many features. But, in real applications, it often happens that:
we don’t know the causal relationships linking the features and the target variable;
we have too many features;
there is high redundancy within the features.
In these cases, it may be that an all-relevant algorithm such as Boruta is too “indulgent”, whereas MRMR is capable of removing unnecessary features.
So, now the question is: how does MRMR work?
When using MRMR, you are basically required to make only one choice: deciding the number of features that you want to keep. We will call this number K. In our example, we will take K=3.
In real applications, one can choose K based on domain knowledge or other constraints, such as model capacity, machine memory or time available.
MRMR works iteratively. At each iteration, it identifies the best feature (according to a rule) and adds it to the basket of selected features. Once a feature goes into the bucket, it cannot ever come out.
In our example, these are the outcomes that we would get at the end of each iteration:
What is the rule that determines the choice of the “Best” feature at each iteration — namely IQ at step 1, Age at step 2 and Height at step 3? This is the core of MRMR.
“Maximum Relevance - Minimum Redundancy” is so called because — at each iteration — we want to select the feature that has maximum relevance with respect to the target variable and minimum redundancy with respect to the features that have been selected at previous iterations.
In practice, at each iteration i, a score is computed for each feature to be evaluated (f):
The best feature at iteration i is the one having the highest score. As simple as that.
The only question now is how to calculate the numerator and the denominator. Based on this decision, the authors of Uber paper identify many variants of MRMR, such as MID, MIQ, FCD, FCQ, FRQ, RFCQ and RFRQ. However:
Since FCQ is embarassingly simple and fast and works generally better than the other algorithms, I will focus on this variant (by the way, extending to other variants is straightforward).
The relevance of a feature f at the i-th iteration (numerator) is computed as the F-statistic between the feature and the target variable (here to know more about the F-test). The redundancy (denominator) is computed as the average (Pearson) correlation between the feature and all the features that have been selected at previous iterations. So, the formula becomes:
where i is the i-th iteration, f is the feature that is being evaluated, F is F-statistic and corr is Pearson correlation. Note that correlation is taken in absolute value. In fact, if two features have correlation .9 or -.9 it makes no difference: in both cases they are highly redundant.
To make things even more explicit, imagine that we are at the 3rd iteration. This is what happened previously:
IQ has been selected at the 1st iteration;
Age has been selected at the 2nd iteration.
Which feature should we select next?
All we need to compute the score of each feature are the F-statistics and the correlations:
As we said above, the next best feature is the one with the highest score, in this case Height.
The iterative process that we have described above is easily implemented in Python:
This implementation is very easy to understand. However, it is suboptimal. Can you figure out why?
In the code above, we are calculating a lot of correlations that we will never use. In fact, at line 6, we are processing all the possible pairs of features. This means F * (F - 1) / 2 pairs. For F = 10,000, this would mean 50 million correlations!
We could save much more time by processing only the pairs of features that we need at each iteration, i.e. computing correlations “as we go”. This can save us a lot of time.
After all, at each iteration, we only need to compute all the correlations between the feature selected at the previous iteration and all the features that have never been selected, and store them in a correlation matrix. This means:
1st iteration: no correlations needed. In fact, no feature has been selected yet: it’s enough to select the feature having the highest score (i.e. the highest F-statistic).
2nd iteration: F - 1 correlations needed.
3rd iteration: F - 2 correlations needed.
...
Kth iteration: F - K + 1 correlations needed.
Now, doing the math is easy: this procedure requires to compute less than F * (K - 1) correlations. If F=10,000 and K=50, this leads to a much more reasonable number: less than 500 thousand correlations.
This improved version would look like this:
This is almost equivalent to the previous version, except for lines 11 and 21 – 23.
You can find a ready-to-use version of MRMR for classification problems in my Github. It can be installed through:
pip install mrmr_selection
This is a snippet of how you can use it on a Pandas dataframe:
from mrmr import mrmr_classiffrom sklearn.datasets import make_classification# create some dataX, y = make_classification(n_samples = 1000, n_features = 50, n_informative = 10, n_redundant = 40)X = pd.DataFrame(X)y = pd.Series(y)# use mrmr classificationselected_features = mrmr_classif(X, y, K = 10)
We have seen why MRMR is a useful feature selection step in many practical problems: because it tries to find a small set of features that are relevant with respect to the target variable and are scarcely redundant with each other.
MRMR is valuable not only because it is effective (as proved in Uber paper), but also because its simplicity makes it fast and easily implementable in any pipeline.
Thank you for reading! I hope you found this post useful.
I appreciate feedback and constructive criticism. If you want to talk about this article or other related topics, you can text me at my Linkedin contact. | [
{
"code": null,
"e": 237,
"s": 47,
"text": "MRMR (acronym for Maximum Relevance — Minimum Redundancy) is a feature selection algorithm that has gained new popularity after the pubblication — in 2019 — of this paper by Uber engineers:"
},
{
"code": null,
"e": 385,
"s": 237,
"text": "The authors show how — thanks to MRMR — they achieved great results in automating feature selection in various marketing applications, among which:"
},
{
"code": null,
"e": 403,
"s": 385,
"text": "user acquisition,"
},
{
"code": null,
"e": 421,
"s": 403,
"text": "cross/up-selling,"
},
{
"code": null,
"e": 450,
"s": 421,
"text": "user churn and reactivation."
},
{
"code": null,
"e": 574,
"s": 450,
"text": "However, MRMR is not a recent discovery. It was first proposed in this paper published in 2005 by two Berkeley researchers:"
},
{
"code": null,
"e": 879,
"s": 574,
"text": "The authors claim that, out of tens of thousands of genes, selecting just few of them (for instance 50) is sufficient for achieving the maximum level of accuracy for the task (predicting a disease). So the point is: how do we find the 50 lucky ones? This is exactly what MRMR was originally designed for."
},
{
"code": null,
"e": 1029,
"s": 879,
"text": "From these first two examples, it’s evident how flexible is MRMR, which can prove useful in completely different domains, from marketing to genomics."
},
{
"code": null,
"e": 1294,
"s": 1029,
"text": "In this article we will see how MRMR works, and how it is different from other popular feature selection algorithms like Boruta (if you want to know more about Boruta, I’ve written a dedicated post: Boruta Explained Exactly How You Wished Someone Explained to You)"
},
{
"code": null,
"e": 1368,
"s": 1294,
"text": "Feature selection algorithms can be broadly classified in two categories:"
},
{
"code": null,
"e": 1400,
"s": 1368,
"text": "minimal-optimal (such as MRMR);"
},
{
"code": null,
"e": 1431,
"s": 1400,
"text": "all-relevant (such as Boruta)."
},
{
"code": null,
"e": 1701,
"s": 1431,
"text": "Minimal-optimal methods seek to identify a small set of features that — put together — have the maximum possible predictive power. On the other hand, all-relevant algorithms are designed to select all the features that — individually — have any predictive power at all."
},
{
"code": null,
"e": 1938,
"s": 1701,
"text": "Thus, if feature A and feature B are both relevant, but they bring more or less the same information, an all-relevant method will select them both, whereas a minimal-optimal method will select only one of them and discard the other one."
},
{
"code": null,
"e": 2248,
"s": 1938,
"text": "This may seem a suble distinction, but it makes a huge difference in practice. Imagine a scenario in which we have 10 thousand features. You use Boruta and you find out that 5 thousand of them have some kind of relationship with the target variable. But 5 thousand is still an unmanageable number of features."
},
{
"code": null,
"e": 2580,
"s": 2248,
"text": "In the example brought by Ding and Peng, you could likely achieve the same (or often higher) accuracy with a far smaller model, for instance 50 features. But, how to choose them? Taking the top 50 features from Boruta doesn’t work. In fact, many of them may be highly correlated with each other: they wouldn’t add much information."
},
{
"code": null,
"e": 2623,
"s": 2580,
"text": "MRMR was developed to overcome this issue."
},
{
"code": null,
"e": 2799,
"s": 2623,
"text": "Let’s take a toy example. Say that our task is to predict the income of some people, knowing some of their (or their relatives’) characteristics. We dispose of these features:"
},
{
"code": null,
"e": 3000,
"s": 2799,
"text": "Let’s also imagine that we know the causal relationships between the variables (this is a privilege that we don’t have often in real life, however it’s useful for understanding the logic behind MRMR)."
},
{
"code": null,
"e": 3264,
"s": 3000,
"text": "Knowing the causal network would make feature selection ridiculously easy: we would choose {Age, IQ, Height}, since these are the only ones that have a direct causal relationship with the target variable. Adding any of the others would throw in unnecessary noise."
},
{
"code": null,
"e": 3448,
"s": 3264,
"text": "However, these are not necessarily the features that — taken individually — have the strongest predictive value with respect to the target variable. This is summarised by saying that:"
},
{
"code": null,
"e": 3527,
"s": 3448,
"text": "“The best K features are not the K best features.” (Adapted from T. M. Cover)."
},
{
"code": null,
"e": 3548,
"s": 3527,
"text": "What does this mean?"
},
{
"code": null,
"e": 3867,
"s": 3548,
"text": "For instance, take Mother’s IQ: it’s not directly linked to Income, but it’s linked with IQ that is, in turn, heavily linked to Income. So, if you test it, you will find a quite strong relationship between Mother’s IQ and Income. But since we have already IQ in our model, there’s no point in keeping also Mother’s IQ."
},
{
"code": null,
"e": 4011,
"s": 3867,
"text": "In general terms, this implies that it’s not enough to look at individual measures of association between each feature and the target variable."
},
{
"code": null,
"e": 4073,
"s": 4011,
"text": "We wish to find the best K features, not the K best features!"
},
{
"code": null,
"e": 4297,
"s": 4073,
"text": "This is exactly the problem with Boruta: it provides an individual evaluation for each feature. Indeed, in our example, Boruta would select all the 7 features, since all of them have some statistical dependence with Income."
},
{
"code": null,
"e": 4421,
"s": 4297,
"text": "And this could make sense in cases where we don’t have too many features. But, in real applications, it often happens that:"
},
{
"code": null,
"e": 4506,
"s": 4421,
"text": "we don’t know the causal relationships linking the features and the target variable;"
},
{
"code": null,
"e": 4533,
"s": 4506,
"text": "we have too many features;"
},
{
"code": null,
"e": 4579,
"s": 4533,
"text": "there is high redundancy within the features."
},
{
"code": null,
"e": 4729,
"s": 4579,
"text": "In these cases, it may be that an all-relevant algorithm such as Boruta is too “indulgent”, whereas MRMR is capable of removing unnecessary features."
},
{
"code": null,
"e": 4774,
"s": 4729,
"text": "So, now the question is: how does MRMR work?"
},
{
"code": null,
"e": 4960,
"s": 4774,
"text": "When using MRMR, you are basically required to make only one choice: deciding the number of features that you want to keep. We will call this number K. In our example, we will take K=3."
},
{
"code": null,
"e": 5105,
"s": 4960,
"text": "In real applications, one can choose K based on domain knowledge or other constraints, such as model capacity, machine memory or time available."
},
{
"code": null,
"e": 5311,
"s": 5105,
"text": "MRMR works iteratively. At each iteration, it identifies the best feature (according to a rule) and adds it to the basket of selected features. Once a feature goes into the bucket, it cannot ever come out."
},
{
"code": null,
"e": 5398,
"s": 5311,
"text": "In our example, these are the outcomes that we would get at the end of each iteration:"
},
{
"code": null,
"e": 5567,
"s": 5398,
"text": "What is the rule that determines the choice of the “Best” feature at each iteration — namely IQ at step 1, Age at step 2 and Height at step 3? This is the core of MRMR."
},
{
"code": null,
"e": 5844,
"s": 5567,
"text": "“Maximum Relevance - Minimum Redundancy” is so called because — at each iteration — we want to select the feature that has maximum relevance with respect to the target variable and minimum redundancy with respect to the features that have been selected at previous iterations."
},
{
"code": null,
"e": 5936,
"s": 5844,
"text": "In practice, at each iteration i, a score is computed for each feature to be evaluated (f):"
},
{
"code": null,
"e": 6024,
"s": 5936,
"text": "The best feature at iteration i is the one having the highest score. As simple as that."
},
{
"code": null,
"e": 6240,
"s": 6024,
"text": "The only question now is how to calculate the numerator and the denominator. Based on this decision, the authors of Uber paper identify many variants of MRMR, such as MID, MIQ, FCD, FCQ, FRQ, RFCQ and RFRQ. However:"
},
{
"code": null,
"e": 6428,
"s": 6240,
"text": "Since FCQ is embarassingly simple and fast and works generally better than the other algorithms, I will focus on this variant (by the way, extending to other variants is straightforward)."
},
{
"code": null,
"e": 6796,
"s": 6428,
"text": "The relevance of a feature f at the i-th iteration (numerator) is computed as the F-statistic between the feature and the target variable (here to know more about the F-test). The redundancy (denominator) is computed as the average (Pearson) correlation between the feature and all the features that have been selected at previous iterations. So, the formula becomes:"
},
{
"code": null,
"e": 7086,
"s": 6796,
"text": "where i is the i-th iteration, f is the feature that is being evaluated, F is F-statistic and corr is Pearson correlation. Note that correlation is taken in absolute value. In fact, if two features have correlation .9 or -.9 it makes no difference: in both cases they are highly redundant."
},
{
"code": null,
"e": 7197,
"s": 7086,
"text": "To make things even more explicit, imagine that we are at the 3rd iteration. This is what happened previously:"
},
{
"code": null,
"e": 7240,
"s": 7197,
"text": "IQ has been selected at the 1st iteration;"
},
{
"code": null,
"e": 7284,
"s": 7240,
"text": "Age has been selected at the 2nd iteration."
},
{
"code": null,
"e": 7321,
"s": 7284,
"text": "Which feature should we select next?"
},
{
"code": null,
"e": 7413,
"s": 7321,
"text": "All we need to compute the score of each feature are the F-statistics and the correlations:"
},
{
"code": null,
"e": 7509,
"s": 7413,
"text": "As we said above, the next best feature is the one with the highest score, in this case Height."
},
{
"code": null,
"e": 7593,
"s": 7509,
"text": "The iterative process that we have described above is easily implemented in Python:"
},
{
"code": null,
"e": 7692,
"s": 7593,
"text": "This implementation is very easy to understand. However, it is suboptimal. Can you figure out why?"
},
{
"code": null,
"e": 7941,
"s": 7692,
"text": "In the code above, we are calculating a lot of correlations that we will never use. In fact, at line 6, we are processing all the possible pairs of features. This means F * (F - 1) / 2 pairs. For F = 10,000, this would mean 50 million correlations!"
},
{
"code": null,
"e": 8115,
"s": 7941,
"text": "We could save much more time by processing only the pairs of features that we need at each iteration, i.e. computing correlations “as we go”. This can save us a lot of time."
},
{
"code": null,
"e": 8349,
"s": 8115,
"text": "After all, at each iteration, we only need to compute all the correlations between the feature selected at the previous iteration and all the features that have never been selected, and store them in a correlation matrix. This means:"
},
{
"code": null,
"e": 8522,
"s": 8349,
"text": "1st iteration: no correlations needed. In fact, no feature has been selected yet: it’s enough to select the feature having the highest score (i.e. the highest F-statistic)."
},
{
"code": null,
"e": 8564,
"s": 8522,
"text": "2nd iteration: F - 1 correlations needed."
},
{
"code": null,
"e": 8606,
"s": 8564,
"text": "3rd iteration: F - 2 correlations needed."
},
{
"code": null,
"e": 8610,
"s": 8606,
"text": "..."
},
{
"code": null,
"e": 8656,
"s": 8610,
"text": "Kth iteration: F - K + 1 correlations needed."
},
{
"code": null,
"e": 8860,
"s": 8656,
"text": "Now, doing the math is easy: this procedure requires to compute less than F * (K - 1) correlations. If F=10,000 and K=50, this leads to a much more reasonable number: less than 500 thousand correlations."
},
{
"code": null,
"e": 8904,
"s": 8860,
"text": "This improved version would look like this:"
},
{
"code": null,
"e": 8988,
"s": 8904,
"text": "This is almost equivalent to the previous version, except for lines 11 and 21 – 23."
},
{
"code": null,
"e": 9103,
"s": 8988,
"text": "You can find a ready-to-use version of MRMR for classification problems in my Github. It can be installed through:"
},
{
"code": null,
"e": 9130,
"s": 9103,
"text": "pip install mrmr_selection"
},
{
"code": null,
"e": 9193,
"s": 9130,
"text": "This is a snippet of how you can use it on a Pandas dataframe:"
},
{
"code": null,
"e": 9494,
"s": 9193,
"text": "from mrmr import mrmr_classiffrom sklearn.datasets import make_classification# create some dataX, y = make_classification(n_samples = 1000, n_features = 50, n_informative = 10, n_redundant = 40)X = pd.DataFrame(X)y = pd.Series(y)# use mrmr classificationselected_features = mrmr_classif(X, y, K = 10)"
},
{
"code": null,
"e": 9726,
"s": 9494,
"text": "We have seen why MRMR is a useful feature selection step in many practical problems: because it tries to find a small set of features that are relevant with respect to the target variable and are scarcely redundant with each other."
},
{
"code": null,
"e": 9891,
"s": 9726,
"text": "MRMR is valuable not only because it is effective (as proved in Uber paper), but also because its simplicity makes it fast and easily implementable in any pipeline."
},
{
"code": null,
"e": 9949,
"s": 9891,
"text": "Thank you for reading! I hope you found this post useful."
}
]
|
How to write your own header file in C?
| Here we will see how to create own header file using C. To make a header file, we have to create one file with a name, and extension should be (*.h). In that function there will be no main() function. In that file, we can put some variables, some functions etc.
To use that header file, it should be present at the same directory, where the program is located. Now using #include we have to put the header file name. The name will be inside double quotes. Include syntax will be look like this.
#include”header_file.h”
Let us see one program to get the idea.
int MY_VAR = 10;
int add(int x, int y){
return x + y;
}
int sub(int x, int y){
return x - y;
}
int mul(int x, int y){
return x * y;
}
int negate(int x){
return -x;
}
#include <stdio.h>
#include "my_header.h"
main(void) {
printf("The value of My_VAR: %d\n", MY_VAR);
printf("The value of (50 + 84): %d\n", add(50, 84));
printf("The value of (65 - 23): %d\n", sub(65, 23));
printf("The value of (3 * 15): %d\n", mul(3, 15));
printf("The negative of 15: %d\n", negate(15));
}
The value of My_VAR: 10
The value of (50 + 84): 134
The value of (65 - 23): 42
The value of (3 * 15): 45
The negative of 15: -15 | [
{
"code": null,
"e": 1324,
"s": 1062,
"text": "Here we will see how to create own header file using C. To make a header file, we have to create one file with a name, and extension should be (*.h). In that function there will be no main() function. In that file, we can put some variables, some functions etc."
},
{
"code": null,
"e": 1557,
"s": 1324,
"text": "To use that header file, it should be present at the same directory, where the program is located. Now using #include we have to put the header file name. The name will be inside double quotes. Include syntax will be look like this."
},
{
"code": null,
"e": 1581,
"s": 1557,
"text": "#include”header_file.h”"
},
{
"code": null,
"e": 1621,
"s": 1581,
"text": "Let us see one program to get the idea."
},
{
"code": null,
"e": 1799,
"s": 1621,
"text": "int MY_VAR = 10;\nint add(int x, int y){\n return x + y;\n}\nint sub(int x, int y){\n return x - y;\n}\nint mul(int x, int y){\n return x * y;\n}\nint negate(int x){\n return -x;\n}"
},
{
"code": null,
"e": 2121,
"s": 1799,
"text": "#include <stdio.h>\n#include \"my_header.h\"\nmain(void) {\n printf(\"The value of My_VAR: %d\\n\", MY_VAR);\n printf(\"The value of (50 + 84): %d\\n\", add(50, 84));\n printf(\"The value of (65 - 23): %d\\n\", sub(65, 23));\n printf(\"The value of (3 * 15): %d\\n\", mul(3, 15));\n printf(\"The negative of 15: %d\\n\", negate(15));\n}"
},
{
"code": null,
"e": 2250,
"s": 2121,
"text": "The value of My_VAR: 10\nThe value of (50 + 84): 134\nThe value of (65 - 23): 42\nThe value of (3 * 15): 45\nThe negative of 15: -15"
}
]
|
CSS Margins and Padding - GeeksforGeeks | 05 Apr, 2022
In this article, we will learn about the CSS Margin & Padding properties of the Box Model & understand their implementation through the example.
CSS Margins: CSS margins are used to create space around the element. We can set the different sizes of margins for individual sides(top, right, bottom, left).
Margin properties can have the following values:
Length in cm, px, pt, etc.
Width % of the element.
Margin calculated by the browser: auto.
Syntax:
body
{
margin: size;
}
The margin property is a shorthand property having the following individual margin properties:
margin-top: It is used to set the top margin of an element.
margin-right: It is used to set the right margin of an element.
margin-bottom: It is used to specify the amount of margin to be used on the bottom of an element.
margin-left: It is used to set the width of the margin on the left of the desired element.
Note: The margin property allows the negative values.
We will discuss all 4 properties sequentially.
If the margin property has 4 values:
margin: 40px 100px 120px 80px;
top = 40px
right = 100px
bottom = 120px
left = 80px
Example: This example describes the margin property by specifying the four values.
HTML
<html> <head> <style> p { margin: 80px 100px 50px 80px; } </style></head> <body> <h1> GeekforGeeks </h1> <p> Margin properties </p> </body> </html>
Output:
If the margin property has 3 values:
margin: 40px 100px 120px;
top = 40px
right and left = 100px
bottom = 120px
Example: This example describes the margin property by specifying the three values.
HTML
<html> <head> <style> p { margin: 80px 50px 100px; } </style></head> <body> <h1> GeeksforGeeks </h1> <p> Margin properties </p> </body> </html>
Output:
If the margin property has 2 values:
margin: 40px 100px;
top and bottom = 40px;
left and right = 100px;
Example: This example describes the margin property by specifying the double value.
HTML
<html> <head> <style> p { margin: 100px 150px; } </style></head> <body> <h1> GeeksforGeeks </h1> <p> Margin properties </p> </body> </html>
Output:
If the margin property has 1 value:
margin: 40px;
top, right, bottom and left = 40px
Example: This example describes the margin property by specifying the single value.
HTML
<html> <head> <style> p { margin: 100px; } </style></head> <body> <h1> GeeksforGeeks </h1> <p> Margin properties </p> </body> </html>
Output:
CSS Padding: CSS paddings are used to create space around the element, inside any defined border. We can set different paddings for individual sides(top, right, bottom, left). It is important to add border properties to implement padding properties.
Padding properties can have the following values:
Length in cm, px, pt, etc.
Width % of the element.
Syntax:
body
{
padding: size;
}
The padding CSS shorthand property can be used to specify the padding for each side of an element in the following order:
padding-top: It is used to set the width of the padding area on the top of an element.
padding-right: It is used to set the width of the padding area on the right of an element.
padding-bottom: It is used to set the height of the padding area on the bottom of an element.
padding-left: It is used to set the width of the padding area on the left of an element.
Note: The padding property allows the negative values.
We will discuss all these 4 properties sequentially.
If the padding property has 4 values:
padding: 40px 100px 120px 80px;
top = 40px
right = 100px
bottom = 120px
left = 80px
Example: This example describes the padding property by specifying the 4 values.
HTML
<html> <head> <style> p { padding: 80px 100px 50px 80px; border: 1px solid black; } </style></head> <body> <h1>GeeksforGeeks</h1> <p>Padding properties</p> </body> </html>
Output:
If the padding property has 3 values:
padding: 40px 100px 120px;
top = 40px
right and left = 100px
bottom = 120px
Example: This example describes the padding property by specifying the 3 values.
HTML
<html> <head> <style> p { padding: 80px 50px 100px; border: 1px solid black; } </style></head> <body> <h1>GeeksforGeeks</h1> <p>Padding properties</p> </body> </html>
Output:
If the padding property has 2 values:
padding: 100px 150px;
top and bottom = 100px;
left and right = 150px;
Example: This example describes the padding property using a double value.
HTML
<html> <head> <style> p { padding: 100px 150px; border: 1px solid black; } </style></head> <body> <h1>GeeksforGeeks</h1> <p>Padding properties</p> </body> </html>
Output:
If the padding property has 1 value:
padding: 100px;
top, right, bottom and left = 100px
Example: This example describes the padding property using a single value.
HTML
<html> <head> <style> p { padding: 100px; border: 1px solid black; } </style></head> <body> <h1>GeeksforGeeks</h1> <p>Padding properties</p> </body> </html>
Output:
Difference between Margin and Padding:
Margin is used to create space around elements and padding is used to create space around elements inside the border.
We can set the margin property to auto but we cannot set the padding property to auto.
In Margin property we can allow negative or float number but in padding we cannot allow negative values.
Margin and padding target all 4 sides of the element. Margin and padding will work without the border property also. The difference will be more clear with the following example.
Example: This example describes the margin & padding properties around the content.
HTML
<!DOCTYPE html><html> <head> <style> h2 { margin: 50px; border: 70px solid green; padding: 80px; } </style></head> <body> <h1>GeeksforGeeks</h1> <h2> Padding properties </h2></body> </html>
Output:
Supported Browser:
Google Chrome 1.0
Internet Explorer 3.0
Microsoft Edge 12.0
Firefox 1.0
Opera 3.5
Safari 1.0
ysachin2314
bhaskargeeksforgeeks
itskawal2000
CSS-Basics
CSS
Web Technologies
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 create footer to stay at the bottom of a Web page?
How to update Node.js and NPM to next version ?
CSS to put icon inside an input element in a form
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": 28071,
"s": 28043,
"text": "\n05 Apr, 2022"
},
{
"code": null,
"e": 28217,
"s": 28071,
"text": "In this article, we will learn about the CSS Margin & Padding properties of the Box Model & understand their implementation through the example. "
},
{
"code": null,
"e": 28377,
"s": 28217,
"text": "CSS Margins: CSS margins are used to create space around the element. We can set the different sizes of margins for individual sides(top, right, bottom, left)."
},
{
"code": null,
"e": 28426,
"s": 28377,
"text": "Margin properties can have the following values:"
},
{
"code": null,
"e": 28453,
"s": 28426,
"text": "Length in cm, px, pt, etc."
},
{
"code": null,
"e": 28477,
"s": 28453,
"text": "Width % of the element."
},
{
"code": null,
"e": 28517,
"s": 28477,
"text": "Margin calculated by the browser: auto."
},
{
"code": null,
"e": 28526,
"s": 28517,
"text": "Syntax: "
},
{
"code": null,
"e": 28553,
"s": 28526,
"text": "body\n{\n margin: size;\n}"
},
{
"code": null,
"e": 28648,
"s": 28553,
"text": "The margin property is a shorthand property having the following individual margin properties:"
},
{
"code": null,
"e": 28708,
"s": 28648,
"text": "margin-top: It is used to set the top margin of an element."
},
{
"code": null,
"e": 28772,
"s": 28708,
"text": "margin-right: It is used to set the right margin of an element."
},
{
"code": null,
"e": 28870,
"s": 28772,
"text": "margin-bottom: It is used to specify the amount of margin to be used on the bottom of an element."
},
{
"code": null,
"e": 28961,
"s": 28870,
"text": "margin-left: It is used to set the width of the margin on the left of the desired element."
},
{
"code": null,
"e": 29015,
"s": 28961,
"text": "Note: The margin property allows the negative values."
},
{
"code": null,
"e": 29062,
"s": 29015,
"text": "We will discuss all 4 properties sequentially."
},
{
"code": null,
"e": 29100,
"s": 29062,
"text": "If the margin property has 4 values: "
},
{
"code": null,
"e": 29131,
"s": 29100,
"text": "margin: 40px 100px 120px 80px;"
},
{
"code": null,
"e": 29142,
"s": 29131,
"text": "top = 40px"
},
{
"code": null,
"e": 29156,
"s": 29142,
"text": "right = 100px"
},
{
"code": null,
"e": 29171,
"s": 29156,
"text": "bottom = 120px"
},
{
"code": null,
"e": 29183,
"s": 29171,
"text": "left = 80px"
},
{
"code": null,
"e": 29267,
"s": 29183,
"text": "Example: This example describes the margin property by specifying the four values."
},
{
"code": null,
"e": 29272,
"s": 29267,
"text": "HTML"
},
{
"code": "<html> <head> <style> p { margin: 80px 100px 50px 80px; } </style></head> <body> <h1> GeekforGeeks </h1> <p> Margin properties </p> </body> </html>",
"e": 29461,
"s": 29272,
"text": null
},
{
"code": null,
"e": 29469,
"s": 29461,
"text": "Output:"
},
{
"code": null,
"e": 29507,
"s": 29469,
"text": "If the margin property has 3 values: "
},
{
"code": null,
"e": 29534,
"s": 29507,
"text": "margin: 40px 100px 120px; "
},
{
"code": null,
"e": 29545,
"s": 29534,
"text": "top = 40px"
},
{
"code": null,
"e": 29568,
"s": 29545,
"text": "right and left = 100px"
},
{
"code": null,
"e": 29583,
"s": 29568,
"text": "bottom = 120px"
},
{
"code": null,
"e": 29667,
"s": 29583,
"text": "Example: This example describes the margin property by specifying the three values."
},
{
"code": null,
"e": 29672,
"s": 29667,
"text": "HTML"
},
{
"code": "<html> <head> <style> p { margin: 80px 50px 100px; } </style></head> <body> <h1> GeeksforGeeks </h1> <p> Margin properties </p> </body> </html>",
"e": 29857,
"s": 29672,
"text": null
},
{
"code": null,
"e": 29865,
"s": 29857,
"text": "Output:"
},
{
"code": null,
"e": 29902,
"s": 29865,
"text": "If the margin property has 2 values:"
},
{
"code": null,
"e": 29923,
"s": 29902,
"text": "margin: 40px 100px; "
},
{
"code": null,
"e": 29946,
"s": 29923,
"text": "top and bottom = 40px;"
},
{
"code": null,
"e": 29970,
"s": 29946,
"text": "left and right = 100px;"
},
{
"code": null,
"e": 30055,
"s": 29970,
"text": "Example: This example describes the margin property by specifying the double value."
},
{
"code": null,
"e": 30060,
"s": 30055,
"text": "HTML"
},
{
"code": "<html> <head> <style> p { margin: 100px 150px; } </style></head> <body> <h1> GeeksforGeeks </h1> <p> Margin properties </p> </body> </html>",
"e": 30241,
"s": 30060,
"text": null
},
{
"code": null,
"e": 30249,
"s": 30241,
"text": "Output:"
},
{
"code": null,
"e": 30286,
"s": 30249,
"text": "If the margin property has 1 value: "
},
{
"code": null,
"e": 30301,
"s": 30286,
"text": "margin: 40px; "
},
{
"code": null,
"e": 30336,
"s": 30301,
"text": "top, right, bottom and left = 40px"
},
{
"code": null,
"e": 30420,
"s": 30336,
"text": "Example: This example describes the margin property by specifying the single value."
},
{
"code": null,
"e": 30425,
"s": 30420,
"text": "HTML"
},
{
"code": "<html> <head> <style> p { margin: 100px; } </style></head> <body> <h1> GeeksforGeeks </h1> <p> Margin properties </p> </body> </html>",
"e": 30600,
"s": 30425,
"text": null
},
{
"code": null,
"e": 30608,
"s": 30600,
"text": "Output:"
},
{
"code": null,
"e": 30858,
"s": 30608,
"text": "CSS Padding: CSS paddings are used to create space around the element, inside any defined border. We can set different paddings for individual sides(top, right, bottom, left). It is important to add border properties to implement padding properties."
},
{
"code": null,
"e": 30909,
"s": 30858,
"text": "Padding properties can have the following values: "
},
{
"code": null,
"e": 30936,
"s": 30909,
"text": "Length in cm, px, pt, etc."
},
{
"code": null,
"e": 30960,
"s": 30936,
"text": "Width % of the element."
},
{
"code": null,
"e": 30970,
"s": 30960,
"text": "Syntax: "
},
{
"code": null,
"e": 30998,
"s": 30970,
"text": "body\n{\n padding: size;\n}"
},
{
"code": null,
"e": 31120,
"s": 30998,
"text": "The padding CSS shorthand property can be used to specify the padding for each side of an element in the following order:"
},
{
"code": null,
"e": 31207,
"s": 31120,
"text": "padding-top: It is used to set the width of the padding area on the top of an element."
},
{
"code": null,
"e": 31298,
"s": 31207,
"text": "padding-right: It is used to set the width of the padding area on the right of an element."
},
{
"code": null,
"e": 31392,
"s": 31298,
"text": "padding-bottom: It is used to set the height of the padding area on the bottom of an element."
},
{
"code": null,
"e": 31481,
"s": 31392,
"text": "padding-left: It is used to set the width of the padding area on the left of an element."
},
{
"code": null,
"e": 31536,
"s": 31481,
"text": "Note: The padding property allows the negative values."
},
{
"code": null,
"e": 31589,
"s": 31536,
"text": "We will discuss all these 4 properties sequentially."
},
{
"code": null,
"e": 31628,
"s": 31589,
"text": "If the padding property has 4 values: "
},
{
"code": null,
"e": 31661,
"s": 31628,
"text": "padding: 40px 100px 120px 80px; "
},
{
"code": null,
"e": 31672,
"s": 31661,
"text": "top = 40px"
},
{
"code": null,
"e": 31686,
"s": 31672,
"text": "right = 100px"
},
{
"code": null,
"e": 31701,
"s": 31686,
"text": "bottom = 120px"
},
{
"code": null,
"e": 31713,
"s": 31701,
"text": "left = 80px"
},
{
"code": null,
"e": 31794,
"s": 31713,
"text": "Example: This example describes the padding property by specifying the 4 values."
},
{
"code": null,
"e": 31799,
"s": 31794,
"text": "HTML"
},
{
"code": "<html> <head> <style> p { padding: 80px 100px 50px 80px; border: 1px solid black; } </style></head> <body> <h1>GeeksforGeeks</h1> <p>Padding properties</p> </body> </html>",
"e": 32006,
"s": 31799,
"text": null
},
{
"code": null,
"e": 32014,
"s": 32006,
"text": "Output:"
},
{
"code": null,
"e": 32052,
"s": 32014,
"text": "If the padding property has 3 values:"
},
{
"code": null,
"e": 32080,
"s": 32052,
"text": "padding: 40px 100px 120px; "
},
{
"code": null,
"e": 32091,
"s": 32080,
"text": "top = 40px"
},
{
"code": null,
"e": 32114,
"s": 32091,
"text": "right and left = 100px"
},
{
"code": null,
"e": 32129,
"s": 32114,
"text": "bottom = 120px"
},
{
"code": null,
"e": 32210,
"s": 32129,
"text": "Example: This example describes the padding property by specifying the 3 values."
},
{
"code": null,
"e": 32215,
"s": 32210,
"text": "HTML"
},
{
"code": "<html> <head> <style> p { padding: 80px 50px 100px; border: 1px solid black; } </style></head> <body> <h1>GeeksforGeeks</h1> <p>Padding properties</p> </body> </html>",
"e": 32417,
"s": 32215,
"text": null
},
{
"code": null,
"e": 32425,
"s": 32417,
"text": "Output:"
},
{
"code": null,
"e": 32464,
"s": 32425,
"text": "If the padding property has 2 values: "
},
{
"code": null,
"e": 32487,
"s": 32464,
"text": "padding: 100px 150px; "
},
{
"code": null,
"e": 32511,
"s": 32487,
"text": "top and bottom = 100px;"
},
{
"code": null,
"e": 32535,
"s": 32511,
"text": "left and right = 150px;"
},
{
"code": null,
"e": 32610,
"s": 32535,
"text": "Example: This example describes the padding property using a double value."
},
{
"code": null,
"e": 32615,
"s": 32610,
"text": "HTML"
},
{
"code": "<html> <head> <style> p { padding: 100px 150px; border: 1px solid black; } </style></head> <body> <h1>GeeksforGeeks</h1> <p>Padding properties</p> </body> </html>",
"e": 32813,
"s": 32615,
"text": null
},
{
"code": null,
"e": 32821,
"s": 32813,
"text": "Output:"
},
{
"code": null,
"e": 32858,
"s": 32821,
"text": "If the padding property has 1 value:"
},
{
"code": null,
"e": 32875,
"s": 32858,
"text": "padding: 100px; "
},
{
"code": null,
"e": 32911,
"s": 32875,
"text": "top, right, bottom and left = 100px"
},
{
"code": null,
"e": 32986,
"s": 32911,
"text": "Example: This example describes the padding property using a single value."
},
{
"code": null,
"e": 32991,
"s": 32986,
"text": "HTML"
},
{
"code": "<html> <head> <style> p { padding: 100px; border: 1px solid black; } </style></head> <body> <h1>GeeksforGeeks</h1> <p>Padding properties</p> </body> </html>",
"e": 33183,
"s": 32991,
"text": null
},
{
"code": null,
"e": 33191,
"s": 33183,
"text": "Output:"
},
{
"code": null,
"e": 33230,
"s": 33191,
"text": "Difference between Margin and Padding:"
},
{
"code": null,
"e": 33348,
"s": 33230,
"text": "Margin is used to create space around elements and padding is used to create space around elements inside the border."
},
{
"code": null,
"e": 33435,
"s": 33348,
"text": "We can set the margin property to auto but we cannot set the padding property to auto."
},
{
"code": null,
"e": 33540,
"s": 33435,
"text": "In Margin property we can allow negative or float number but in padding we cannot allow negative values."
},
{
"code": null,
"e": 33719,
"s": 33540,
"text": "Margin and padding target all 4 sides of the element. Margin and padding will work without the border property also. The difference will be more clear with the following example."
},
{
"code": null,
"e": 33803,
"s": 33719,
"text": "Example: This example describes the margin & padding properties around the content."
},
{
"code": null,
"e": 33808,
"s": 33803,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <style> h2 { margin: 50px; border: 70px solid green; padding: 80px; } </style></head> <body> <h1>GeeksforGeeks</h1> <h2> Padding properties </h2></body> </html>",
"e": 34050,
"s": 33808,
"text": null
},
{
"code": null,
"e": 34058,
"s": 34050,
"text": "Output:"
},
{
"code": null,
"e": 34077,
"s": 34058,
"text": "Supported Browser:"
},
{
"code": null,
"e": 34095,
"s": 34077,
"text": "Google Chrome 1.0"
},
{
"code": null,
"e": 34117,
"s": 34095,
"text": "Internet Explorer 3.0"
},
{
"code": null,
"e": 34137,
"s": 34117,
"text": "Microsoft Edge 12.0"
},
{
"code": null,
"e": 34149,
"s": 34137,
"text": "Firefox 1.0"
},
{
"code": null,
"e": 34159,
"s": 34149,
"text": "Opera 3.5"
},
{
"code": null,
"e": 34170,
"s": 34159,
"text": "Safari 1.0"
},
{
"code": null,
"e": 34182,
"s": 34170,
"text": "ysachin2314"
},
{
"code": null,
"e": 34203,
"s": 34182,
"text": "bhaskargeeksforgeeks"
},
{
"code": null,
"e": 34216,
"s": 34203,
"text": "itskawal2000"
},
{
"code": null,
"e": 34227,
"s": 34216,
"text": "CSS-Basics"
},
{
"code": null,
"e": 34231,
"s": 34227,
"text": "CSS"
},
{
"code": null,
"e": 34248,
"s": 34231,
"text": "Web Technologies"
},
{
"code": null,
"e": 34346,
"s": 34248,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34396,
"s": 34346,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 34458,
"s": 34396,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 34516,
"s": 34458,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 34564,
"s": 34516,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 34614,
"s": 34564,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 34656,
"s": 34614,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 34689,
"s": 34656,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 34732,
"s": 34689,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 34782,
"s": 34732,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
]
|
Activation Functions. So why do we need Activation functions... | by Dhaval Dholakia | Towards Data Science | Welcome to my first post! I am a Data Scientist and have been an active reader of Medium blogs. Now, I am planning to use Medium blog to document my journey in learning Deep Learning and share my experiences through the projects I have been working on. Hopefully, by sharing my views on the subjects I can also learn from the fantastic data science/deep learning community on Medium! I would love to hear your feedback on my first post here. With that said, let’s get started ...
The basic idea of how a neural network learns is — We have some input data that we feed it into the network and then we perform a series of linear operations layer by layer and derive an output. In a simple case for a particular layer is that we multiply the input by the weights, add a bias and apply an activation function and pass the output to the next layer. We keep repeating the process until we reach the last layer. The final value is our output. We then compute the error between the “calculated output” and the “true output” and then calculate the partial derivatives of this error with respect to the parameters in each layer going backwards and keep updating the parameters accordingly!
Neural networks are said to be universal function approximators. The main underlying goal of a neural network is to learn complex non-linear functions. If we do not apply any non-linearity in our multi-layer neural network, we are simply trying to seperate the classes using a linear hyperplane. As we know, in the real-world nothing is linear!
Also, imagine we perform simple linear operation as described above, namely; multiply the input by weights, add a bias and sum them across all the inputs arriving to the neuron. It is likely that in certain situations, the output derived above, takes a large value. When, this output is fed into the further layers, they can be transformed to even larger values, making things computationally uncontrollable. This is where the activation functions play a major role i.e. squashing a real-number to a fix interval (e.g. between -1 and 1).
Let us see different types of activation functions and how they compare against each other:
The sigmoid activation function has the mathematical form `sig(z) = 1/ (1 + e^-z)`. As we can see, it basically takes a real valued number as the input and squashes it between 0 and 1. It is often termed as a squashing function as well. It aims to introduce non-linearity in the input space. The non-linearity is where we get the wiggle and the network learns to capture complicated relationships. As we can see from the above mathematical representation, a large negative number passed through the sigmoid function becomes 0 and a large positive number becomes 1. Due to this property, sigmoid function often has a really nice interpretation associated with it as the firing rate of the neuron; from not firing at all (0) to fully-saturated firing at an assumed maximum frequency (1). However, sigmoid activation functions have become less popular over the period of time due to the following two major drawbacks:
Killing gradients:Sigmoid neurons get saturated on the boundaries and hence the local gradients at these regions is almost zero. To give you a more intuitive example to understand this, consider the inputs to the sigmoid function to be +15 and -15. The derivative of sigmoid function is `sig(z) * (1 — sig(z))`. As mentioned above, the large positive values are squashed near 1 and large negative values are squashed near 0. Hence, effectively making the local gradient to near 0. As a result, during backpropagation, this gradient gets multiplied to the gradient of this neurons’ output for the final objective function, hence it will effectively “kill” the gradient and no signal will flow through the neuron to its weights. Also, we have to pay attention to initializing the weights of sigmoid neurons to avoid saturation, because, if the initial weights are too large, then most neurons will get saturated and hence the network will hardly learn.
Non zero-centered outputs:The output is always between 0 and 1, that means that the output after applying sigmoid is always positive hence, during gradient-descent, the gradient on the weights during backpropagation will always be either positive or negative depending on the output of the neuron. As a result, the gradient updates go too far in different directions which makes optimization harder.
The python implementation looks something similar to:
import numpy as npdef sigmoid(z): return 1 / (1 + np.exp(-z))
The tanh or hyperbolic tangent activation function has the mathematical form `tanh(z) = (e^z — e^-z) / (e^z + e^-z)`. It is basically a shifted sigmoid neuron. It basically takes a real valued number and squashes it between -1 and +1. Similar to sigmoid neuron, it saturates at large positive and negative values. However, its output is always zero-centered which helps since the neurons in the later layers of the network would be receiving inputs that are zero-centered. Hence, in practice, tanh activation functions are preffered in hidden layers over sigmoid.
import numpy as npdef tanh(z): return np.tanh(z)
The ReLU or Rectified Linear Unit is represented as `ReLU(z) = max(0, z)`. It basically thresholds the inputs at zero, i.e. all negative values in the input to the ReLU neuron are set to zero. Fairly recently, it has become popular as it was found that it greatly accelerates the convergence of stochastic gradient descent as compared to Sigmoid or Tanh activation functions. Just to give an intuition, the gradient is either 0 or 1 depending on the sign of the input. Let us discuss some of the advantages of ReLU:
Sparsity of Activations:As we studied above, ReLU and Tanh activation functions would almost always get fired in the neural network, resulting in the almost all the activations getting processed in calculating the final output of the network. Now surely this is a good thing but only if our network is small or we had unlimited computational power. Imagine we have a very deep neural network with a lot of neurons, we would ideally want only a section of neurons to fire and contribute to the final output of the network and hence, we want a section of the neurons in the network to be passive. ReLU gives us this benefit. Hence, due to the characteristics of ReLU, there is a possibility that 50% of neurons to give 0 activations and thus leading to fewer neurons to fire as a result of which the network becomes lighter and we can compute the output faster.
However, it has a drawback in terms of a problem called as dying neurons.
Dead Neurons:ReLU units can be fragile during training and can “die”. That is, if the units are not activated initially, then during backpropagation zero gradients flow through them. Hence, neurons that “die” will stop responding to the variations in the output error because of which the parameters will never be updated/updated during backpropagation. However, there are concepts such as Leaky ReLU that can be used to overcome this problem. Also, having a proper setting of the learning rate can prevent causing the neurons to be dead.
import numpy as npdef relu(z): return z * (z > 0)
The Leaky ReLU is just an extension of the traditional ReLU function. As we saw that for values less than 0, the gradient is 0 which results in “Dead Neurons” in those regions. To address this problem, Leaky ReLU comes in handy. That is, instead of defining values less than 0 as 0, we instead define negative values as a small linear combination of the input. The small value commonly used is 0.01. It is represented as `LeakyReLU(z) = max(0.01 * z, z)`. The idea of Leaky ReLU can be extended even further by making a small change. Instead of multiplying `z` with a constant number, we can learn the multiplier and treat it as an additional hyperparameter in our process. This is known as Parametric ReLU. In practice, it is believed that this performs better than Leaky ReLU.
import numpy as npdef leaky_relu(z): return np.maximum(0.01 * z, z)
Thank you for reading. In this article I tried to lay down my understanding of some of the most commonly used activation functions, why we use them in the first place and which activation function should one use. Keep chilling and keep innovating!
Misc:
If you are working in Data Science or Deep Learning field do not hesitate to reach out if you think there is an opportunity to collaborate. I am looking for full-time opportunities and would love to discuss. | [
{
"code": null,
"e": 652,
"s": 172,
"text": "Welcome to my first post! I am a Data Scientist and have been an active reader of Medium blogs. Now, I am planning to use Medium blog to document my journey in learning Deep Learning and share my experiences through the projects I have been working on. Hopefully, by sharing my views on the subjects I can also learn from the fantastic data science/deep learning community on Medium! I would love to hear your feedback on my first post here. With that said, let’s get started ..."
},
{
"code": null,
"e": 1352,
"s": 652,
"text": "The basic idea of how a neural network learns is — We have some input data that we feed it into the network and then we perform a series of linear operations layer by layer and derive an output. In a simple case for a particular layer is that we multiply the input by the weights, add a bias and apply an activation function and pass the output to the next layer. We keep repeating the process until we reach the last layer. The final value is our output. We then compute the error between the “calculated output” and the “true output” and then calculate the partial derivatives of this error with respect to the parameters in each layer going backwards and keep updating the parameters accordingly!"
},
{
"code": null,
"e": 1697,
"s": 1352,
"text": "Neural networks are said to be universal function approximators. The main underlying goal of a neural network is to learn complex non-linear functions. If we do not apply any non-linearity in our multi-layer neural network, we are simply trying to seperate the classes using a linear hyperplane. As we know, in the real-world nothing is linear!"
},
{
"code": null,
"e": 2235,
"s": 1697,
"text": "Also, imagine we perform simple linear operation as described above, namely; multiply the input by weights, add a bias and sum them across all the inputs arriving to the neuron. It is likely that in certain situations, the output derived above, takes a large value. When, this output is fed into the further layers, they can be transformed to even larger values, making things computationally uncontrollable. This is where the activation functions play a major role i.e. squashing a real-number to a fix interval (e.g. between -1 and 1)."
},
{
"code": null,
"e": 2327,
"s": 2235,
"text": "Let us see different types of activation functions and how they compare against each other:"
},
{
"code": null,
"e": 3242,
"s": 2327,
"text": "The sigmoid activation function has the mathematical form `sig(z) = 1/ (1 + e^-z)`. As we can see, it basically takes a real valued number as the input and squashes it between 0 and 1. It is often termed as a squashing function as well. It aims to introduce non-linearity in the input space. The non-linearity is where we get the wiggle and the network learns to capture complicated relationships. As we can see from the above mathematical representation, a large negative number passed through the sigmoid function becomes 0 and a large positive number becomes 1. Due to this property, sigmoid function often has a really nice interpretation associated with it as the firing rate of the neuron; from not firing at all (0) to fully-saturated firing at an assumed maximum frequency (1). However, sigmoid activation functions have become less popular over the period of time due to the following two major drawbacks:"
},
{
"code": null,
"e": 4193,
"s": 3242,
"text": "Killing gradients:Sigmoid neurons get saturated on the boundaries and hence the local gradients at these regions is almost zero. To give you a more intuitive example to understand this, consider the inputs to the sigmoid function to be +15 and -15. The derivative of sigmoid function is `sig(z) * (1 — sig(z))`. As mentioned above, the large positive values are squashed near 1 and large negative values are squashed near 0. Hence, effectively making the local gradient to near 0. As a result, during backpropagation, this gradient gets multiplied to the gradient of this neurons’ output for the final objective function, hence it will effectively “kill” the gradient and no signal will flow through the neuron to its weights. Also, we have to pay attention to initializing the weights of sigmoid neurons to avoid saturation, because, if the initial weights are too large, then most neurons will get saturated and hence the network will hardly learn."
},
{
"code": null,
"e": 4593,
"s": 4193,
"text": "Non zero-centered outputs:The output is always between 0 and 1, that means that the output after applying sigmoid is always positive hence, during gradient-descent, the gradient on the weights during backpropagation will always be either positive or negative depending on the output of the neuron. As a result, the gradient updates go too far in different directions which makes optimization harder."
},
{
"code": null,
"e": 4647,
"s": 4593,
"text": "The python implementation looks something similar to:"
},
{
"code": null,
"e": 4709,
"s": 4647,
"text": "import numpy as npdef sigmoid(z): return 1 / (1 + np.exp(-z))"
},
{
"code": null,
"e": 5273,
"s": 4709,
"text": "The tanh or hyperbolic tangent activation function has the mathematical form `tanh(z) = (e^z — e^-z) / (e^z + e^-z)`. It is basically a shifted sigmoid neuron. It basically takes a real valued number and squashes it between -1 and +1. Similar to sigmoid neuron, it saturates at large positive and negative values. However, its output is always zero-centered which helps since the neurons in the later layers of the network would be receiving inputs that are zero-centered. Hence, in practice, tanh activation functions are preffered in hidden layers over sigmoid."
},
{
"code": null,
"e": 5322,
"s": 5273,
"text": "import numpy as npdef tanh(z): return np.tanh(z)"
},
{
"code": null,
"e": 5838,
"s": 5322,
"text": "The ReLU or Rectified Linear Unit is represented as `ReLU(z) = max(0, z)`. It basically thresholds the inputs at zero, i.e. all negative values in the input to the ReLU neuron are set to zero. Fairly recently, it has become popular as it was found that it greatly accelerates the convergence of stochastic gradient descent as compared to Sigmoid or Tanh activation functions. Just to give an intuition, the gradient is either 0 or 1 depending on the sign of the input. Let us discuss some of the advantages of ReLU:"
},
{
"code": null,
"e": 6698,
"s": 5838,
"text": "Sparsity of Activations:As we studied above, ReLU and Tanh activation functions would almost always get fired in the neural network, resulting in the almost all the activations getting processed in calculating the final output of the network. Now surely this is a good thing but only if our network is small or we had unlimited computational power. Imagine we have a very deep neural network with a lot of neurons, we would ideally want only a section of neurons to fire and contribute to the final output of the network and hence, we want a section of the neurons in the network to be passive. ReLU gives us this benefit. Hence, due to the characteristics of ReLU, there is a possibility that 50% of neurons to give 0 activations and thus leading to fewer neurons to fire as a result of which the network becomes lighter and we can compute the output faster."
},
{
"code": null,
"e": 6772,
"s": 6698,
"text": "However, it has a drawback in terms of a problem called as dying neurons."
},
{
"code": null,
"e": 7311,
"s": 6772,
"text": "Dead Neurons:ReLU units can be fragile during training and can “die”. That is, if the units are not activated initially, then during backpropagation zero gradients flow through them. Hence, neurons that “die” will stop responding to the variations in the output error because of which the parameters will never be updated/updated during backpropagation. However, there are concepts such as Leaky ReLU that can be used to overcome this problem. Also, having a proper setting of the learning rate can prevent causing the neurons to be dead."
},
{
"code": null,
"e": 7361,
"s": 7311,
"text": "import numpy as npdef relu(z): return z * (z > 0)"
},
{
"code": null,
"e": 8140,
"s": 7361,
"text": "The Leaky ReLU is just an extension of the traditional ReLU function. As we saw that for values less than 0, the gradient is 0 which results in “Dead Neurons” in those regions. To address this problem, Leaky ReLU comes in handy. That is, instead of defining values less than 0 as 0, we instead define negative values as a small linear combination of the input. The small value commonly used is 0.01. It is represented as `LeakyReLU(z) = max(0.01 * z, z)`. The idea of Leaky ReLU can be extended even further by making a small change. Instead of multiplying `z` with a constant number, we can learn the multiplier and treat it as an additional hyperparameter in our process. This is known as Parametric ReLU. In practice, it is believed that this performs better than Leaky ReLU."
},
{
"code": null,
"e": 8208,
"s": 8140,
"text": "import numpy as npdef leaky_relu(z): return np.maximum(0.01 * z, z)"
},
{
"code": null,
"e": 8456,
"s": 8208,
"text": "Thank you for reading. In this article I tried to lay down my understanding of some of the most commonly used activation functions, why we use them in the first place and which activation function should one use. Keep chilling and keep innovating!"
},
{
"code": null,
"e": 8462,
"s": 8456,
"text": "Misc:"
}
]
|
Approximating Integrals using Numpy [ Riemann / Trapeze / Simpson’s / Adaptive /Monte Carlo Integration ] | by Jae Duk Seo | Towards Data Science | Approximating integrals is a very important task in computer science (even relating to neural networks). And today I wanted to implement different methods of approximating integrals.
Functions that we are going to Use
In total we are going to approximate the integral for four different functions
1. integral from -8 to 6 x dx = 18902. integral from -10 to 120 (x^2 + 100 - x^5) dx = -4976632440003. integral from -10 to 23 sqrt(x) dx = 2/3 (23 sqrt(23) + 10 i sqrt(10))≈73.5361 + 21.0819 i4. integral from 0 to pi x sin(x^2) dx = sin^2(π^2/2)≈0.9513
And as seen above we can already see the results from analytical solutions.
Approximating Methods
Riemann integration
Trapeze integration
Simpson’s integration
Adaptive integration
Monte Carlo integration
As seen above we are going to use five different methods to estimate the integrals. Just as a side note, among the five methods four (except adaptive integral) have a hyper parameter as a number of samples. Increasing this value will result in better approximation of integral,
Function 1
While Adaptive integral got the most accurate integral value, other methods either under/over estimated. (of course as we increase number of samples it gets more accurate.)
Function 2
For this function adaptive integral method have under estimated the integral value for large amount.
Function 3
Except for the adaptive integral method overall other methods did quite well, for small number of data points.
Function 4
Interestingly similar results for sine function as well.
Interactive Code
To access the code for this post please click here.
Amazing Resources
Final Words
This was a good review as well as good programming practice. When I was playing around with the values, it became quite clear that Monte Carlo methods integration is a powerful method but it needs more time to converge properly.
If any errors are found, please email me at [email protected], if you wish to see the list of all of my writing please view my website here.
Reference
(2018). Maths.qmul.ac.uk. Retrieved 1 December 2018, from http://www.maths.qmul.ac.uk/~wj/MTH5110/notes/MAS235_lecturenotes1.pdfFourier Series GIF — Find & Share on GIPHY. (2018). GIPHY. Retrieved 1 December 2018, from https://giphy.com/gifs/fourier-series-HqZuL4RWgf2msMonte Carlo Integration In Python For Noobs. (2018). YouTube. Retrieved 1 December 2018, from https://www.youtube.com/watch?v=WAf0rqwAvggBatman Integration · LeiosOS . (2018). Leios.github.io. Retrieved 1 December 2018, from https://leios.github.io/Batman_MontecarloDhamdhere, K., Sundararajan, M., & Yan, Q. (2018). How Important Is a Neuron?. Arxiv.org. Retrieved 1 December 2018, from https://arxiv.org/abs/1805.12233
(2018). Maths.qmul.ac.uk. Retrieved 1 December 2018, from http://www.maths.qmul.ac.uk/~wj/MTH5110/notes/MAS235_lecturenotes1.pdf
Fourier Series GIF — Find & Share on GIPHY. (2018). GIPHY. Retrieved 1 December 2018, from https://giphy.com/gifs/fourier-series-HqZuL4RWgf2ms
Monte Carlo Integration In Python For Noobs. (2018). YouTube. Retrieved 1 December 2018, from https://www.youtube.com/watch?v=WAf0rqwAvgg
Batman Integration · LeiosOS . (2018). Leios.github.io. Retrieved 1 December 2018, from https://leios.github.io/Batman_Montecarlo
Dhamdhere, K., Sundararajan, M., & Yan, Q. (2018). How Important Is a Neuron?. Arxiv.org. Retrieved 1 December 2018, from https://arxiv.org/abs/1805.12233 | [
{
"code": null,
"e": 355,
"s": 172,
"text": "Approximating integrals is a very important task in computer science (even relating to neural networks). And today I wanted to implement different methods of approximating integrals."
},
{
"code": null,
"e": 390,
"s": 355,
"text": "Functions that we are going to Use"
},
{
"code": null,
"e": 469,
"s": 390,
"text": "In total we are going to approximate the integral for four different functions"
},
{
"code": null,
"e": 733,
"s": 469,
"text": "1. integral from -8 to 6 x dx = 18902. integral from -10 to 120 (x^2 + 100 - x^5) dx = -4976632440003. integral from -10 to 23 sqrt(x) dx = 2/3 (23 sqrt(23) + 10 i sqrt(10))≈73.5361 + 21.0819 i4. integral from 0 to pi x sin(x^2) dx = sin^2(π^2/2)≈0.9513"
},
{
"code": null,
"e": 809,
"s": 733,
"text": "And as seen above we can already see the results from analytical solutions."
},
{
"code": null,
"e": 831,
"s": 809,
"text": "Approximating Methods"
},
{
"code": null,
"e": 851,
"s": 831,
"text": "Riemann integration"
},
{
"code": null,
"e": 871,
"s": 851,
"text": "Trapeze integration"
},
{
"code": null,
"e": 893,
"s": 871,
"text": "Simpson’s integration"
},
{
"code": null,
"e": 914,
"s": 893,
"text": "Adaptive integration"
},
{
"code": null,
"e": 938,
"s": 914,
"text": "Monte Carlo integration"
},
{
"code": null,
"e": 1216,
"s": 938,
"text": "As seen above we are going to use five different methods to estimate the integrals. Just as a side note, among the five methods four (except adaptive integral) have a hyper parameter as a number of samples. Increasing this value will result in better approximation of integral,"
},
{
"code": null,
"e": 1227,
"s": 1216,
"text": "Function 1"
},
{
"code": null,
"e": 1400,
"s": 1227,
"text": "While Adaptive integral got the most accurate integral value, other methods either under/over estimated. (of course as we increase number of samples it gets more accurate.)"
},
{
"code": null,
"e": 1411,
"s": 1400,
"text": "Function 2"
},
{
"code": null,
"e": 1512,
"s": 1411,
"text": "For this function adaptive integral method have under estimated the integral value for large amount."
},
{
"code": null,
"e": 1523,
"s": 1512,
"text": "Function 3"
},
{
"code": null,
"e": 1634,
"s": 1523,
"text": "Except for the adaptive integral method overall other methods did quite well, for small number of data points."
},
{
"code": null,
"e": 1645,
"s": 1634,
"text": "Function 4"
},
{
"code": null,
"e": 1702,
"s": 1645,
"text": "Interestingly similar results for sine function as well."
},
{
"code": null,
"e": 1719,
"s": 1702,
"text": "Interactive Code"
},
{
"code": null,
"e": 1771,
"s": 1719,
"text": "To access the code for this post please click here."
},
{
"code": null,
"e": 1789,
"s": 1771,
"text": "Amazing Resources"
},
{
"code": null,
"e": 1801,
"s": 1789,
"text": "Final Words"
},
{
"code": null,
"e": 2030,
"s": 1801,
"text": "This was a good review as well as good programming practice. When I was playing around with the values, it became quite clear that Monte Carlo methods integration is a powerful method but it needs more time to converge properly."
},
{
"code": null,
"e": 2175,
"s": 2030,
"text": "If any errors are found, please email me at [email protected], if you wish to see the list of all of my writing please view my website here."
},
{
"code": null,
"e": 2185,
"s": 2175,
"text": "Reference"
},
{
"code": null,
"e": 2876,
"s": 2185,
"text": "(2018). Maths.qmul.ac.uk. Retrieved 1 December 2018, from http://www.maths.qmul.ac.uk/~wj/MTH5110/notes/MAS235_lecturenotes1.pdfFourier Series GIF — Find & Share on GIPHY. (2018). GIPHY. Retrieved 1 December 2018, from https://giphy.com/gifs/fourier-series-HqZuL4RWgf2msMonte Carlo Integration In Python For Noobs. (2018). YouTube. Retrieved 1 December 2018, from https://www.youtube.com/watch?v=WAf0rqwAvggBatman Integration · LeiosOS . (2018). Leios.github.io. Retrieved 1 December 2018, from https://leios.github.io/Batman_MontecarloDhamdhere, K., Sundararajan, M., & Yan, Q. (2018). How Important Is a Neuron?. Arxiv.org. Retrieved 1 December 2018, from https://arxiv.org/abs/1805.12233"
},
{
"code": null,
"e": 3005,
"s": 2876,
"text": "(2018). Maths.qmul.ac.uk. Retrieved 1 December 2018, from http://www.maths.qmul.ac.uk/~wj/MTH5110/notes/MAS235_lecturenotes1.pdf"
},
{
"code": null,
"e": 3148,
"s": 3005,
"text": "Fourier Series GIF — Find & Share on GIPHY. (2018). GIPHY. Retrieved 1 December 2018, from https://giphy.com/gifs/fourier-series-HqZuL4RWgf2ms"
},
{
"code": null,
"e": 3286,
"s": 3148,
"text": "Monte Carlo Integration In Python For Noobs. (2018). YouTube. Retrieved 1 December 2018, from https://www.youtube.com/watch?v=WAf0rqwAvgg"
},
{
"code": null,
"e": 3416,
"s": 3286,
"text": "Batman Integration · LeiosOS . (2018). Leios.github.io. Retrieved 1 December 2018, from https://leios.github.io/Batman_Montecarlo"
}
]
|
How to use R in Google Colab | Towards Data Science | Colab, or Colaboratory is an interactive notebook provided by Google (primarily) for writing and running Python through a browser. We can perform data analysis, create models, evaluate these models in Colab. The processing is done on Google-owned servers in the cloud. We only need a browser and a fairly stable internet connection.
Colab is a great alternative tool to facilitate our work, whether as a student, professional, or researcher.
Although Colab is primarily used for coding in Python, apparently we can also use it for R (#Rstats).
This post will tell you how to run R in Google Colab and how to mount Google Drive or access BigQuery in R notebook.
The first way is to use the rpy2 package in the Python runtime. This method allows you to execute R and Python syntax together.
The second way is to actually start the notebook in the R runtime.
Open your favorite browser.Create a new notebook: https://colab.research.google.com/#create=true.Run rmagic by executing this command %load_ext rpy2.ipython.After that, every time you want to use R, add %%R in the beginning of each cell.
Open your favorite browser.
Create a new notebook: https://colab.research.google.com/#create=true.
Run rmagic by executing this command %load_ext rpy2.ipython.
After that, every time you want to use R, add %%R in the beginning of each cell.
Start rmagic by executing this in a cell:
%load_ext rpy2.ipython
Use %%R to execute cell magic. Use this if you want all syntax in a cell to be executed in R. Note that this must be placed at the beginning of the cell.
%%Rx <- seq(0, 2*pi, length.out=50)x
These lines will return a variable x, and display it on the cell output:
Use %R to execute line magic. Use this if you want a single line in a cell to be executed in R.
Here is how you could use this line magic to copy R variable to Python:
x = %R x
To use the notebook directly with R:
Open your favorite browser.Go to this URL: https://colab.research.google.com/#create=true&language=r, or this short URL https://colab.to/r
Open your favorite browser.
Go to this URL: https://colab.research.google.com/#create=true&language=r, or this short URL https://colab.to/r
After accessing the URL, you will be taken to a new Colab notebook with the default title Unitled.ipynb.
At first glance, there is no difference between notebooks with Python and R runtimes. However, if we go to the “Runtime” settings, and select “Change runtime type”, we will get a dialog confirming that we are already in R runtime.
You can also confirm that you are in the R runtime by trying to mount your Drive to the notebook. Doing so, you will get an unfortunate message like this:
The message “Mounting your Google Drive is only available on hosted Python runtimes.” clearly indicates that you are not in the Python runtime.
Congratulations, you have now successfully run R in Colab. You can check the R version by typing R.version.string to print out the R version.
Here, several packages that are useful for data processing and data visualization are already available. You can check it by running print(installed.packages()).
If you’re having trouble installing packages, this post might help you:
towardsdatascience.com
This should be done fairly easily. We only need to install the “googledrive” package and perform the authentication process.
install.packages("googledrive")library("googledrive")
After installing the package, we need to authenticate and authorize the googledrive package. You can read the package documentation here:
googledrive.tidyverse.org
# authorize google drivedrive_auth( email = gargle::gargle_oauth_email(), path = NULL, scopes = "https://www.googleapis.com/auth/drive", cache = gargle::gargle_oauth_cache(), use_oob = gargle::gargle_oob_default(), token = NULL)
Unfortunately the process did not go smoothly when trying to authenticate. We are instead faced with an error message like this:
Apparently, the error occurred because the interactive function in httr package could not be executed.
Here’s a workaround that we can use, provided by jobdiogene’s: https://gist.github.com/jobdiogenes/235620928c84e604c6e56211ccf681f0
# Check if is running in Colab and redefine is_interactive()if (file.exists("/usr/local/lib/python3.6/dist-packages/google/colab/_ipython.py")) { install.packages("R.utils") library("R.utils") library("httr") my_check <- function() {return(TRUE)} reassignInPackage("is_interactive", pkgName = "httr", my_check) options(rlang_interactive=TRUE)}
After running that lines, we can try to authenticate Google Drive again, and now it will work!
drive_auth(use_oob = TRUE, cache = TRUE)
You will need to click the link and grant permission for the packages to access your Google Drive. After this you should be able to get the authorization code to be pasted in the code field.
For business people, or for researchers who are more comfortable using R, perhaps we need to retrieve data from company-owned BigQuery or publicly available datasets there.
Now that we have the workaround, authorizing BigQuery and retrieve data from there would be simple:
install.packages("bigrquery")library("bigrquery")bq_auth(use_oob = TRUE, cache = FALSE)
Extract data from BigQuery with custom query:
# Store the project idprojectid = "your-project-id"# Set the querysql <- "SELECT * FROM your_table"# Run the queryproject_query <- bq_project_query(projectid, sql, use_legacy_sql = FALSE)# Download result to dataframedf <- bq_table_download(project_query)
This is what I think I can contribute to the data community. As I mentioned earlier, Google Colab provide us an alternative for learning or working with R, besides Kaggle and RStudio Cloud. All of them are good platforms, especially when used for learning purposes; can shorten the time for initial setup (downloading and installing R, and installing packages). Even though the way to use R in Google Colab is a bit confusing, and doesn’t yet have the same services as the Python runtime, in the end, it still works quite well.
Thanks for reading! | [
{
"code": null,
"e": 504,
"s": 171,
"text": "Colab, or Colaboratory is an interactive notebook provided by Google (primarily) for writing and running Python through a browser. We can perform data analysis, create models, evaluate these models in Colab. The processing is done on Google-owned servers in the cloud. We only need a browser and a fairly stable internet connection."
},
{
"code": null,
"e": 613,
"s": 504,
"text": "Colab is a great alternative tool to facilitate our work, whether as a student, professional, or researcher."
},
{
"code": null,
"e": 715,
"s": 613,
"text": "Although Colab is primarily used for coding in Python, apparently we can also use it for R (#Rstats)."
},
{
"code": null,
"e": 832,
"s": 715,
"text": "This post will tell you how to run R in Google Colab and how to mount Google Drive or access BigQuery in R notebook."
},
{
"code": null,
"e": 960,
"s": 832,
"text": "The first way is to use the rpy2 package in the Python runtime. This method allows you to execute R and Python syntax together."
},
{
"code": null,
"e": 1027,
"s": 960,
"text": "The second way is to actually start the notebook in the R runtime."
},
{
"code": null,
"e": 1265,
"s": 1027,
"text": "Open your favorite browser.Create a new notebook: https://colab.research.google.com/#create=true.Run rmagic by executing this command %load_ext rpy2.ipython.After that, every time you want to use R, add %%R in the beginning of each cell."
},
{
"code": null,
"e": 1293,
"s": 1265,
"text": "Open your favorite browser."
},
{
"code": null,
"e": 1364,
"s": 1293,
"text": "Create a new notebook: https://colab.research.google.com/#create=true."
},
{
"code": null,
"e": 1425,
"s": 1364,
"text": "Run rmagic by executing this command %load_ext rpy2.ipython."
},
{
"code": null,
"e": 1506,
"s": 1425,
"text": "After that, every time you want to use R, add %%R in the beginning of each cell."
},
{
"code": null,
"e": 1548,
"s": 1506,
"text": "Start rmagic by executing this in a cell:"
},
{
"code": null,
"e": 1571,
"s": 1548,
"text": "%load_ext rpy2.ipython"
},
{
"code": null,
"e": 1725,
"s": 1571,
"text": "Use %%R to execute cell magic. Use this if you want all syntax in a cell to be executed in R. Note that this must be placed at the beginning of the cell."
},
{
"code": null,
"e": 1762,
"s": 1725,
"text": "%%Rx <- seq(0, 2*pi, length.out=50)x"
},
{
"code": null,
"e": 1835,
"s": 1762,
"text": "These lines will return a variable x, and display it on the cell output:"
},
{
"code": null,
"e": 1931,
"s": 1835,
"text": "Use %R to execute line magic. Use this if you want a single line in a cell to be executed in R."
},
{
"code": null,
"e": 2003,
"s": 1931,
"text": "Here is how you could use this line magic to copy R variable to Python:"
},
{
"code": null,
"e": 2012,
"s": 2003,
"text": "x = %R x"
},
{
"code": null,
"e": 2049,
"s": 2012,
"text": "To use the notebook directly with R:"
},
{
"code": null,
"e": 2188,
"s": 2049,
"text": "Open your favorite browser.Go to this URL: https://colab.research.google.com/#create=true&language=r, or this short URL https://colab.to/r"
},
{
"code": null,
"e": 2216,
"s": 2188,
"text": "Open your favorite browser."
},
{
"code": null,
"e": 2328,
"s": 2216,
"text": "Go to this URL: https://colab.research.google.com/#create=true&language=r, or this short URL https://colab.to/r"
},
{
"code": null,
"e": 2433,
"s": 2328,
"text": "After accessing the URL, you will be taken to a new Colab notebook with the default title Unitled.ipynb."
},
{
"code": null,
"e": 2664,
"s": 2433,
"text": "At first glance, there is no difference between notebooks with Python and R runtimes. However, if we go to the “Runtime” settings, and select “Change runtime type”, we will get a dialog confirming that we are already in R runtime."
},
{
"code": null,
"e": 2819,
"s": 2664,
"text": "You can also confirm that you are in the R runtime by trying to mount your Drive to the notebook. Doing so, you will get an unfortunate message like this:"
},
{
"code": null,
"e": 2963,
"s": 2819,
"text": "The message “Mounting your Google Drive is only available on hosted Python runtimes.” clearly indicates that you are not in the Python runtime."
},
{
"code": null,
"e": 3105,
"s": 2963,
"text": "Congratulations, you have now successfully run R in Colab. You can check the R version by typing R.version.string to print out the R version."
},
{
"code": null,
"e": 3267,
"s": 3105,
"text": "Here, several packages that are useful for data processing and data visualization are already available. You can check it by running print(installed.packages())."
},
{
"code": null,
"e": 3339,
"s": 3267,
"text": "If you’re having trouble installing packages, this post might help you:"
},
{
"code": null,
"e": 3362,
"s": 3339,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 3487,
"s": 3362,
"text": "This should be done fairly easily. We only need to install the “googledrive” package and perform the authentication process."
},
{
"code": null,
"e": 3541,
"s": 3487,
"text": "install.packages(\"googledrive\")library(\"googledrive\")"
},
{
"code": null,
"e": 3679,
"s": 3541,
"text": "After installing the package, we need to authenticate and authorize the googledrive package. You can read the package documentation here:"
},
{
"code": null,
"e": 3705,
"s": 3679,
"text": "googledrive.tidyverse.org"
},
{
"code": null,
"e": 3940,
"s": 3705,
"text": "# authorize google drivedrive_auth( email = gargle::gargle_oauth_email(), path = NULL, scopes = \"https://www.googleapis.com/auth/drive\", cache = gargle::gargle_oauth_cache(), use_oob = gargle::gargle_oob_default(), token = NULL)"
},
{
"code": null,
"e": 4069,
"s": 3940,
"text": "Unfortunately the process did not go smoothly when trying to authenticate. We are instead faced with an error message like this:"
},
{
"code": null,
"e": 4172,
"s": 4069,
"text": "Apparently, the error occurred because the interactive function in httr package could not be executed."
},
{
"code": null,
"e": 4304,
"s": 4172,
"text": "Here’s a workaround that we can use, provided by jobdiogene’s: https://gist.github.com/jobdiogenes/235620928c84e604c6e56211ccf681f0"
},
{
"code": null,
"e": 4655,
"s": 4304,
"text": "# Check if is running in Colab and redefine is_interactive()if (file.exists(\"/usr/local/lib/python3.6/dist-packages/google/colab/_ipython.py\")) { install.packages(\"R.utils\") library(\"R.utils\") library(\"httr\") my_check <- function() {return(TRUE)} reassignInPackage(\"is_interactive\", pkgName = \"httr\", my_check) options(rlang_interactive=TRUE)}"
},
{
"code": null,
"e": 4750,
"s": 4655,
"text": "After running that lines, we can try to authenticate Google Drive again, and now it will work!"
},
{
"code": null,
"e": 4791,
"s": 4750,
"text": "drive_auth(use_oob = TRUE, cache = TRUE)"
},
{
"code": null,
"e": 4982,
"s": 4791,
"text": "You will need to click the link and grant permission for the packages to access your Google Drive. After this you should be able to get the authorization code to be pasted in the code field."
},
{
"code": null,
"e": 5155,
"s": 4982,
"text": "For business people, or for researchers who are more comfortable using R, perhaps we need to retrieve data from company-owned BigQuery or publicly available datasets there."
},
{
"code": null,
"e": 5255,
"s": 5155,
"text": "Now that we have the workaround, authorizing BigQuery and retrieve data from there would be simple:"
},
{
"code": null,
"e": 5343,
"s": 5255,
"text": "install.packages(\"bigrquery\")library(\"bigrquery\")bq_auth(use_oob = TRUE, cache = FALSE)"
},
{
"code": null,
"e": 5389,
"s": 5343,
"text": "Extract data from BigQuery with custom query:"
},
{
"code": null,
"e": 5645,
"s": 5389,
"text": "# Store the project idprojectid = \"your-project-id\"# Set the querysql <- \"SELECT * FROM your_table\"# Run the queryproject_query <- bq_project_query(projectid, sql, use_legacy_sql = FALSE)# Download result to dataframedf <- bq_table_download(project_query)"
},
{
"code": null,
"e": 6173,
"s": 5645,
"text": "This is what I think I can contribute to the data community. As I mentioned earlier, Google Colab provide us an alternative for learning or working with R, besides Kaggle and RStudio Cloud. All of them are good platforms, especially when used for learning purposes; can shorten the time for initial setup (downloading and installing R, and installing packages). Even though the way to use R in Google Colab is a bit confusing, and doesn’t yet have the same services as the Python runtime, in the end, it still works quite well."
}
]
|
Set a linear gradient as the background image with CSS | Set a linear gradient as the background image, with linear-gradient() CSS function. You can try to run the following code to implement linear-gradient() function in CSS
Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
#demo {
height: 200px;
background: linear-gradient(green, orange, maroon);
}
</style>
</head>
<body>
<p>Setting background as linear gradient.</p>
<div id = "demo"></div>
</body>
</html> | [
{
"code": null,
"e": 1231,
"s": 1062,
"text": "Set a linear gradient as the background image, with linear-gradient() CSS function. You can try to run the following code to implement linear-gradient() function in CSS"
},
{
"code": null,
"e": 1241,
"s": 1231,
"text": "Live Demo"
},
{
"code": null,
"e": 1544,
"s": 1241,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n #demo {\n height: 200px;\n background: linear-gradient(green, orange, maroon);\n }\n </style>\n </head>\n <body>\n <p>Setting background as linear gradient.</p>\n <div id = \"demo\"></div>\n </body>\n</html>"
}
]
|
Pascal - goto Statement | A goto statement in Pascal provides an unconditional jump from the goto to a labeled statement in the same function.
NOTE − Use of goto statement is highly discouraged in any programming language because it makes difficult to trace the control flow of a program, making the program hard to understand and hard to modify. Any program that uses a goto can be rewritten so that it doesn't need the goto.
The syntax for a goto statement in Pascal is as follows −
goto label;
...
...
label: statement;
Here, label must be an unsigned integer label, whose value can be from 1 to 9999.
The following program illustrates the concept.
program exGoto;
label 1;
var
a : integer;
begin
a := 10;
(* repeat until loop execution *)
1: repeat
if( a = 15) then
begin
(* skip the iteration *)
a := a + 1;
goto 1;
end;
writeln('value of a: ', a);
a:= a +1;
until a = 20;
end.
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19
Please note that −
In Pascal, all labels must be declared before constant and variable declarations.
In Pascal, all labels must be declared before constant and variable declarations.
The if and goto statements may be used in the compound statement to transfer control out of the compound statement, but it is illegal to transfer control into a compound statement.
The if and goto statements may be used in the compound statement to transfer control out of the compound statement, but it is illegal to transfer control into a compound statement.
94 Lectures
8.5 hours
Stone River ELearning
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2200,
"s": 2083,
"text": "A goto statement in Pascal provides an unconditional jump from the goto to a labeled statement in the same function."
},
{
"code": null,
"e": 2485,
"s": 2200,
"text": "NOTE − Use of goto statement is highly discouraged in any programming language because it makes difficult to trace the control flow of a program, making the program hard to understand and hard to modify. Any program that uses a goto can be rewritten so that it doesn't need the goto. "
},
{
"code": null,
"e": 2543,
"s": 2485,
"text": "The syntax for a goto statement in Pascal is as follows −"
},
{
"code": null,
"e": 2588,
"s": 2543,
"text": "goto label;\n ...\n ...\nlabel: statement;\n"
},
{
"code": null,
"e": 2671,
"s": 2588,
"text": "Here, label must be an unsigned integer label, whose value can be from 1 to 9999. "
},
{
"code": null,
"e": 2718,
"s": 2671,
"text": "The following program illustrates the concept."
},
{
"code": null,
"e": 3037,
"s": 2718,
"text": "program exGoto;\nlabel 1; \nvar\n a : integer;\n\nbegin\n a := 10;\n (* repeat until loop execution *)\n 1: repeat\n if( a = 15) then\n \n begin\n (* skip the iteration *)\n a := a + 1;\n goto 1;\n end;\n \n writeln('value of a: ', a);\n a:= a +1;\n until a = 20;\nend."
},
{
"code": null,
"e": 3118,
"s": 3037,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 3254,
"s": 3118,
"text": "value of a: 10\nvalue of a: 11\nvalue of a: 12\nvalue of a: 13\nvalue of a: 14\nvalue of a: 16\nvalue of a: 17\nvalue of a: 18\nvalue of a: 19\n"
},
{
"code": null,
"e": 3273,
"s": 3254,
"text": "Please note that −"
},
{
"code": null,
"e": 3356,
"s": 3273,
"text": "In Pascal, all labels must be declared before constant and variable declarations. "
},
{
"code": null,
"e": 3439,
"s": 3356,
"text": "In Pascal, all labels must be declared before constant and variable declarations. "
},
{
"code": null,
"e": 3621,
"s": 3439,
"text": "The if and goto statements may be used in the compound statement to transfer control out of the compound statement, but it is illegal to transfer control into a compound statement. "
},
{
"code": null,
"e": 3803,
"s": 3621,
"text": "The if and goto statements may be used in the compound statement to transfer control out of the compound statement, but it is illegal to transfer control into a compound statement. "
},
{
"code": null,
"e": 3838,
"s": 3803,
"text": "\n 94 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 3861,
"s": 3838,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 3868,
"s": 3861,
"text": " Print"
},
{
"code": null,
"e": 3879,
"s": 3868,
"text": " Add Notes"
}
]
|
A Simple Guide to Deploying a Dockerized Python app to Azure | by Bjørnar Kjenaas Mælum | Towards Data Science | So you are telling me you have built an app and now you want to deploy it for everyone to see? Look no further. Here is how to deploy it on Azure using Docker, Azure Container Registry and Azure Container Instances.
This guide uses a FastAPI app as the example app and assumes you are familiar with the basics of using the terminal, building a Python application and basic Docker commands. If you have an app of your own that you want to deploy to Azure the only thing you need is to Dockerize the app using a suitable Dockerfile that matches your app.
What will you have achieved after finishing this guide? Well, you’ll have a deployed version of your app on Azure. Great, right?
First, let’s set up a working FastAPI app we can deploy to Azure. I will be using a simple Hello World example you can find here: https://github.com/bmaelum/fastapi-hello-world
The app contains a main file in the /app folder, this is where the FastAPI code is found.
from fastapi import FastAPI app = FastAPI( title="FastAPI - Hello World", description="This is the Hello World of FastAPI.", version="1.0.0",) @app.get("/")def hello_world(): return {"Hello": "World"}
To use app, first fork the repository to create a copy in your own Github account. This is necessary to complete the steps using Github Actions. If you want to use the example code for this guide fork the repo by going to this URL: https://github.com/bmaelum/fastapi-hello-world and click the “Fork” button.
To be able to test the code, clone the repo to your machine:
git clone [email protected]:<your-username>/fastapi-hello-world.git
Then install the requirements found in the requirements.txt file into your environment:
pip install -r requirements.txt
To run the app, simply type:
uvicorn app.main:app
You should see something like this in the terminal:
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
Testing the app can be done in the browser or with a tool like Postman. To check out the app in your browser simply go to the URL printed in the terminal, in this case: http://127.0.0.1:8000.
Now, let’s Dockerize the application.
Using Docker to deploy your app is great for many reasons, one of them is that it helps you make sure you have the same environment for your local development as for the deployment on Azure.
Make sure you have a suitable Dockerfile. In the example file the Dockerfile looks like this:
FROM tiangolo/uvicorn-gunicorn-fastapi:python3.7 COPY ./app /app COPY requirements.txt .RUN pip --no-cache-dir install -r requirements.txt
To build the Docker image simply run:
docker build -t fastapi-image .
To run the image in a container, simply run:
docker run -p 80:80 -it fastapi-image
To test the app you can use the same address as before, just change the port to 80, like this: http://127.0.0.1:80.
Your app works locally, great! Now it’s time to deploy it to Azure!
Ready to deploy to Azure? Exciting!
Deploying the app to Azure requires us doing a few actions in the Azure portal as well as using Github Actions.
This guide will now be following the official documentation of Microsoft found here: https://docs.microsoft.com/en-us/azure/container-instances/container-instances-github-action
Firstly we need to create a Service Principal, a role, in the desired resource group. If you don’t already have a resource group simply create one by going to Resource groups in the Azure portal.
To create a Service Principal we are using Bash in the Azure Cloud Shell. Open this by clicking on the Cloud Shell icon on the top of the page:
Make sure it is set to Bash in the top left of the Cloud Shell:
Then, create a Service Principal for the Resource Group in Azure by using the following command and give the role a name and the scope is the Resource ID for your Resource Group.
Get the Resource Group ID:
groupId=$(az group show \ --name <resource-group-name> \ --query id --output tsv)
Create the role:
az ad sp create-for-rbac \ --name githubactions \ --scope $groupId \ --role Contributor \ --sdk-auth
This will give you a JSON in this format:
{ "clientId": "", "clientSecret": "", "subscriptionId": "", "tenantId": "", "activeDirectoryEndpointUrl": "https://login.microsoftonline.com", "resourceManagerEndpointUrl": "https://management.azure.com/", "activeDirectoryGraphResourceId": "https://graph.windows.net/", "sqlManagementEndpointUrl": "https://management.core.windows.net:8443/", "galleryEndpointUrl": "https://gallery.azure.com/", "managementEndpointUrl": "https://management.core.windows.net/"}
Make sure to save this as it will be used to authenticate when using Github Actions.
To manage a Docker container and images you need to create a Container Registry within Azure.
Search for “Container registries” and choose “Create”. Choose your resource group, a name for the instance and a location. For SKU you can choose the Basic option.
Great, let’s get going with the setup of Github Actions.
Remember the JSON you collected in the previous step? Now it’s time to use it.
Go to Github and the repository containing your app. Then go to Settings -> Secrets and add the following credentials(official docs):
AZURE_CREDENTIALSThe entire JSON output from the service principal creation step
REGISTRY_LOGIN_SERVERThe login server name of your registry (all lowercase). Example: myregistry.azurecr.io
REGISTRY_USERNAMEThe clientId from the JSON output from the service principal creation
REGISTRY_PASSWORDThe clientSecret from the JSON output from the service principal creation
RESOURCE_GROUPThe name of the resource group you used to scope the service principal
Now, let’s setup the workflow using Github Actions. Firstly, go to your repo on Github and click the “Actions” button. From there, choose “Skip this and set up a workflow yourself”.
Replace the existing code in the main.yml file with the following code:
on: [push]name: PythonAppAzureDeploymentjobs: build-and-deploy: runs-on: ubuntu-latest steps: # checkout the repo - name: 'Checkout GitHub Action' uses: actions/checkout@main - name: 'Login via Azure CLI' uses: azure/login@v1 with: creds: ${{ secrets.AZURE_CREDENTIALS }} - name: 'Build and push image' uses: azure/docker-login@v1 with: login-server: ${{ secrets.REGISTRY_LOGIN_SERVER }} username: ${{ secrets.REGISTRY_USERNAME }} password: ${{ secrets.REGISTRY_PASSWORD }} - run: | docker build . -t ${{ secrets.REGISTRY_LOGIN_SERVER }}/sampleapp:${{ github.sha }} docker push ${{ secrets.REGISTRY_LOGIN_SERVER }}/sampleapp:${{ github.sha }} - name: 'Deploy to Azure Container Instances' uses: 'azure/aci-deploy@v1' with: resource-group: ${{ secrets.RESOURCE_GROUP }} dns-name-label: ${{ secrets.RESOURCE_GROUP }}${{ github.run_number }} image: ${{ secrets.REGISTRY_LOGIN_SERVER }}/sampleapp:${{ github.sha }} registry-login-server: ${{ secrets.REGISTRY_LOGIN_SERVER }} registry-username: ${{ secrets.REGISTRY_USERNAME }} registry-password: ${{ secrets.REGISTRY_PASSWORD }} name: fastapi-sampleapp location: 'west europe'
Then, commit the file and because we have specified “on: push” it will run straight away. If it doesn’t make sure the code has been commited and pushed to the repo.
Now, wait for the code to be built and deployed. You can follow the progress by clicking “Actions” and choosing the running pipeline.
If you get the error:
Error: The subscription is not registered to use namespace ‘Microsoft.ContainerInstance’.
Simply do the following in PowerShell:
Register-AzResourceProvider -ProviderNamespace Microsoft.ContainerInstance
Alternatively, in Azure, you can go to “Subscriptions”, choose your subscription, go to Resource Providers, search for “ContainerInstance”, click the desired result and click “Register”.
Your Dockerized app should now be visible when going to the Container Instances in the Azure portal.
To test the app click on the newly deployed Container Instance and go to Properties. Under FQDN there is a URL. Paste the URL in your browser and you should see something like this: | [
{
"code": null,
"e": 388,
"s": 172,
"text": "So you are telling me you have built an app and now you want to deploy it for everyone to see? Look no further. Here is how to deploy it on Azure using Docker, Azure Container Registry and Azure Container Instances."
},
{
"code": null,
"e": 725,
"s": 388,
"text": "This guide uses a FastAPI app as the example app and assumes you are familiar with the basics of using the terminal, building a Python application and basic Docker commands. If you have an app of your own that you want to deploy to Azure the only thing you need is to Dockerize the app using a suitable Dockerfile that matches your app."
},
{
"code": null,
"e": 854,
"s": 725,
"text": "What will you have achieved after finishing this guide? Well, you’ll have a deployed version of your app on Azure. Great, right?"
},
{
"code": null,
"e": 1031,
"s": 854,
"text": "First, let’s set up a working FastAPI app we can deploy to Azure. I will be using a simple Hello World example you can find here: https://github.com/bmaelum/fastapi-hello-world"
},
{
"code": null,
"e": 1121,
"s": 1031,
"text": "The app contains a main file in the /app folder, this is where the FastAPI code is found."
},
{
"code": null,
"e": 1345,
"s": 1121,
"text": "from fastapi import FastAPI app = FastAPI( title=\"FastAPI - Hello World\", description=\"This is the Hello World of FastAPI.\", version=\"1.0.0\",) @app.get(\"/\")def hello_world(): return {\"Hello\": \"World\"}"
},
{
"code": null,
"e": 1653,
"s": 1345,
"text": "To use app, first fork the repository to create a copy in your own Github account. This is necessary to complete the steps using Github Actions. If you want to use the example code for this guide fork the repo by going to this URL: https://github.com/bmaelum/fastapi-hello-world and click the “Fork” button."
},
{
"code": null,
"e": 1714,
"s": 1653,
"text": "To be able to test the code, clone the repo to your machine:"
},
{
"code": null,
"e": 1779,
"s": 1714,
"text": "git clone [email protected]:<your-username>/fastapi-hello-world.git"
},
{
"code": null,
"e": 1867,
"s": 1779,
"text": "Then install the requirements found in the requirements.txt file into your environment:"
},
{
"code": null,
"e": 1899,
"s": 1867,
"text": "pip install -r requirements.txt"
},
{
"code": null,
"e": 1928,
"s": 1899,
"text": "To run the app, simply type:"
},
{
"code": null,
"e": 1949,
"s": 1928,
"text": "uvicorn app.main:app"
},
{
"code": null,
"e": 2001,
"s": 1949,
"text": "You should see something like this in the terminal:"
},
{
"code": null,
"e": 2075,
"s": 2001,
"text": "INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)"
},
{
"code": null,
"e": 2267,
"s": 2075,
"text": "Testing the app can be done in the browser or with a tool like Postman. To check out the app in your browser simply go to the URL printed in the terminal, in this case: http://127.0.0.1:8000."
},
{
"code": null,
"e": 2305,
"s": 2267,
"text": "Now, let’s Dockerize the application."
},
{
"code": null,
"e": 2496,
"s": 2305,
"text": "Using Docker to deploy your app is great for many reasons, one of them is that it helps you make sure you have the same environment for your local development as for the deployment on Azure."
},
{
"code": null,
"e": 2590,
"s": 2496,
"text": "Make sure you have a suitable Dockerfile. In the example file the Dockerfile looks like this:"
},
{
"code": null,
"e": 2729,
"s": 2590,
"text": "FROM tiangolo/uvicorn-gunicorn-fastapi:python3.7 COPY ./app /app COPY requirements.txt .RUN pip --no-cache-dir install -r requirements.txt"
},
{
"code": null,
"e": 2767,
"s": 2729,
"text": "To build the Docker image simply run:"
},
{
"code": null,
"e": 2799,
"s": 2767,
"text": "docker build -t fastapi-image ."
},
{
"code": null,
"e": 2844,
"s": 2799,
"text": "To run the image in a container, simply run:"
},
{
"code": null,
"e": 2882,
"s": 2844,
"text": "docker run -p 80:80 -it fastapi-image"
},
{
"code": null,
"e": 2998,
"s": 2882,
"text": "To test the app you can use the same address as before, just change the port to 80, like this: http://127.0.0.1:80."
},
{
"code": null,
"e": 3066,
"s": 2998,
"text": "Your app works locally, great! Now it’s time to deploy it to Azure!"
},
{
"code": null,
"e": 3102,
"s": 3066,
"text": "Ready to deploy to Azure? Exciting!"
},
{
"code": null,
"e": 3214,
"s": 3102,
"text": "Deploying the app to Azure requires us doing a few actions in the Azure portal as well as using Github Actions."
},
{
"code": null,
"e": 3392,
"s": 3214,
"text": "This guide will now be following the official documentation of Microsoft found here: https://docs.microsoft.com/en-us/azure/container-instances/container-instances-github-action"
},
{
"code": null,
"e": 3588,
"s": 3392,
"text": "Firstly we need to create a Service Principal, a role, in the desired resource group. If you don’t already have a resource group simply create one by going to Resource groups in the Azure portal."
},
{
"code": null,
"e": 3732,
"s": 3588,
"text": "To create a Service Principal we are using Bash in the Azure Cloud Shell. Open this by clicking on the Cloud Shell icon on the top of the page:"
},
{
"code": null,
"e": 3796,
"s": 3732,
"text": "Make sure it is set to Bash in the top left of the Cloud Shell:"
},
{
"code": null,
"e": 3975,
"s": 3796,
"text": "Then, create a Service Principal for the Resource Group in Azure by using the following command and give the role a name and the scope is the Resource ID for your Resource Group."
},
{
"code": null,
"e": 4002,
"s": 3975,
"text": "Get the Resource Group ID:"
},
{
"code": null,
"e": 4086,
"s": 4002,
"text": "groupId=$(az group show \\ --name <resource-group-name> \\ --query id --output tsv)"
},
{
"code": null,
"e": 4103,
"s": 4086,
"text": "Create the role:"
},
{
"code": null,
"e": 4208,
"s": 4103,
"text": "az ad sp create-for-rbac \\ --name githubactions \\ --scope $groupId \\ --role Contributor \\ --sdk-auth"
},
{
"code": null,
"e": 4250,
"s": 4208,
"text": "This will give you a JSON in this format:"
},
{
"code": null,
"e": 4720,
"s": 4250,
"text": "{ \"clientId\": \"\", \"clientSecret\": \"\", \"subscriptionId\": \"\", \"tenantId\": \"\", \"activeDirectoryEndpointUrl\": \"https://login.microsoftonline.com\", \"resourceManagerEndpointUrl\": \"https://management.azure.com/\", \"activeDirectoryGraphResourceId\": \"https://graph.windows.net/\", \"sqlManagementEndpointUrl\": \"https://management.core.windows.net:8443/\", \"galleryEndpointUrl\": \"https://gallery.azure.com/\", \"managementEndpointUrl\": \"https://management.core.windows.net/\"}"
},
{
"code": null,
"e": 4805,
"s": 4720,
"text": "Make sure to save this as it will be used to authenticate when using Github Actions."
},
{
"code": null,
"e": 4899,
"s": 4805,
"text": "To manage a Docker container and images you need to create a Container Registry within Azure."
},
{
"code": null,
"e": 5063,
"s": 4899,
"text": "Search for “Container registries” and choose “Create”. Choose your resource group, a name for the instance and a location. For SKU you can choose the Basic option."
},
{
"code": null,
"e": 5120,
"s": 5063,
"text": "Great, let’s get going with the setup of Github Actions."
},
{
"code": null,
"e": 5199,
"s": 5120,
"text": "Remember the JSON you collected in the previous step? Now it’s time to use it."
},
{
"code": null,
"e": 5333,
"s": 5199,
"text": "Go to Github and the repository containing your app. Then go to Settings -> Secrets and add the following credentials(official docs):"
},
{
"code": null,
"e": 5414,
"s": 5333,
"text": "AZURE_CREDENTIALSThe entire JSON output from the service principal creation step"
},
{
"code": null,
"e": 5522,
"s": 5414,
"text": "REGISTRY_LOGIN_SERVERThe login server name of your registry (all lowercase). Example: myregistry.azurecr.io"
},
{
"code": null,
"e": 5609,
"s": 5522,
"text": "REGISTRY_USERNAMEThe clientId from the JSON output from the service principal creation"
},
{
"code": null,
"e": 5700,
"s": 5609,
"text": "REGISTRY_PASSWORDThe clientSecret from the JSON output from the service principal creation"
},
{
"code": null,
"e": 5785,
"s": 5700,
"text": "RESOURCE_GROUPThe name of the resource group you used to scope the service principal"
},
{
"code": null,
"e": 5967,
"s": 5785,
"text": "Now, let’s setup the workflow using Github Actions. Firstly, go to your repo on Github and click the “Actions” button. From there, choose “Skip this and set up a workflow yourself”."
},
{
"code": null,
"e": 6039,
"s": 5967,
"text": "Replace the existing code in the main.yml file with the following code:"
},
{
"code": null,
"e": 7464,
"s": 6039,
"text": "on: [push]name: PythonAppAzureDeploymentjobs: build-and-deploy: runs-on: ubuntu-latest steps: # checkout the repo - name: 'Checkout GitHub Action' uses: actions/checkout@main - name: 'Login via Azure CLI' uses: azure/login@v1 with: creds: ${{ secrets.AZURE_CREDENTIALS }} - name: 'Build and push image' uses: azure/docker-login@v1 with: login-server: ${{ secrets.REGISTRY_LOGIN_SERVER }} username: ${{ secrets.REGISTRY_USERNAME }} password: ${{ secrets.REGISTRY_PASSWORD }} - run: | docker build . -t ${{ secrets.REGISTRY_LOGIN_SERVER }}/sampleapp:${{ github.sha }} docker push ${{ secrets.REGISTRY_LOGIN_SERVER }}/sampleapp:${{ github.sha }} - name: 'Deploy to Azure Container Instances' uses: 'azure/aci-deploy@v1' with: resource-group: ${{ secrets.RESOURCE_GROUP }} dns-name-label: ${{ secrets.RESOURCE_GROUP }}${{ github.run_number }} image: ${{ secrets.REGISTRY_LOGIN_SERVER }}/sampleapp:${{ github.sha }} registry-login-server: ${{ secrets.REGISTRY_LOGIN_SERVER }} registry-username: ${{ secrets.REGISTRY_USERNAME }} registry-password: ${{ secrets.REGISTRY_PASSWORD }} name: fastapi-sampleapp location: 'west europe'"
},
{
"code": null,
"e": 7629,
"s": 7464,
"text": "Then, commit the file and because we have specified “on: push” it will run straight away. If it doesn’t make sure the code has been commited and pushed to the repo."
},
{
"code": null,
"e": 7763,
"s": 7629,
"text": "Now, wait for the code to be built and deployed. You can follow the progress by clicking “Actions” and choosing the running pipeline."
},
{
"code": null,
"e": 7785,
"s": 7763,
"text": "If you get the error:"
},
{
"code": null,
"e": 7875,
"s": 7785,
"text": "Error: The subscription is not registered to use namespace ‘Microsoft.ContainerInstance’."
},
{
"code": null,
"e": 7914,
"s": 7875,
"text": "Simply do the following in PowerShell:"
},
{
"code": null,
"e": 7989,
"s": 7914,
"text": "Register-AzResourceProvider -ProviderNamespace Microsoft.ContainerInstance"
},
{
"code": null,
"e": 8176,
"s": 7989,
"text": "Alternatively, in Azure, you can go to “Subscriptions”, choose your subscription, go to Resource Providers, search for “ContainerInstance”, click the desired result and click “Register”."
},
{
"code": null,
"e": 8277,
"s": 8176,
"text": "Your Dockerized app should now be visible when going to the Container Instances in the Azure portal."
}
]
|
Filtering Tweets by Location. Regular Expressions + Account Location... | by Leah Pope | Towards Data Science | In my latest project, I explored the question, “What is the public sentiment in the United States on K-12 learning during the COVID-19 pandemic?”. Using data collected from Twitter, Natural Language Processing, and Supervised Machine Learning, I created a text classifier to predict Tweets' sentiment on this topic.
Since I wanted to hone in on sentiment in the United States, I needed to filter Tweets by location. The Twitter Developer site offers some good guidance here on the available options.
I choose to use the Account Location geographical metadata. Here are the details from the Twitter Developer website: “Based on the ‘home’ location provided by the user in their public profile. This is a free-form character field and may or may not contain metadata that can be geo-referenced”.
Before we begin, here are a few caveats:
Since Account Location is not guaranteed to be populated, you have to accept the fact that you’ll potentially miss out on relevant Tweets.
The approach I used depends on Account Location containing a US identifier(such as a valid US state name).
If those caveats are acceptable to you, keep reading. :)
Before I share the actual code, here’s a rundown of my methodology:
I created a Python script to listen in on Twitter Stream for pertinent Tweets on my subject(s) of interest.
Upon getting a Tweet, I get the Account Location attribute and use regular expressions to check if it’s a US Location.
Tweets that pass the Location check carry on through my code for further processing. (In my case, I stored the Tweet in a MongoDB collection.)
Now that I’ve shared the overall workflow let’s look at some code.
My script uses a tweepy.StreamListener to listen for incoming Tweets off the Twitter Stream. The magic happens in my StreamListener’s on_status function.
def on_status(self, tweet): # Checking tweet for likely USA location is_usa_loc = self.get_is_usa_loc(tweet) if is_usa_loc: # insert the tweet into collection twitter_collection.insert(tweet_doc) else: print(‘Could not determine USA location’)def get_is_usa_loc(self, tweet): is_usa_loc = False if tweet.user.location: user_loc_str = str(tweet.user.location).upper() is_usa_loc = re.search(usa_states_regex, user_loc_str) or re.search(usa_states_fullname_regex, user_loc_str) return is_usa_loc
Within on_status, I call a helper function: get_is_usa_loc. In this helper function, I first check to ensure that Account Location is actually populated in the Tweet. If so, I convert Account Location to an upper case String and check it against two regular expressions. One regex checks for US state two-character abbreviations. The other regex checks for US state full names. The Account Location only has to match one. :)
Here are the regular expressions I used. The first is for state abbreviations, and the second is for full state names and the term ‘USA’.
usa_states_regex = ‘,\s{1(A[KLRZ]|C[AOT]|D[CE]|FL|GA|HI|I[ADLN]|K[SY]|LA|M[ADEINOST]|N[CDEHJMVY]|O[HKR]|P[AR]|RI|S[CD]|T[NX]|UT|V[AIT]|W[AIVY])’usa_states_fullname_regex = '(ALABAMA|ALASKA|ARIZONA|ARKANSAS|CALIFORNIA|'\ 'COLORADO|CONNECTICUT|DELAWARE|FLORIDA|GEORGIA|HAWAII|'\ 'IDAHO|ILLINOIS|INDIANA|IOWA|KANSAS|KENTUCKY|'\ 'LOUISIANA|MAINE|MARYLAND|MASSACHUSETTS|MICHIGAN|'\ 'MINNESOTA|MISSISSIPPI|MISSOURI|MONTANA|'\ 'NEBRASKA|NEVADA|NEW\sHAMPSHIRE|NEWSJERSEY|'\ 'NEW\sMEXICO|NEW\sYORK|NORTH\sCAROLINA|'\ 'NORTH\sDAKOTA|OHIO|OKLAHOMA|OREGON|PENNSYLVANIA|'\ 'RHODE\sISLAND|SOUTH\sCAROLINA|SOUTH\sDAKOTA|'\ 'TENNESSEE|TEXAS|UTAH|VERMONT|VIRGINIA|'\ 'WASHINGTON|WEST\sVIRGINIA|WISCONSIN|WYOMING|USA)'
And that’s it! I’ve just walked you through my process of filtering Twitter data by Account Location using some straightforward Python code along with regular expressions.
If you’ve found this helpful, I encourage you to expand on this example in your own work. Please feel free to reach out with suggestions for improvement or let me know if this has helped you. | [
{
"code": null,
"e": 488,
"s": 172,
"text": "In my latest project, I explored the question, “What is the public sentiment in the United States on K-12 learning during the COVID-19 pandemic?”. Using data collected from Twitter, Natural Language Processing, and Supervised Machine Learning, I created a text classifier to predict Tweets' sentiment on this topic."
},
{
"code": null,
"e": 672,
"s": 488,
"text": "Since I wanted to hone in on sentiment in the United States, I needed to filter Tweets by location. The Twitter Developer site offers some good guidance here on the available options."
},
{
"code": null,
"e": 966,
"s": 672,
"text": "I choose to use the Account Location geographical metadata. Here are the details from the Twitter Developer website: “Based on the ‘home’ location provided by the user in their public profile. This is a free-form character field and may or may not contain metadata that can be geo-referenced”."
},
{
"code": null,
"e": 1007,
"s": 966,
"text": "Before we begin, here are a few caveats:"
},
{
"code": null,
"e": 1146,
"s": 1007,
"text": "Since Account Location is not guaranteed to be populated, you have to accept the fact that you’ll potentially miss out on relevant Tweets."
},
{
"code": null,
"e": 1253,
"s": 1146,
"text": "The approach I used depends on Account Location containing a US identifier(such as a valid US state name)."
},
{
"code": null,
"e": 1310,
"s": 1253,
"text": "If those caveats are acceptable to you, keep reading. :)"
},
{
"code": null,
"e": 1378,
"s": 1310,
"text": "Before I share the actual code, here’s a rundown of my methodology:"
},
{
"code": null,
"e": 1486,
"s": 1378,
"text": "I created a Python script to listen in on Twitter Stream for pertinent Tweets on my subject(s) of interest."
},
{
"code": null,
"e": 1605,
"s": 1486,
"text": "Upon getting a Tweet, I get the Account Location attribute and use regular expressions to check if it’s a US Location."
},
{
"code": null,
"e": 1748,
"s": 1605,
"text": "Tweets that pass the Location check carry on through my code for further processing. (In my case, I stored the Tweet in a MongoDB collection.)"
},
{
"code": null,
"e": 1815,
"s": 1748,
"text": "Now that I’ve shared the overall workflow let’s look at some code."
},
{
"code": null,
"e": 1969,
"s": 1815,
"text": "My script uses a tweepy.StreamListener to listen for incoming Tweets off the Twitter Stream. The magic happens in my StreamListener’s on_status function."
},
{
"code": null,
"e": 2519,
"s": 1969,
"text": "def on_status(self, tweet): # Checking tweet for likely USA location is_usa_loc = self.get_is_usa_loc(tweet) if is_usa_loc: # insert the tweet into collection twitter_collection.insert(tweet_doc) else: print(‘Could not determine USA location’)def get_is_usa_loc(self, tweet): is_usa_loc = False if tweet.user.location: user_loc_str = str(tweet.user.location).upper() is_usa_loc = re.search(usa_states_regex, user_loc_str) or re.search(usa_states_fullname_regex, user_loc_str) return is_usa_loc"
},
{
"code": null,
"e": 2944,
"s": 2519,
"text": "Within on_status, I call a helper function: get_is_usa_loc. In this helper function, I first check to ensure that Account Location is actually populated in the Tweet. If so, I convert Account Location to an upper case String and check it against two regular expressions. One regex checks for US state two-character abbreviations. The other regex checks for US state full names. The Account Location only has to match one. :)"
},
{
"code": null,
"e": 3082,
"s": 2944,
"text": "Here are the regular expressions I used. The first is for state abbreviations, and the second is for full state names and the term ‘USA’."
},
{
"code": null,
"e": 4053,
"s": 3082,
"text": "usa_states_regex = ‘,\\s{1(A[KLRZ]|C[AOT]|D[CE]|FL|GA|HI|I[ADLN]|K[SY]|LA|M[ADEINOST]|N[CDEHJMVY]|O[HKR]|P[AR]|RI|S[CD]|T[NX]|UT|V[AIT]|W[AIVY])’usa_states_fullname_regex = '(ALABAMA|ALASKA|ARIZONA|ARKANSAS|CALIFORNIA|'\\ 'COLORADO|CONNECTICUT|DELAWARE|FLORIDA|GEORGIA|HAWAII|'\\ 'IDAHO|ILLINOIS|INDIANA|IOWA|KANSAS|KENTUCKY|'\\ 'LOUISIANA|MAINE|MARYLAND|MASSACHUSETTS|MICHIGAN|'\\ 'MINNESOTA|MISSISSIPPI|MISSOURI|MONTANA|'\\ 'NEBRASKA|NEVADA|NEW\\sHAMPSHIRE|NEWSJERSEY|'\\ 'NEW\\sMEXICO|NEW\\sYORK|NORTH\\sCAROLINA|'\\ 'NORTH\\sDAKOTA|OHIO|OKLAHOMA|OREGON|PENNSYLVANIA|'\\ 'RHODE\\sISLAND|SOUTH\\sCAROLINA|SOUTH\\sDAKOTA|'\\ 'TENNESSEE|TEXAS|UTAH|VERMONT|VIRGINIA|'\\ 'WASHINGTON|WEST\\sVIRGINIA|WISCONSIN|WYOMING|USA)'"
},
{
"code": null,
"e": 4225,
"s": 4053,
"text": "And that’s it! I’ve just walked you through my process of filtering Twitter data by Account Location using some straightforward Python code along with regular expressions."
}
]
|
How to build a simple GUI calculator using tkinter in Python | In Python, we use the tkinter library to create GUI components and craft better user interface.
In this article you will learn methods to build a simple GUI based calculator application.
Before we jump into it, there are a few things we need to get organised first.
Let us start by downloading Python’s imaging library that we will be using to get images from our local system. In order to install PIL(Pillow), launch you terminal and type the command below.
pip install Pillow
Now that you have the package installed. You will have to download icons needed for the calculator.
You can go on Google images and download the required icons. However, if you want the same set of icons I’ve used for this project, you can download it from −
https://www.dropbox.com/sh/0zqd6zd9b8asmor/AAC3d2iOvMRl8INkbCuMUo_ya?dl=0.
Make sure you download all the icons to a folder named “asset”.
Next up, we need to import the required modules.
from tkinter import *
from PIL import Image # pip install Pillow
from PIL import ImageTk
And that’s it. You must now have everything set up and ready to get started.
Firstly, we must create the functions the GUI components will use.
There are three main functions, one when the number or symbol is pressed, another when the equal to button is pressed and then finally when the clear button is pressed.
Let us first initialise few global variables −
txt = ""
res = False
ans = 0
Function when number of key is pressed −
def press(num):
global txt, ans, res
if (res==True):
txt = ans
res = False
txt = txt + str(num)
equation.set(txt)
Function when the equal to button is pressed −
def equal():
try:
global txt, ans, res
ans = str(eval(txt))
equation.set(ans)
res = True
except:
equation.set("ERROR : Invalid Equation")
txt=""
Function when the clear button is pressed −
def clear():
global txt, ans, res
txt = ""
equation.set("")
res = False
Now that we’ve defined the functions, we can start the main function and start working on the GUI components.
if __name__ == "__main__":
window = Tk()
window.configure(background="black")
window.title("Calculator")
window.iconbitmap("assets\Calculator\Logo.ico")
window.geometry("343x417")
window.resizable(0,0)
The above lines of code will structure a perfect calculator.
Note − In order to avoid getting errors, make sure you follow the exact file structure as the code above. Save the logo icon inside the Calculator folder which is within the assets folder.
Follow the below format −
+---Working Directory
+---Calculator.py
+---assets
+---Calculator
+---All the icons.
Next up, let us design the text field where we will see the numbers.
equation = StringVar()
txt_field = Entry(relief=RIDGE,textvariable=equation,bd=10,font=("Aerial",20),bg="powder blue")
txt_field.grid(columnspan=4,ipady=10,ipadx=10,sticky="nsew")
Now, we will follow a repetitive procedure of adding icons to the GUI window, one by one. Below is a single example of it, follow it for the rest or just copy it from the complete code at the end of this article.
width=80
height=80
img1 = Image.open("assets/Calculator/one.PNG")
img1 = img1.resize((width,height))
oneImage = ImageTk.PhotoImage(img1)
button1 = Button(window, image=oneImage,bg="white",command = lambda:press(1),height=height,width=width)
button1.grid(row=2,column=0,sticky="nsew")
Similar to the above lines, follow for button2, button3 and on until you cover all the numbers and symbols.
And that’s it. If you run the program now, you must see a very abstract looking calculator.
In case you are not able to follow up, you can take the complete code from below.
from tkinter import *
from PIL import Image
from PIL import ImageTk
txt = ""
res = False
ans = 0
def press(num):
global txt, ans, res
if (res==True):
txt = ans
res = False
txt = txt + str(num)
equation.set(txt)
def equal():
try:
global txt, ans, res
ans = str(eval(txt))
equation.set(ans)
res = True
except:
equation.set("ERROR : Invalid Equation")
txt=""
def clear():
global txt, ans, res
txt = ""
equation.set("")
res = False
if __name__ == "__main__":
window = Tk()
window.configure(background="black")
window.title("Calculator")
window.iconbitmap("assets\Calculator\Logo.ico")
window.geometry("343x417")
window.resizable(0,0)
equation = StringVar()
txt_field = Entry(relief=RIDGE,textvariable=equation,bd=10,font=("Aerial",20),bg="powder blue")
txt_field.grid(columnspan=4,ipady=10,ipadx=10,sticky="nsew")
width=80
height=80
img1 = Image.open("assets/Calculator/one.PNG")
img1 = img1.resize((width,height))
oneImage = ImageTk.PhotoImage(img1)
button1 = Button(window, image=oneImage,bg="white",command = lambda:press(1),height=height,width=width)
button1.grid(row=2,column=0,sticky="nsew")
img2 = Image.open("assets/Calculator/two.PNG")
img2 = img2.resize((width,height))
twoImage = ImageTk.PhotoImage(img2)
button2 = Button(window, image=twoImage,bg="white",command = lambda:press(2),height=height,width=width)
button2.grid(row=2,column=1,sticky="nsew")
img3 = Image.open("assets/Calculator/three.PNG")
img3 = img3.resize((width,height))
threeImage = ImageTk.PhotoImage(img3)
button3 = Button(window, image=threeImage,bg="white",command = lambda:press(3),height=height,width=width)
button3.grid(row=2,column=2,sticky="nsew")
img4 = Image.open("assets/Calculator/four.PNG")
img4 = img4.resize((width,height))
fourImage = ImageTk.PhotoImage(img4)
button4 = Button(window, image=fourImage,bg="white",command = lambda:press(4),height=height,width=width)
button4.grid(row=3,column=0,sticky="nsew")
img5 = Image.open("assets/Calculator/five.PNG")
img5 = img5.resize((width,height))
fiveImage = ImageTk.PhotoImage(img5)
button5 = Button(window, image=fiveImage,bg="white",command = lambda:press(5),height=height,width=width)
button5.grid(row=3,column=1,sticky="nsew")
img6 = Image.open("assets/Calculator/six.PNG")
img6 = img6.resize((width,height))
sixImage = ImageTk.PhotoImage(img6)
button6 = Button(window, image=sixImage,bg="white",command = lambda:press(6),height=height,width=width)
button6.grid(row=3,column=2,sticky="nsew")
img7 = Image.open("assets/Calculator/seven.PNG")
img7 = img7.resize((width,height))
sevenImage = ImageTk.PhotoImage(img7)
button7 = Button(window, image=sevenImage,bg="white",command = lambda:press(7),height=height,width=width)
button7.grid(row=4,column=0,sticky="nsew")
img8 = Image.open("assets/Calculator/eight.PNG")
img8 = img8.resize((width,height))
eightImage = ImageTk.PhotoImage(img8)
button8 = Button(window, image=eightImage,bg="white",command = lambda:press(8),height=height,width=width)
button8.grid(row=4,column=1,sticky="nsew")
img9 = Image.open("assets/Calculator/nine.PNG")
img9 = img9.resize((width,height))
nineImage = ImageTk.PhotoImage(img9)
button9 = Button(window, image=nineImage,bg="white",command = lambda:press(9),height=height,width=width)
button9.grid(row=4,column=2,sticky="nsew")
img0 = Image.open("assets/Calculator/zero.PNG")
img0 = img0.resize((width,height))
zeroImage = ImageTk.PhotoImage(img0)
button0 = Button(window, image=zeroImage,bg="white",command = lambda:press(0),height=height,width=width)
button0.grid(row=5,column=1,sticky="nsew")
imgx = Image.open("assets/Calculator/multiply.PNG")
imgx = imgx.resize((width,height))
multiplyImage = ImageTk.PhotoImage(imgx)
buttonx = Button(window, image=multiplyImage,bg="white",command = lambda:press("*"),height=height,width=width)
buttonx.grid(row=2,column=3,sticky="nsew")
imgadd = Image.open("assets/Calculator/add.PNG")
imgadd = imgadd.resize((width,height))
addImage = ImageTk.PhotoImage(imgadd)
buttonadd = Button(window, image=addImage,bg="white",command = lambda:press("+"),height=height,width=width)
buttonadd.grid(row=3,column=3,sticky="nsew")
imgdiv = Image.open("assets/Calculator/divide.PNG")
imgdiv = imgdiv.resize((width,height))
divImage = ImageTk.PhotoImage(imgdiv)
buttondiv = Button(window, image=divImage,bg="white",command = lambda:press("/"),height=height,width=width)
buttondiv.grid(row=5,column=3,sticky="nsew")
imgsub = Image.open("assets/Calculator/subtract.PNG")
imgsub = imgsub.resize((width,height))
subImage = ImageTk.PhotoImage(imgsub)
buttonsub = Button(window, image=subImage,bg="white",command = lambda:press("- "),height=height,width=width)
buttonsub.grid(row=4,column=3,sticky="nsew")
imgeq = Image.open("assets/Calculator/equal.PNG")
imgeq = imgeq.resize((width,height))
eqImage = ImageTk.PhotoImage(imgeq)
buttoneq = Button(window, image=eqImage,bg="white",command = equal,height=height,width=width)
buttoneq.grid(row=5,column=2,sticky="nsew")
imgclear = Image.open("assets/Calculator/clear.PNG")
imgclear = imgclear.resize((width,height))
clearImage = ImageTk.PhotoImage(imgclear)
buttonclear = Button(window, image=clearImage,bg="white",command = clear,height=height,width=width)
buttonclear.grid(row=5,column=0,sticky="nsew")
window.mainloop()
If you are having formatting issues with the above program, you can obtain it from https://github.com/SVijayB/PyHub/blob/master/Graphics/Simple%20Calculator.py as well. | [
{
"code": null,
"e": 1158,
"s": 1062,
"text": "In Python, we use the tkinter library to create GUI components and craft better user interface."
},
{
"code": null,
"e": 1249,
"s": 1158,
"text": "In this article you will learn methods to build a simple GUI based calculator application."
},
{
"code": null,
"e": 1328,
"s": 1249,
"text": "Before we jump into it, there are a few things we need to get organised first."
},
{
"code": null,
"e": 1521,
"s": 1328,
"text": "Let us start by downloading Python’s imaging library that we will be using to get images from our local system. In order to install PIL(Pillow), launch you terminal and type the command below."
},
{
"code": null,
"e": 1540,
"s": 1521,
"text": "pip install Pillow"
},
{
"code": null,
"e": 1640,
"s": 1540,
"text": "Now that you have the package installed. You will have to download icons needed for the calculator."
},
{
"code": null,
"e": 1799,
"s": 1640,
"text": "You can go on Google images and download the required icons. However, if you want the same set of icons I’ve used for this project, you can download it from −"
},
{
"code": null,
"e": 1874,
"s": 1799,
"text": "https://www.dropbox.com/sh/0zqd6zd9b8asmor/AAC3d2iOvMRl8INkbCuMUo_ya?dl=0."
},
{
"code": null,
"e": 1938,
"s": 1874,
"text": "Make sure you download all the icons to a folder named “asset”."
},
{
"code": null,
"e": 1987,
"s": 1938,
"text": "Next up, we need to import the required modules."
},
{
"code": null,
"e": 2076,
"s": 1987,
"text": "from tkinter import *\nfrom PIL import Image # pip install Pillow\nfrom PIL import ImageTk"
},
{
"code": null,
"e": 2153,
"s": 2076,
"text": "And that’s it. You must now have everything set up and ready to get started."
},
{
"code": null,
"e": 2220,
"s": 2153,
"text": "Firstly, we must create the functions the GUI components will use."
},
{
"code": null,
"e": 2389,
"s": 2220,
"text": "There are three main functions, one when the number or symbol is pressed, another when the equal to button is pressed and then finally when the clear button is pressed."
},
{
"code": null,
"e": 2436,
"s": 2389,
"text": "Let us first initialise few global variables −"
},
{
"code": null,
"e": 2465,
"s": 2436,
"text": "txt = \"\"\nres = False\nans = 0"
},
{
"code": null,
"e": 2506,
"s": 2465,
"text": "Function when number of key is pressed −"
},
{
"code": null,
"e": 2644,
"s": 2506,
"text": "def press(num):\n global txt, ans, res\n if (res==True):\n txt = ans\n res = False\n txt = txt + str(num)\n equation.set(txt)"
},
{
"code": null,
"e": 2691,
"s": 2644,
"text": "Function when the equal to button is pressed −"
},
{
"code": null,
"e": 2878,
"s": 2691,
"text": "def equal():\n try:\n global txt, ans, res\n ans = str(eval(txt))\n equation.set(ans)\n res = True\n except:\n equation.set(\"ERROR : Invalid Equation\")\n txt=\"\""
},
{
"code": null,
"e": 2922,
"s": 2878,
"text": "Function when the clear button is pressed −"
},
{
"code": null,
"e": 3006,
"s": 2922,
"text": "def clear():\n global txt, ans, res\n txt = \"\"\n equation.set(\"\")\n res = False"
},
{
"code": null,
"e": 3116,
"s": 3006,
"text": "Now that we’ve defined the functions, we can start the main function and start working on the GUI components."
},
{
"code": null,
"e": 3336,
"s": 3116,
"text": "if __name__ == \"__main__\":\n window = Tk()\n window.configure(background=\"black\")\n window.title(\"Calculator\")\n window.iconbitmap(\"assets\\Calculator\\Logo.ico\")\n window.geometry(\"343x417\")\n window.resizable(0,0)"
},
{
"code": null,
"e": 3397,
"s": 3336,
"text": "The above lines of code will structure a perfect calculator."
},
{
"code": null,
"e": 3586,
"s": 3397,
"text": "Note − In order to avoid getting errors, make sure you follow the exact file structure as the code above. Save the logo icon inside the Calculator folder which is within the assets folder."
},
{
"code": null,
"e": 3612,
"s": 3586,
"text": "Follow the below format −"
},
{
"code": null,
"e": 3718,
"s": 3612,
"text": "+---Working Directory\n +---Calculator.py\n +---assets\n +---Calculator\n +---All the icons."
},
{
"code": null,
"e": 3787,
"s": 3718,
"text": "Next up, let us design the text field where we will see the numbers."
},
{
"code": null,
"e": 3969,
"s": 3787,
"text": "equation = StringVar()\n\ntxt_field = Entry(relief=RIDGE,textvariable=equation,bd=10,font=(\"Aerial\",20),bg=\"powder blue\")\n\ntxt_field.grid(columnspan=4,ipady=10,ipadx=10,sticky=\"nsew\")"
},
{
"code": null,
"e": 4182,
"s": 3969,
"text": "Now, we will follow a repetitive procedure of adding icons to the GUI window, one by one. Below is a single example of it, follow it for the rest or just copy it from the complete code at the end of this article."
},
{
"code": null,
"e": 4466,
"s": 4182,
"text": "width=80\nheight=80\nimg1 = Image.open(\"assets/Calculator/one.PNG\")\nimg1 = img1.resize((width,height))\noneImage = ImageTk.PhotoImage(img1)\nbutton1 = Button(window, image=oneImage,bg=\"white\",command = lambda:press(1),height=height,width=width)\nbutton1.grid(row=2,column=0,sticky=\"nsew\")"
},
{
"code": null,
"e": 4574,
"s": 4466,
"text": "Similar to the above lines, follow for button2, button3 and on until you cover all the numbers and symbols."
},
{
"code": null,
"e": 4666,
"s": 4574,
"text": "And that’s it. If you run the program now, you must see a very abstract looking calculator."
},
{
"code": null,
"e": 4748,
"s": 4666,
"text": "In case you are not able to follow up, you can take the complete code from below."
},
{
"code": null,
"e": 10350,
"s": 4748,
"text": "from tkinter import *\nfrom PIL import Image\nfrom PIL import ImageTk\n\ntxt = \"\"\nres = False\nans = 0\n\ndef press(num):\n global txt, ans, res\n if (res==True):\n txt = ans\n res = False\n txt = txt + str(num)\n equation.set(txt)\ndef equal():\n try:\n global txt, ans, res\n ans = str(eval(txt))\n equation.set(ans)\n res = True\n except:\n equation.set(\"ERROR : Invalid Equation\")\n txt=\"\"\ndef clear():\n global txt, ans, res\n txt = \"\"\n equation.set(\"\")\n res = False\nif __name__ == \"__main__\":\n window = Tk()\n window.configure(background=\"black\")\n window.title(\"Calculator\")\n window.iconbitmap(\"assets\\Calculator\\Logo.ico\")\n window.geometry(\"343x417\")\n window.resizable(0,0)\n equation = StringVar()\n txt_field = Entry(relief=RIDGE,textvariable=equation,bd=10,font=(\"Aerial\",20),bg=\"powder blue\")\n txt_field.grid(columnspan=4,ipady=10,ipadx=10,sticky=\"nsew\")\n width=80\n height=80\n img1 = Image.open(\"assets/Calculator/one.PNG\")\n img1 = img1.resize((width,height))\n oneImage = ImageTk.PhotoImage(img1)\n button1 = Button(window, image=oneImage,bg=\"white\",command = lambda:press(1),height=height,width=width)\n button1.grid(row=2,column=0,sticky=\"nsew\")\n img2 = Image.open(\"assets/Calculator/two.PNG\")\n img2 = img2.resize((width,height))\n twoImage = ImageTk.PhotoImage(img2)\n button2 = Button(window, image=twoImage,bg=\"white\",command = lambda:press(2),height=height,width=width)\n button2.grid(row=2,column=1,sticky=\"nsew\")\n img3 = Image.open(\"assets/Calculator/three.PNG\")\n img3 = img3.resize((width,height))\n threeImage = ImageTk.PhotoImage(img3)\n button3 = Button(window, image=threeImage,bg=\"white\",command = lambda:press(3),height=height,width=width)\n button3.grid(row=2,column=2,sticky=\"nsew\")\n img4 = Image.open(\"assets/Calculator/four.PNG\")\n img4 = img4.resize((width,height))\n fourImage = ImageTk.PhotoImage(img4)\n button4 = Button(window, image=fourImage,bg=\"white\",command = lambda:press(4),height=height,width=width)\n button4.grid(row=3,column=0,sticky=\"nsew\")\n img5 = Image.open(\"assets/Calculator/five.PNG\")\n img5 = img5.resize((width,height))\n fiveImage = ImageTk.PhotoImage(img5)\n button5 = Button(window, image=fiveImage,bg=\"white\",command = lambda:press(5),height=height,width=width)\n button5.grid(row=3,column=1,sticky=\"nsew\")\n img6 = Image.open(\"assets/Calculator/six.PNG\")\n img6 = img6.resize((width,height))\n sixImage = ImageTk.PhotoImage(img6)\n button6 = Button(window, image=sixImage,bg=\"white\",command = lambda:press(6),height=height,width=width)\n button6.grid(row=3,column=2,sticky=\"nsew\")\n img7 = Image.open(\"assets/Calculator/seven.PNG\")\n img7 = img7.resize((width,height))\n sevenImage = ImageTk.PhotoImage(img7)\n button7 = Button(window, image=sevenImage,bg=\"white\",command = lambda:press(7),height=height,width=width)\n button7.grid(row=4,column=0,sticky=\"nsew\")\n img8 = Image.open(\"assets/Calculator/eight.PNG\")\n img8 = img8.resize((width,height))\n eightImage = ImageTk.PhotoImage(img8)\n button8 = Button(window, image=eightImage,bg=\"white\",command = lambda:press(8),height=height,width=width)\n button8.grid(row=4,column=1,sticky=\"nsew\")\n img9 = Image.open(\"assets/Calculator/nine.PNG\")\n img9 = img9.resize((width,height))\n nineImage = ImageTk.PhotoImage(img9)\n button9 = Button(window, image=nineImage,bg=\"white\",command = lambda:press(9),height=height,width=width)\n button9.grid(row=4,column=2,sticky=\"nsew\")\n img0 = Image.open(\"assets/Calculator/zero.PNG\")\n img0 = img0.resize((width,height))\n zeroImage = ImageTk.PhotoImage(img0)\n button0 = Button(window, image=zeroImage,bg=\"white\",command = lambda:press(0),height=height,width=width)\n button0.grid(row=5,column=1,sticky=\"nsew\")\n imgx = Image.open(\"assets/Calculator/multiply.PNG\")\n imgx = imgx.resize((width,height))\n multiplyImage = ImageTk.PhotoImage(imgx)\n buttonx = Button(window, image=multiplyImage,bg=\"white\",command = lambda:press(\"*\"),height=height,width=width)\n buttonx.grid(row=2,column=3,sticky=\"nsew\")\n imgadd = Image.open(\"assets/Calculator/add.PNG\")\n imgadd = imgadd.resize((width,height))\n addImage = ImageTk.PhotoImage(imgadd)\n buttonadd = Button(window, image=addImage,bg=\"white\",command = lambda:press(\"+\"),height=height,width=width)\n buttonadd.grid(row=3,column=3,sticky=\"nsew\")\n imgdiv = Image.open(\"assets/Calculator/divide.PNG\")\n imgdiv = imgdiv.resize((width,height))\n divImage = ImageTk.PhotoImage(imgdiv)\n buttondiv = Button(window, image=divImage,bg=\"white\",command = lambda:press(\"/\"),height=height,width=width)\n buttondiv.grid(row=5,column=3,sticky=\"nsew\")\n imgsub = Image.open(\"assets/Calculator/subtract.PNG\")\n imgsub = imgsub.resize((width,height))\n subImage = ImageTk.PhotoImage(imgsub)\n buttonsub = Button(window, image=subImage,bg=\"white\",command = lambda:press(\"- \"),height=height,width=width)\n buttonsub.grid(row=4,column=3,sticky=\"nsew\")\n imgeq = Image.open(\"assets/Calculator/equal.PNG\")\n imgeq = imgeq.resize((width,height))\n eqImage = ImageTk.PhotoImage(imgeq)\n buttoneq = Button(window, image=eqImage,bg=\"white\",command = equal,height=height,width=width)\n buttoneq.grid(row=5,column=2,sticky=\"nsew\")\n imgclear = Image.open(\"assets/Calculator/clear.PNG\")\n imgclear = imgclear.resize((width,height))\n clearImage = ImageTk.PhotoImage(imgclear)\n buttonclear = Button(window, image=clearImage,bg=\"white\",command = clear,height=height,width=width)\nbuttonclear.grid(row=5,column=0,sticky=\"nsew\")\n\nwindow.mainloop()"
},
{
"code": null,
"e": 10519,
"s": 10350,
"text": "If you are having formatting issues with the above program, you can obtain it from https://github.com/SVijayB/PyHub/blob/master/Graphics/Simple%20Calculator.py as well."
}
]
|
Python 3 - String startswith() Method | The startswith() method checks whether the string starts with str, optionally restricting the matching with the given indices start and end.
Following is the syntax for startswith() method −
str.startswith(str, beg = 0,end = len(string));
str − This is the string to be checked.
str − This is the string to be checked.
beg − This is the optional parameter to set start index of the matching boundary.
beg − This is the optional parameter to set start index of the matching boundary.
end − This is the optional parameter to set start index of the matching boundary.
end − This is the optional parameter to set start index of the matching boundary.
This method returns true if found matching string otherwise false.
The following example shows the usage of startswith() method.
#!/usr/bin/python3
str = "this is string example....wow!!!"
print (str.startswith( 'this' ))
print (str.startswith( 'string', 8 ))
print (str.startswith( 'this', 2, 4 ))
When we run above program, it produces the following result −
True
True
False
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2481,
"s": 2340,
"text": "The startswith() method checks whether the string starts with str, optionally restricting the matching with the given indices start and end."
},
{
"code": null,
"e": 2531,
"s": 2481,
"text": "Following is the syntax for startswith() method −"
},
{
"code": null,
"e": 2580,
"s": 2531,
"text": "str.startswith(str, beg = 0,end = len(string));\n"
},
{
"code": null,
"e": 2620,
"s": 2580,
"text": "str − This is the string to be checked."
},
{
"code": null,
"e": 2660,
"s": 2620,
"text": "str − This is the string to be checked."
},
{
"code": null,
"e": 2742,
"s": 2660,
"text": "beg − This is the optional parameter to set start index of the matching boundary."
},
{
"code": null,
"e": 2824,
"s": 2742,
"text": "beg − This is the optional parameter to set start index of the matching boundary."
},
{
"code": null,
"e": 2906,
"s": 2824,
"text": "end − This is the optional parameter to set start index of the matching boundary."
},
{
"code": null,
"e": 2988,
"s": 2906,
"text": "end − This is the optional parameter to set start index of the matching boundary."
},
{
"code": null,
"e": 3055,
"s": 2988,
"text": "This method returns true if found matching string otherwise false."
},
{
"code": null,
"e": 3117,
"s": 3055,
"text": "The following example shows the usage of startswith() method."
},
{
"code": null,
"e": 3288,
"s": 3117,
"text": "#!/usr/bin/python3\n\nstr = \"this is string example....wow!!!\"\nprint (str.startswith( 'this' ))\nprint (str.startswith( 'string', 8 ))\nprint (str.startswith( 'this', 2, 4 ))"
},
{
"code": null,
"e": 3350,
"s": 3288,
"text": "When we run above program, it produces the following result −"
},
{
"code": null,
"e": 3367,
"s": 3350,
"text": "True\nTrue\nFalse\n"
},
{
"code": null,
"e": 3404,
"s": 3367,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 3420,
"s": 3404,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3453,
"s": 3420,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 3472,
"s": 3453,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3507,
"s": 3472,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 3529,
"s": 3507,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 3563,
"s": 3529,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 3591,
"s": 3563,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3626,
"s": 3591,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 3640,
"s": 3626,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3673,
"s": 3640,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3690,
"s": 3673,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 3697,
"s": 3690,
"text": " Print"
},
{
"code": null,
"e": 3708,
"s": 3697,
"text": " Add Notes"
}
]
|
stack empty() and stack size() in C++ STL | In this article we will be discussing the working, syntax and examples of stack::empty() and stack::size() function in C++ STL.
Stacks are the data structure that stores the data in LIFO (Last In First Out) where we do
insertion and deletion from the top of the last element inserted. Like a stack of plates, if we want to push a new plate into the stack we insert on the top and if we want to remove the plate from the stack we then also remove it from the top.
stack::empty() function is an inbuilt function in C++ STL, which is defined in <stack>header file. empty() is used to check whether the associated container is empty or not and return true or false accordingly.
The function checks the container should be empty means the size of the container should be 0.
stack_name.empty();
The function accepts no parameter(s).
This function returns true if the container is empty, else false.
Input
std::stack<int> stack1;
stack1.emplace(1);
stack1.emplace(2);
stack1.emplace(3);
stack1.empty();
Output
false
Input
std::stack<int> stack2;
stack2.empty();
Output
true
Live Demo
#include <iostream>
#include <stack>
using namespace std;
int main(){
stack<int> stck;
int Product = 1;
stck.push(1);
stck.push(2);
stck.push(3);
stck.push(4);
stck.push(5);
stck.push(6);
while (!stck.empty()){
Product = Product * stck.top();
stck.pop();
}
cout<<"\nProduct of elements in stack are: "<<Product;
return 0;
}
If we run the above code it will generate the following output −
Product of elements in stack are: 720
stack::size() function is an inbuilt function in C++ STL, which is defined in <stack>header file. size() is used to check the associated container’s size and return the result in an integer value, which is the number of elements in the container.
If the container is empty the size() returns 0
stack_name.size();
The function accepts no parameter(s).
This function returns the size of the container
Input
std::stack<int> stack1;
stack1.emplace(1);
stack1.emplace(2);
stack1.emplace(3);
stack1.size();
Output
3
Input
std::stack<int> stack2;
stack2.size();
Output
0
Live Demo
#include <iostream>
#include <stack>
using namespace std;
int main(){
stack<int> stck;
int Product = 1;
stck.push(1);
stck.push(2);
stck.push(3);
stck.push(4);
stck.push(5);
stck.push(6);
cout<<"size of stack is: "<<stck.size();
while (stck.size()>0){
Product = Product * stck.top();
stck.pop();
}
cout<<"\nProduct of elements in stack are: "<<Product;
return 0;
}
If we run the above code it will generate the following output −
size of stack is: 6
Product of elements in stack are: 720 | [
{
"code": null,
"e": 1190,
"s": 1062,
"text": "In this article we will be discussing the working, syntax and examples of stack::empty() and stack::size() function in C++ STL."
},
{
"code": null,
"e": 1525,
"s": 1190,
"text": "Stacks are the data structure that stores the data in LIFO (Last In First Out) where we do\ninsertion and deletion from the top of the last element inserted. Like a stack of plates, if we want to push a new plate into the stack we insert on the top and if we want to remove the plate from the stack we then also remove it from the top."
},
{
"code": null,
"e": 1736,
"s": 1525,
"text": "stack::empty() function is an inbuilt function in C++ STL, which is defined in <stack>header file. empty() is used to check whether the associated container is empty or not and return true or false accordingly."
},
{
"code": null,
"e": 1831,
"s": 1736,
"text": "The function checks the container should be empty means the size of the container should be 0."
},
{
"code": null,
"e": 1851,
"s": 1831,
"text": "stack_name.empty();"
},
{
"code": null,
"e": 1889,
"s": 1851,
"text": "The function accepts no parameter(s)."
},
{
"code": null,
"e": 1955,
"s": 1889,
"text": "This function returns true if the container is empty, else false."
},
{
"code": null,
"e": 1962,
"s": 1955,
"text": "Input "
},
{
"code": null,
"e": 2059,
"s": 1962,
"text": "std::stack<int> stack1;\nstack1.emplace(1);\nstack1.emplace(2);\nstack1.emplace(3);\nstack1.empty();"
},
{
"code": null,
"e": 2067,
"s": 2059,
"text": "Output "
},
{
"code": null,
"e": 2073,
"s": 2067,
"text": "false"
},
{
"code": null,
"e": 2080,
"s": 2073,
"text": "Input "
},
{
"code": null,
"e": 2120,
"s": 2080,
"text": "std::stack<int> stack2;\nstack2.empty();"
},
{
"code": null,
"e": 2128,
"s": 2120,
"text": "Output "
},
{
"code": null,
"e": 2133,
"s": 2128,
"text": "true"
},
{
"code": null,
"e": 2144,
"s": 2133,
"text": " Live Demo"
},
{
"code": null,
"e": 2516,
"s": 2144,
"text": "#include <iostream>\n#include <stack>\nusing namespace std;\nint main(){\n stack<int> stck;\n int Product = 1;\n stck.push(1);\n stck.push(2);\n stck.push(3);\n stck.push(4);\n stck.push(5);\n stck.push(6);\n while (!stck.empty()){\n Product = Product * stck.top();\n stck.pop();\n }\n cout<<\"\\nProduct of elements in stack are: \"<<Product;\n return 0;\n}"
},
{
"code": null,
"e": 2581,
"s": 2516,
"text": "If we run the above code it will generate the following output −"
},
{
"code": null,
"e": 2619,
"s": 2581,
"text": "Product of elements in stack are: 720"
},
{
"code": null,
"e": 2866,
"s": 2619,
"text": "stack::size() function is an inbuilt function in C++ STL, which is defined in <stack>header file. size() is used to check the associated container’s size and return the result in an integer value, which is the number of elements in the container."
},
{
"code": null,
"e": 2913,
"s": 2866,
"text": "If the container is empty the size() returns 0"
},
{
"code": null,
"e": 2932,
"s": 2913,
"text": "stack_name.size();"
},
{
"code": null,
"e": 2970,
"s": 2932,
"text": "The function accepts no parameter(s)."
},
{
"code": null,
"e": 3018,
"s": 2970,
"text": "This function returns the size of the container"
},
{
"code": null,
"e": 3025,
"s": 3018,
"text": "Input "
},
{
"code": null,
"e": 3121,
"s": 3025,
"text": "std::stack<int> stack1;\nstack1.emplace(1);\nstack1.emplace(2);\nstack1.emplace(3);\nstack1.size();"
},
{
"code": null,
"e": 3129,
"s": 3121,
"text": "Output "
},
{
"code": null,
"e": 3131,
"s": 3129,
"text": "3"
},
{
"code": null,
"e": 3137,
"s": 3131,
"text": "Input"
},
{
"code": null,
"e": 3176,
"s": 3137,
"text": "std::stack<int> stack2;\nstack2.size();"
},
{
"code": null,
"e": 3184,
"s": 3176,
"text": "Output "
},
{
"code": null,
"e": 3186,
"s": 3184,
"text": "0"
},
{
"code": null,
"e": 3197,
"s": 3186,
"text": " Live Demo"
},
{
"code": null,
"e": 3613,
"s": 3197,
"text": "#include <iostream>\n#include <stack>\nusing namespace std;\nint main(){\n stack<int> stck;\n int Product = 1;\n stck.push(1);\n stck.push(2);\n stck.push(3);\n stck.push(4);\n stck.push(5);\n stck.push(6);\n cout<<\"size of stack is: \"<<stck.size();\n while (stck.size()>0){\n Product = Product * stck.top();\n stck.pop();\n }\n cout<<\"\\nProduct of elements in stack are: \"<<Product;\n return 0;\n}"
},
{
"code": null,
"e": 3678,
"s": 3613,
"text": "If we run the above code it will generate the following output −"
},
{
"code": null,
"e": 3736,
"s": 3678,
"text": "size of stack is: 6\nProduct of elements in stack are: 720"
}
]
|
SQL Full Outer Join Using Where Clause - GeeksforGeeks | 25 Aug, 2021
A SQL join statement is used to combine rows or information from two or more than two tables on the basis of a common attribute or field. There are basically four types of JOINS in SQL.
In this article, we will discuss about FULL OUTER JOIN using WHERE clause.
Consider the two tables below:
Sample Input Table 1 :
Sample Input Table 2 :
FULL OUTER JOIN : Full Join provides result with concatenation of LEFT JOIN and RIGHT JOIN. The result will contain all the rows from both Table 1 and Table 2. The rows having no matching in result table will have NULL values.
SELECT * FROM Table1
FULL OUTER JOIN Table2
ON Table1.column_match=Table2.column_match;
Table1: First Table in Database.
Table2: Second Table in Database.
column_match: The column common to both the tables.
Sample Output :
FULL OUTER JOIN using WHERE CLAUSE : The use of WHERE clause with FULL OUTER JOIN helps to retrieve all those rows which have no entry matching on joining both the tables having NULL entry.
SELECT * FROM Table1
FULL OUTER JOIN Table2
ON Table1.column_match=Table2.column_match
WHERE Table1.column is NULL
OR Table2.column is NULL;
Table1: First Table in Database.
Table2: Second Table in Database.
column_match: The column common to both the tables.
column: The column having NULL value after Full Outer Join
The above Query returns only those customer who bought mobile phones and don’t have any record saved in Customer Information Table as well as the customer information who didn’t buy any product.
SQL QUERY FOR THE SAMPLE INPUTS : We have considered a Customer and Purchase Information of Mobile Phones from an E-Commerce site during Big Billion Days. The Database E-Commerce has two tables one has information about the Product and the other one have information about the Customer. Now, we will perform FULL OUTER JOIN between these two tables to concatenate them into a single table and get complete data about the customers and the products they purchased from the site.
BASIC SQL QUERY :
1. Creating a Database
CREATE DATABASE database_name;
2. Creating a Table
CREATE TABLE Table_name(
col_1 TYPE col_1_constraint,
col_2 TYPE col_2 constraint
.....
)
col: Column name
TYPE: Data type whether an integer, variable character, etc
col_constraint: Constraints in SQL like PRIMARY KEY, NOT NULL, UNIQUE, REFERENCES, etc
3. Inserting into a Table
INSERT INTO Table_name
VALUES(val_1, val_2, val_3, ..........)
val: Values in particular column
4. View The Table
SELECT * FROM Table_name
For more information regarding SQL syntaxes visit our website SQL Tutorial.
Output :
1. Customer Information and Purchase Information Table
Purchase Information Table
Customer Information Table
2. Full Outer Join
Result Table of FULL OUTER JOIN
3. Full Outer Join with WHERE clause
FULL OUTER JOIN with WHERE clause Resultant Table
sagar0719kumar
kalrap615
DBMS-SQL
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Update Multiple Columns in Single Update Statement in SQL?
How to Alter Multiple Columns at Once in SQL Server?
What is Temporary Table in SQL?
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL using Python
SQL | Subquery
SQL Query to Convert VARCHAR to INT
SQL | Date functions
SQL - SELECT from Multiple Tables with MS SQL Server
SQL Query to Insert Multiple Rows | [
{
"code": null,
"e": 24294,
"s": 24266,
"text": "\n25 Aug, 2021"
},
{
"code": null,
"e": 24480,
"s": 24294,
"text": "A SQL join statement is used to combine rows or information from two or more than two tables on the basis of a common attribute or field. There are basically four types of JOINS in SQL."
},
{
"code": null,
"e": 24555,
"s": 24480,
"text": "In this article, we will discuss about FULL OUTER JOIN using WHERE clause."
},
{
"code": null,
"e": 24586,
"s": 24555,
"text": "Consider the two tables below:"
},
{
"code": null,
"e": 24610,
"s": 24586,
"text": "Sample Input Table 1 : "
},
{
"code": null,
"e": 24633,
"s": 24610,
"text": "Sample Input Table 2 :"
},
{
"code": null,
"e": 24861,
"s": 24633,
"text": "FULL OUTER JOIN : Full Join provides result with concatenation of LEFT JOIN and RIGHT JOIN. The result will contain all the rows from both Table 1 and Table 2. The rows having no matching in result table will have NULL values. "
},
{
"code": null,
"e": 25069,
"s": 24861,
"text": "SELECT * FROM Table1\nFULL OUTER JOIN Table2\nON Table1.column_match=Table2.column_match;\n\nTable1: First Table in Database.\nTable2: Second Table in Database.\ncolumn_match: The column common to both the tables."
},
{
"code": null,
"e": 25085,
"s": 25069,
"text": "Sample Output :"
},
{
"code": null,
"e": 25276,
"s": 25085,
"text": "FULL OUTER JOIN using WHERE CLAUSE : The use of WHERE clause with FULL OUTER JOIN helps to retrieve all those rows which have no entry matching on joining both the tables having NULL entry. "
},
{
"code": null,
"e": 25596,
"s": 25276,
"text": "SELECT * FROM Table1\nFULL OUTER JOIN Table2\nON Table1.column_match=Table2.column_match\nWHERE Table1.column is NULL\nOR Table2.column is NULL;\n\nTable1: First Table in Database.\nTable2: Second Table in Database.\ncolumn_match: The column common to both the tables.\ncolumn: The column having NULL value after Full Outer Join"
},
{
"code": null,
"e": 25791,
"s": 25596,
"text": "The above Query returns only those customer who bought mobile phones and don’t have any record saved in Customer Information Table as well as the customer information who didn’t buy any product."
},
{
"code": null,
"e": 26270,
"s": 25791,
"text": "SQL QUERY FOR THE SAMPLE INPUTS : We have considered a Customer and Purchase Information of Mobile Phones from an E-Commerce site during Big Billion Days. The Database E-Commerce has two tables one has information about the Product and the other one have information about the Customer. Now, we will perform FULL OUTER JOIN between these two tables to concatenate them into a single table and get complete data about the customers and the products they purchased from the site."
},
{
"code": null,
"e": 26288,
"s": 26270,
"text": "BASIC SQL QUERY :"
},
{
"code": null,
"e": 26311,
"s": 26288,
"text": "1. Creating a Database"
},
{
"code": null,
"e": 26342,
"s": 26311,
"text": "CREATE DATABASE database_name;"
},
{
"code": null,
"e": 26362,
"s": 26342,
"text": "2. Creating a Table"
},
{
"code": null,
"e": 26617,
"s": 26362,
"text": "CREATE TABLE Table_name(\ncol_1 TYPE col_1_constraint,\ncol_2 TYPE col_2 constraint\n.....\n)\n\ncol: Column name\nTYPE: Data type whether an integer, variable character, etc\ncol_constraint: Constraints in SQL like PRIMARY KEY, NOT NULL, UNIQUE, REFERENCES, etc"
},
{
"code": null,
"e": 26643,
"s": 26617,
"text": "3. Inserting into a Table"
},
{
"code": null,
"e": 26740,
"s": 26643,
"text": "INSERT INTO Table_name\nVALUES(val_1, val_2, val_3, ..........)\n\nval: Values in particular column"
},
{
"code": null,
"e": 26758,
"s": 26740,
"text": "4. View The Table"
},
{
"code": null,
"e": 26783,
"s": 26758,
"text": "SELECT * FROM Table_name"
},
{
"code": null,
"e": 26859,
"s": 26783,
"text": "For more information regarding SQL syntaxes visit our website SQL Tutorial."
},
{
"code": null,
"e": 26868,
"s": 26859,
"text": "Output :"
},
{
"code": null,
"e": 26923,
"s": 26868,
"text": "1. Customer Information and Purchase Information Table"
},
{
"code": null,
"e": 26950,
"s": 26923,
"text": "Purchase Information Table"
},
{
"code": null,
"e": 26977,
"s": 26950,
"text": "Customer Information Table"
},
{
"code": null,
"e": 26997,
"s": 26977,
"text": "2. Full Outer Join "
},
{
"code": null,
"e": 27029,
"s": 26997,
"text": "Result Table of FULL OUTER JOIN"
},
{
"code": null,
"e": 27066,
"s": 27029,
"text": "3. Full Outer Join with WHERE clause"
},
{
"code": null,
"e": 27117,
"s": 27066,
"text": "FULL OUTER JOIN with WHERE clause Resultant Table"
},
{
"code": null,
"e": 27132,
"s": 27117,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 27142,
"s": 27132,
"text": "kalrap615"
},
{
"code": null,
"e": 27151,
"s": 27142,
"text": "DBMS-SQL"
},
{
"code": null,
"e": 27155,
"s": 27151,
"text": "SQL"
},
{
"code": null,
"e": 27159,
"s": 27155,
"text": "SQL"
},
{
"code": null,
"e": 27257,
"s": 27159,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27266,
"s": 27257,
"text": "Comments"
},
{
"code": null,
"e": 27279,
"s": 27266,
"text": "Old Comments"
},
{
"code": null,
"e": 27345,
"s": 27279,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 27398,
"s": 27345,
"text": "How to Alter Multiple Columns at Once in SQL Server?"
},
{
"code": null,
"e": 27430,
"s": 27398,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 27508,
"s": 27430,
"text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter"
},
{
"code": null,
"e": 27525,
"s": 27508,
"text": "SQL using Python"
},
{
"code": null,
"e": 27540,
"s": 27525,
"text": "SQL | Subquery"
},
{
"code": null,
"e": 27576,
"s": 27540,
"text": "SQL Query to Convert VARCHAR to INT"
},
{
"code": null,
"e": 27597,
"s": 27576,
"text": "SQL | Date functions"
},
{
"code": null,
"e": 27650,
"s": 27597,
"text": "SQL - SELECT from Multiple Tables with MS SQL Server"
}
]
|
Full Pipeline Project: Python AI for detecting fake news | by Johnny Wales | Towards Data Science | Too many articles on machine learning focus only on modeling. Those crucial middle bits of model building and validation are surely deserving of attention, but I want more — and I hope you do, too. I’ve written this complete review of my own project, to include data wrangling, the aforementioned model work, and creation of a public interface. If you want to skip right to the “punchline,” the finished program can be found at https://www.unslanted.net/newsbot/.
I started with the idea that the wording of fake news is distinct from that of standard news, and that machine learning can detect this difference. In my own examination of fake news articles, I found relatively frequent use of terms seemingly intended to inspire outrage. I also found the writing skill evident in such articles was generally considerably lesser than that evident in standard news. With these things in mind, I had some basis to begin building my model to sort fake news from the rest.
To find out if this hypothesis is correct, we first need an objectively labeled data set that will give us examples of fake news and examples of real news as provided by professional fact checkers. The data needs to have URLs that point to news articles and a ruling on the truth or fiction of that article. I located 2 data sets that meet this criteria. The first is the interactive media bias chart from Ad Fontes Media. You can access their chart and get the first data set here: https://www.adfontesmedia.com/interactive-media-bias-chart/ The other data set we’ll be using is the FakeNewsNet data set available here: https://github.com/KaiDMML/FakeNewsNet. I did some manual changes to the data sets to eliminate PDFs and anything obviously not a URL, and standardized the scoring system by giving a ‘fake’ rating to all of the items from FakeNewsNet’s politifact_fake.csv, and a ‘real’ rating to all items from the politifact_real.csv file.
Once we have our data sets, our next task will be to combine those data sets into a single database table that we can then use to extract the text we’ll be working with. I use the Django ORM for managing a connection to my database. Later, this also makes it easier to provide a public interface to our models, because Django is a full featured MVC web framework. After starting our app via manage.py, I have to create the table via the Django.db models classes:
from django.db import modelsclass ArticleExample(models.Model): # This will hold the visible text for this example body_text = models.TextField() # This bias score is a left-right bias provided by Media Bias # Chart, but not used in this project. bias_score = models.FloatField() bias_class = models.IntegerField() # quality_score comes from the Media Bias Chart data quality_score = models.FloatField() # quality_class is based on the quality score and allows us to # integrate politifact data in their # 4-class way, True = 4, Mostly True = 3, Mostly Fake = 2, # Fake = 1 quality_class = models.IntegerField() origin_url = models.TextField() origin_source = models.TextField()
Easy, right? Next we go back to Django’s manage.py and run makemigrations and migrate to set up our database.
Now we have to get data into this table. This is a process of data wrangling, and is one of the most difficult and time consuming parts of machine learning. In large ML environments, there are data engineers who do little else than getting data sets together.
Let’s dig right into this problem. Essentially, we need to:
Load up our list of URLs and scores.Load the page from the URL and parse itStore the parsed version along with the scoreAdd a class for any data point that doesn’t have one by splitting up the data evenly.
Load up our list of URLs and scores.
Load the page from the URL and parse it
Store the parsed version along with the score
Add a class for any data point that doesn’t have one by splitting up the data evenly.
First lets look at everything except the part about parsing the page. For now, you just need to know that SoupStrainer (which we’ll develop in a minute) will handle all that for us.
The main part of this program is harvester.py. In the first section of harvester, we have to do some initial setup to allow our django program to run from the command line rather than via a web interface.
import os, sys, re, timeproj_path = “/home/jwales/eclipse-workspace/crowdnews/”os.environ.setdefault(“DJANGO_SETTINGS_MODULE”, “crowdnews.settings”)sys.path.append(proj_path)os.chdir(proj_path)from django.core.wsgi import get_wsgi_applicationapplication = get_wsgi_application()from django.contrib.gis.views import feed
Your mileage will vary a bit depending on the particulars of the project path on your machine. Next, we need to load and set up our models and SoupStrainer, our parser. We’ll explain what that means soon, just stick with me.
import pandas as pdfrom newsbot.strainer import *from newsbot.models import *ss = SoupStrainer()print(“Initializing dictionary...”)ss.init()
Next we have the following method for loading the data we got from Politifact:
def harvest_Politifact_data(): print(“Ready to harvest Politifact data.”) input(“[Enter to continue, Ctl+C to cancel]>>”) print(“Reading URLs file”) # Read the data file into a pandas dataframe df_csv = pd.read_csv(“newsbot/politifact_data.csv”, error_bad_lines=False, quotechar=’”’, thousands=’,’, low_memory=False) for index, row in df_csv.iterrows(): print(“Attempting URL: “ + row[‘news_url’]) if(ss.loadAddress(row[‘news_url’])): print(“Loaded OK”) # some of this data loads 404 pages b/c it is a little old, # some load login pages. I’ve found that # ignoring anything under 500 characters is a decent # strategy for weeding those out. if(len(ss.extractText)>500): ae = ArticleExample() ae.body_text = ss.extractText ae.origin_url = row[‘news_url’] ae.origin_source = ‘politifact data’ ae.bias_score = 0 # Politifact data doesn’t have this ae.bias_class = 5 # 5 is ‘no data’ ae.quality_score = row[‘score’] ae.quality_class = row[‘class’] ae.save() print(“Saved, napping for 1...”) time.sleep(1) else: print(“**** This URL produced insufficient data.”) else: print(“**** Error on that URL ^^^^^”)
Going through this, you’ll see we first used Pandas to read in the CSV file with our URLs and scores. Then we send it off to our parser and save the resulting text in body_text. Then we nap for 1 second to be kind to the websites we’re harvesting from. The process for the Media Bias Chart data is similar, we just have to split up the quality_class by each 1/4 of the quality score from media bias chart.
The real meat of the work isn’t here yet, though! How are we getting the data from these websites, what does it look like, and how are we parsing it?
For this task, we will need to limit the number of words we’re looking at. We want to be sure those words are real English words and we want to only save the word stem, so words like programmer, programming, and program can all be reduced to program. This will limit the size of our eventual training examples and make it manageable on an ordinary PC. This task will be in the class SoupStrainer we encountered in harvester, and I told you we’d explain in a minute. The big moment has arrived!
First is our set of imports. We’ll use BeautifulSoup for parsing the HTML, urllib3 for loading the web pages from the net, and PorterStemmer to do the word stemming. Plus we’ll need a couple of other things tossed in for wrangling this data:
import urllib3, re, string, json, htmlfrom bs4 import BeautifulSoupfrom bs4.element import Commentfrom urllib3.exceptions import HTTPErrorfrom io import StringIOfrom nltk.stem import PorterStemmer
Next we’ll set up our class and initialize our dictionary from a full dictionary you can get from: https://github.com/dwyl/english-words
class SoupStrainer(): englishDictionary = {} haveHeadline = False recHeadline = ‘’ locToGet = ‘’ pageData = None errMsg = None soup = None msgOutput = True def init(self): with open(‘newsbot/words_dictionary.json’) as json_file: self.englishDictionary = json.load(json_file)
We are only interested in visible text on the page, so the next step is to build a filter that is capable of detecting which tags are visible and which ones are not:
def tag_visible(self, element): if element.parent.name in [‘style’, ‘script’, ‘head’, ‘title’, ‘meta’, ‘[document]’]: return False if isinstance(element, Comment): return False return True
We will use this in our next function, which does the actual loading and parsing. Buckle in, this one is a fun ride.
First, we’ll set some things up and be sure it looks at least somewhat like a URL:
def loadAddress(self, address): self.locToGet = address self.haveHeadline = False htmatch = re.compile(‘.*http.*’) user_agent = {‘user-agent’: ‘Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/36.0’} ps = PorterStemmer() if(htmatch.match(self.locToGet) is None): self.locToGet = “http://” + self.locToGet
Next, let's see if we can get the URL to load:
if(len(self.locToGet) > 5): if(self.msgOutput): print(“Ready to load page data for: “ + self.locToGet + “which was derived from “ + address) try: urllib3.disable_warnings( urllib3.exceptions.InsecureRequestWarning) http = urllib3.PoolManager(2, headers=user_agent) r = http.request(‘GET’, self.locToGet) self.pageData = r.data if(self.msgOutput): print(“Page data loaded OK”) except: self.errMsg = ‘Error on HTTP request’ if(self.msgOutput): print(“Problem loading the page”) return False
So far so good, we’re just loading up the web page and grabbing the resulting HTML file. Next, we should extract the visible text, strip it of punctuation, ensure it is a real word, then stem it. I left in a commented line showing how you might want to review any words that aren’t in the dictionary.
self.extractText = ‘’ self.recHeadline = self.locToGet self.soup = BeautifulSoup(self.pageData, ‘html.parser’) ttexts = self.soup.findAll(text=True) viz_text = filter(self.tag_visible, ttexts) allVisText = u””.join(t.strip() for t in viz_text) for word in allVisText.split(): canonWord = word.lower() canonWord = canonWord.translate( str.maketrans(‘’, ‘’, string.punctuation)) canonWord = canonWord.strip(string.punctuation) if(canonWord in self.englishDictionary): canonWord = ps.stem(canonWord) self.extractText = self.extractText + canonWord + “ “ return True
Now when we run harvester.py, we will wind up with a full set of examples with stemmed real words, a URL, and a quality_class that tells us if it is fake or real.
We need to take a look at what model we’ll be building to understand this next part. The core of the plan is to create a matrix of examples where each row is 1 example. The row is made of a set of 1s and 0s indicating whether or not a word matching that index appears in the example. Therefore, the next step we need to go through is attaching a unique index for each word in all examples that we’ve just downloaded and put into our database. So we will need to build a dictionary. The first step there is to build the data models and tables needed for this task. Head back over to models.py, and add the following:
class DictEntry(models.Model): canonWord = models.TextField()
Go out to your terminal and do the makemigrations/migrate dance, and then we are ready to work on building out the dictionary. For that, we need to take a look at the script dictbuilder.py.
Once we have loaded the required django libraries, we build a python dictionary using any words currently in our canonical words dictionary table. This gives us a fast way to see if something is already in the dictionary without having to do a database lookup. If you do this by hitting the database for each individual word test, you will slow down by a factor of at least 10, so this part is definitely worth it. As it happens, we’ll be doing this repeatedly throughout the process, so here we will create a file util.py and create a function to return our dictionary of canonical words:
def loadCanonDict(): canonDict = DictEntry.objects.all() dictSize = canonDict.count() + 1 cDict = {} for cw in canonDict: cDict[cw.canonWord] = cw.pk return cDict
Finally we are ready to build out the dictionary table with all our words from all of our examples:
qs_Examples = ArticleExample.objects.all() #filter(pk__gt = 2942)print(“Examples: “ + str(qs_Examples.count()))for ex in qs_Examples: cwords = ex.body_text.split() for cwrd in cwords: if(cwrd in cDict.keys()): print(‘.’, end=’’, flush=True) else: print(‘X’, end=’’, flush=True) nde = DictEntry(canonWord = cwrd) nde.save() cDict[cwrd] = nde.pk
This will assign a primary key ID to each word, and those are going to be numbered sequentially. This way, when we are building an example, we can use the primary key as the column number to update for any particular example, and be sure the same column means the same thing for every example. Note that if you ever need to blow away the dictionary and rebuild, you’ll also need to go reset the primary key counter. I had to do that during development, maybe this article will save you that headache!
Stepping back, we now have a data set to work with and we have a way to indicate which words exist in any particular example. We have (in my dataset) 20,870 words and 2,500 unique examples with scores. Now we are ready to begin learning our models. If you’re the kind of nerd I am, you’re absolutely giddy at this point.
The problem we face is to classify the news into 1 of 4 possible classes, Fake, Dodgy, Seems Legit, and Real. This is a problem for a classifier model. The library of models we’re using is scikit-learn. We’ll test several models and see which works well. I think this type of problem would be great for a support vector machine or a neural network.
For each article, we now have a copy of the text as stripped-down and stemmed words. Each of those words has a unique ID. We will build each example as a numpy row vector, with each example[n] will be 1 if word ID n appears in the article, and 0 otherwise. Then we stack all those row vectors into a huge 20,870 x 2,500 matrix. Then we will store the quality class provided by our data set in a column vector, and use this matrix and column vector for training and testing our model.
We will need a way to process an article into a row for one example. This is a task we’ll need to repeat again if we test any new example, so again we’ll create a utility function for it:
def buildExampleRow(body_text, cDict): dictSize = len(cDict.keys()) one_ex_vector = np.zeros(dictSize+2) cwords = body_text.split() for word in cwords: if(word in cDict.keys()): one_ex_vector[cDict[word]-1] = 1 else: print("This word doesn't exist in the dict:" + word) return(one_ex_vector)
Next we build a function to load up our examples from the database.
def processExamples(qs_Examples, cDict): Y_vector = np.zeros(qs_Examples.count(), dtype=np.int8) Y_vec_count = 0 examplesMatrix = None for ex in qs_Examples: Y_vector[Y_vec_count] = int(ex.quality_class) Y_vec_count = Y_vec_count + 1 if(examplesMatrix is None): examplesMatrix = buildExampleRow(ex.body_text, cDict) else: examplesMatrix = np.vstack( [examplesMatrix, buildExampleRow(ex.body_text, cDict)]) print('.', end='', flush=True) return( (Y_vector, examplesMatrix))
Now we can set up for training quickly and easily in class_learner.py:
from newsbot.util import *print("Setting up..")cDict = loadCanonDict()qs_Examples = ArticleExample.objects.filter(quality_class__lt = 5)print("Processing examples")(Y_vector, examplesMatrix) = processExamples(qs_Examples, cDict)
It is now time to train and test models. We will break our data into a training and testing set, then we will train our multi-layer perceptron classifier. Easy peasy, as it turns out:
X_train, X_test, y_train, y_test = train_test_split(examplesMatrix, Y_vector, test_size=0.2)model = MLPClassifier(hidden_layer_sizes=(128,64,32,16,8), max_iter=2500)model.fit(X_train, y_train)
The great thing about using a powerful library like SciKit is that the basics of this process are the same for several different models. When you want to change models, you can change the line model=MLPClassifier(...) to another model and you will often get a working program.
Now we have a trained model, and we finally get around to finding out if it worked and if we can build something cool from it. To find out, we’ll need to do some tests and understand them. Thus begins the process of model validation. For a classification model, we can get a great idea of how we’re doing at classifying our news.
print(“***************”)print(“Classification based:”)print(accuracy_score(predictions, y_test))print(confusion_matrix(predictions, y_test))print(classification_report(predictions, y_test))print(“***************”)
Drumroll, please...
***************Accuracy score: 0.546Confusion Matrix: [[ 35 8 3 2] [ 10 44 28 5] [ 21 40 83 58] [ 3 4 45 111]]Classification report: precision recall f1-score support1 0.51 0.73 0.60 48 2 0.46 0.51 0.48 87 3 0.52 0.41 0.46 202 4 0.63 0.68 0.65 163accuracy 0.55 500 macro avg 0.53 0.58 0.55 500weighted avg 0.54 0.55 0.54 500***************
Interpreting these numbers, we get:
Accuracy Score, 0.546: This means 54.6% of our predictions were accurate. Since we have 4 classes, a random guess would have produced an accuracy of 25%, so this is actually an improvement.
Confusion matrix: This set of 16 numbers gives us some very interesting information. I have plotted it below in a more readable format. The rows are each for a class predicted class, and each column has the true class. The number at the intersection of the row and column is the number of the real class predicted as each predicted class. So, for instance, the number 44 that you see on the second row, second column is the number of examples where the true class was 2, and the predicted value was also 2. The 28 you see in the next column of the same row is the number of examples that were actually a 2 but our model predicted a 3. Notice that among articles that are actually a 1, there is strong weighting toward the 1/2 end of the scale. Similarly, on the bottom row we have examples that are actually graded a 4, and notice that the last 2 columns are overwhelmingly bigger than the first two. This is good news!
Classification Report:
Here, each row represents a class, and shows precision, recall, and F1 score. The numbers you see here vary from great to not so great. Generally speaking, it looks like we’re better at locating true news than fake, but if we can do that, we may still get close enough to work with. If you continue down, you’ll see we also get an overall weighted average precision/recall/F1 score that give us a clearer idea of how the model performs overall. Our 0.54 F1 score gives us a balance between our precision and recall scores, and is a good single metric for evaluating classification models. If we get a substantially higher F1 on another model, we should choose it over this one. Accuracy score is also a good single metric, and in practice the two are usually very close.
Earlier, I noted in the confusion matrix that it seems like the classifier is often off by 1. If I also look at the mean absolute error of my model:
mae = mean_absolute_error(y_test, predictions)print(“Mean absolute Error: “ + str(mae))
I will get:
Mean absolute Error: 0.54
Which is further evidence that, on average, the model is within 1 class of the actual answer. This will inform our further development of our models and our end delivery. If we are going to deliver this model to the end user to give them a clear picture of what our model is thinking, we will need to produce probability estimates. Most models can handle that automatically, the support vector classifier requires the “probability=True” flag to produce a probability estimator when training.
Now that you know how to read a confusion matrix and a classification report, and we’ve picked out our single metric for model evaluation, we can now test out a whole bunch of different models. In the code available in the repository, I’ve just commented out calls for all the various models shown here so you can see that scikit allows you to switch learning models by simply changing the model declaration, and everything else remains the same.
3 hours later
After a lot of training and cataloging of results, here is the outcome of our tests of various different models for this problem:
Well, I’m pretty surprised that logistic regression took the 2nd spot. Not so surprised about K-Neighbors and Decision Tree, they didn’t seem like a good fit for this problem. SVC was the clear winner.
Thinking about our interface
Now we have a clear picture of how well or poorly our models perform. Next we need to see how they perform on live examples. We know that the models tend to be close to correct even if they aren’t correct. We next need to know more about whether or not they provide conflicting answers or if they are giving us consistent answers. We’ll have to save our top 3 models and build something to test them.
Saving our models
For this part of the task, I created a new file called class_saver.py. This way, I can load the data 1 time, run and test all three top models, and save them using pickle. We’ll set up our environment and then put our top three models into an iterable python dictionary:
print("Setting up..")cDict = loadCanonDict()qs_Examples = ArticleExample.objects.filter(quality_class__lt = 5)print("Processing examples")(Y_vector, examplesMatrix) = processExamples(qs_Examples, cDict)X_train, X_test, y_train, y_test = train_test_split(examplesMatrix, Y_vector, test_size=0.2)chosen_models = {}chosen_models['newsbot/MLPC_model.sav'] = MLPClassifier(hidden_layer_sizes=(128,64,32,16,8), max_iter=2500)chosen_models['newsbot/svc_model.sav'] = SVC(gamma='scale', probability = True)chosen_models['newsbot/log_model.sav'] = LogisticRegression()
Next we will cycle through the chosen models, train them, and decide if we want to keep them. Note that these models have random initializations and running them more than once will produce slightly different results, so you need to take a peek at their statistics to be sure you’ve got a good one.
for fname, model in chosen_models.items(): print("Working on " + fname) model.fit(X_train, y_train) predictions = model.predict(X_test) print("Classification report: ") print(classification_report(predictions, y_test)) print("***************") dosave = input("Save " + fname + "? ") if(dosave == 'y' or dosave == 'Y'): print("Saving...") pickle.dump(model, open(fname, 'wb')) print("Saved!") else: print("Not saved!")
After training your models and saving them, you’ll wind up with 3 files. My 3 files were very large, total of about 391MB together.
Now, let’s build a command-line interface that will give us our estimates on live examples. Here we can re-use a lot of code. If you’re following along in the repository, we’re now going to work with classify_news.py.
After we do our usual setup of adding in the required imports and setting up Django for our ORM access, we next need to load up our 3 models designed before.
print(“Loading brain...”)log_model = pickle.load(open(‘newsbot/log_model.sav’, ‘rb’))svc_model = pickle.load(open(‘newsbot/svc_model.sav’, ‘rb’))mlp_model = pickle.load(open(‘newsbot/mlp_model.sav’, ‘rb’))print(“Brain load successful.”)
Next we need to initialize everything for turning an article into an example, as we did before:
print("Initializing dictionaries...")cDict = loadCanonDict()ss = SoupStrainer()ss.init()
Then we turn our article into an input row for our models:
url = input("URL to analyze: ")print("Attempting URL: " + url)if(ss.loadAddress(url)): articleX = buildExampleRow(ss.extractText, cDict)else: print("Error on URL, exiting") exit(0)articleX = articleX.reshape(1, -1)
And finally, when we have a proper row vector set up, we can predict and generate probabilities for each of our models:
log_prediction = log_model.predict(articleX)log_probabilities = log_model.predict_proba(articleX)svc_prediction = svc_model.predict(articleX)svc_probabilities = svc_model.predict_proba(articleX)mlp_prediction = mlp_model.predict(articleX)mlp_probabilities = mlp_model.predict_proba(articleX)# 6. Display the processed text and the resultsprint(“*** SVC “)print(“Prediction on this article is: “)print(svc_prediction)print(“Probabilities:”)print(svc_probabilities)print(“*** Logistic “)print(“Prediction on this article is: “)print(log_prediction)print(“Probabilities:”)print(log_probabilities)print(“*** MLP “)print(“Prediction on this article is: “)print(mlp_prediction)print(“Probabilities:”)print(mlp_probabilities)
Now I run the classifier. It takes about 1 to 2 seconds load time to unpickle my models and load up dictionaries, which is a little long but still acceptable. If we are rolling this out at scale, we need to find a way to load the models and dictionaries in memory and have them persist there until removed. For our development version, this will still work. If I paste in an article URL I think is real, I get the following output:
*** SVC Prediction on this article is: [3]Probabilities:[[0.01111608 0.0503078 0.70502378 0.23355233]]*** Logistic Prediction on this article is: [3]Probabilities:[[5.61033543e-04 5.89780773e-03 7.63196217e-01 2.30344942e-01]]*** MLP Prediction on this article is: [4]Probabilities:[[1.18020372e-04 1.93965844e-09 4.88694225e-01 5.11187753e-01]]
These probabilities are showing me the probabilities associated with each of my 4 classes, with the first one being a ruling of fully fake, and the last being a ruling of fully real. In the support vector classifier, the odds of real or mostly real is 70.5+ 23.4 = 93.9%! Similar numbers are achieved with the other two. All of my classifiers agree, this article looks very real. It was the top article on Washington Post at the time of this writing. Next, I go to a very dodgy news source that is a known purveyor of fake and dodgy news stories and pick a story from their front page at random. Here is that output:
*** SVC Prediction on this article is: [1]Probabilities:[[0.80220529 0.18501285 0.01051862 0.00226324]]*** Logistic Prediction on this article is: [1]Probabilities:[[0.53989611 0.45269964 0.0005857 0.00681855]]*** MLP Prediction on this article is: [1]Probabilities:[[8.38376936e-01 1.84104358e-03 1.59391877e-01 3.90143317e-04]]
Eureka! All three classifiers agree, this article is fake. The probabilities are interesting here. the SVC and Logistic models are very sure on this being on the fake/dodgy end of things. Notice that the MLP gives a 15.9% chance of the article being mostly true.
Finally, I will test an article sent to me by one of my readers who I invited to be a beta tester. He found that it was producing inconsistent results in an earlier version of this project, specifically that the first version of my SVC and MLP models were disagreeing. In this version, it also comes up very controversial:
*** SVC Prediction on this article is: [3]Probabilities:[[0.28233338 0.38757642 0.26880828 0.06128192]]*** Logistic Prediction on this article is: [3]Probabilities:[[3.93710544e-01 1.68049849e-01 4.38124141e-01 1.15466230e-04]]*** MLP Prediction on this article is: [3]Probabilities:[[3.67580348e-03 1.66093528e-05 9.96254861e-01 5.27264258e-05]]
Notice that the SVC has almost no idea what to make of this, giving it a pretty equal rating in classes 1, 2, and 3, and then it chose to predict class 3 even though class 2 has the highest probability. The same basic outcome is seen in the logistic model: Somewhat similar probabilities for 1 and 3, plus a 16.8% chance of 2, and it ultimately predicted a 3. The MLP model is sure this article is a 3. Intriguingly, this article is about the economy, but it is from a dodgy source and uses a lot of very loaded language similar to fake news. I think the classifiers have a hard time because it is about a topic outside the training domain. The articles used in training were generally about US politics rather than about the economy, so that may be why we’re seeing this outcome.
Building the web interface
Whew. It has been a long journey, folks. Now we have our 3 models that seem to work pretty well, and we want to deploy them so the public can use them. We know that in many cases where an article should be in class 4, our models usually put most of their weight into class 3 and 4, and that they work similarly on the other end of the scale. We know they sometimes disagree, especially on the finer point of the specific probabilities involved. And we know that the typical user isn’t going to install python and a huge batch of libraries to use this tool. We have to make it easy to use, easy to understand, and available to everyone.
Great news, we originally put this puppy together in the Django MVC framework, so from here it is a relatively simple process to build out a web interface.
First, we update the views.py provided by django when we used startapp to start up this whole process.
In this part, we see some familiar code we’ve worked with before in our command-line interface to set up the models, parse an example, and return our row vector representing the word content of the submitted article:
from django.shortcuts import renderimport pandas as pdimport numpy as npimport picklefrom .models import *from .forms import *from newsbot.strainer import *from newsbot.util import *def index(request): url = request.GET.get('u') if((url is not None) and (len(url) > 5)): print("Setting up") svc_model = pickle.load(open('newsbot/svc_model.sav', 'rb')) mlp_model = pickle.load(open('newsbot/MLPC_model.sav', 'rb')) log_model = pickle.load(open('newsbot/log_model.sav', 'rb')) cDict = loadCanonDict() ss = SoupStrainer() ss.init() print("Setup complete") print("Attempting URL: " + url) if(ss.loadAddress(url)): articleX = buildExampleRow(ss.extractText, cDict) else: print("Error on URL, exiting") return render(request, 'urlFail.html', {'URL', url}) articleX = articleX.reshape(1, -1)
Shazam, we’ve got articleX as our article in a numpy array of 1s and 0s that represents the canonical words that appear in the article.
Now we need to get a result from all our models:
svc_prediction = svc_model.predict(articleX) svc_probabilities = svc_model.predict_proba(articleX) mlp_prediction = mlp_model.predict(articleX) mlp_probabilities = mlp_model.predict_proba(articleX) log_prediction = log_model.predict(articleX) log_probabilities = log_model.predict_proba(articleX)
Next I need to set up some display variables we might want for our template. We want as little math and logic as we can in the template, so we’re setting up the probabilities in display-friending percentage points instead of the statistician’s familiar 0-to-1 float form. We create a total fake and total real metric for each of the models like this:
Total Fake = Fake (class 0) probability + Dodgy (class 1) probability
Total Real = Seems Legit (class 3) probability + True (class 3) probability
This gives us just 1 comparison to do in our template to decide if we want to display “Seems Real” or “Seems Fake” as our ruling.
svc_prb = (svc_probabilities[0][0]*100, svc_probabilities[0][1]*100, svc_probabilities[0][2]*100, svc_probabilities[0][3]*100) svc_totFake = (svc_probabilities[0][0]*100) + (svc_probabilities[0][1]*100) svc_totReal = (svc_probabilities[0][2]*100) + (svc_probabilities[0][3]*100) mlp_prb = (mlp_probabilities[0][0]*100, mlp_probabilities[0][1]*100, mlp_probabilities[0][2]*100, mlp_probabilities[0][3]*100) mlp_totFake = (mlp_probabilities[0][0]*100) + (mlp_probabilities[0][1]*100) mlp_totReal = (mlp_probabilities[0][2]*100) + (mlp_probabilities[0][3]*100) log_prb = (log_probabilities[0][0]*100, log_probabilities[0][1]*100, log_probabilities[0][2]*100, log_probabilities[0][3]*100) log_totFake = (log_probabilities[0][0]*100) + (log_probabilities[0][1]*100) log_totReal = (log_probabilities[0][2]*100) + (log_probabilities[0][3]*100)
Then we want to combine these three models. This will handle the cases of controversial rulings. If 2 of our 3 models are strongly leaning one way, and the other is leaning strongly the other, then averaging them together will settle the dispute. That gives us a probability distribution that we can use as the top-of-page, single prediction that our end user wants: Is it real or fake?
fin_prb = ( (((svc_probabilities[0][0]*100)+(mlp_probabilities[0][0]*100)+(log_probabilities[0][0]*100))/3), (((svc_probabilities[0][1]*100)+(mlp_probabilities[0][1]*100)+(log_probabilities[0][1]*100))/3), (((svc_probabilities[0][2]*100)+(mlp_probabilities[0][2]*100)+(log_probabilities[0][2]*100))/3), (((svc_probabilities[0][3]*100)+(mlp_probabilities[0][3]*100)+(log_probabilities[0][3]*100))/3) ) fin_totFake = (svc_totFake + mlp_totFake + log_totFake)/3 fin_totReal = (svc_totReal + mlp_totReal + log_totReal)/3
Then we dump all that into a context and send that puppy off to our template:
context = {‘headline’:ss.recHeadline, ‘words’: ss.extractText, ‘url’ : url, ‘svc_totFake’: svc_totFake, ‘svc_totReal’: svc_totReal, ‘svc_prediction’: svc_prediction, ‘svc_probabilities’: svc_prb, ‘mlp_totFake’: mlp_totFake, ‘mlp_totReal’: mlp_totReal, ‘mlp_prediction’: mlp_prediction, ‘mlp_probabilities’: mlp_prb, ‘log_totFake’: log_totFake, ‘log_totReal’: log_totReal, ‘log_prediction’: log_prediction, ‘log_probabilities’: log_prb, ‘fin_totFake’: fin_totFake, ‘fin_totReal’: fin_totReal, ‘fin_probabilities’: fin_prb } return render(request, ‘newsbot/results.html’, context)
And you’ll need to add this bit at the end to render the form asking the user to enter a URL if one isn’t provided:
else: return render(request, ‘newsbot/urlForm.html’)
Within the results.html, we just have to create a quick table with each outcome. Here’s the one for the final ruling table:
<h3 style=”text-align: center;”> Combined Result:<br> {% if fin_totFake >= fin_totReal %} Fake/Dodgy {% else %} Seems Legit/True {% endif %} </h3> <br>Probability of Fake: {{ fin_probabilities.0|floatformat }}% chance of Fake<div class=”progress”> <div class=”progress-bar” id=”fakeProb_bar” role=”progressbar” aria-valuenow=”{{ fin_probabilities.0 }}” aria-valuemin=”0" aria-valuemax=”100" style=”width:{{ fin_probabilities.0 }}%”></div></div> <br>Probability of Dodgy: {{ fin_probabilities.1|floatformat }}% chance of Dodgy<div class=”progress”> <div class=”progress-bar” id=”MfakeProb_bar” role=”progressbar” aria-valuenow=”{{ fin_probabilities.1 }}” aria-valuemin=”0" aria-valuemax=”100" style=”width:{{ fin_probabilities.1 }}%”></div></div> <br>Probability of Mostly True: {{ fin_probabilities.2|floatformat }}% chance of Mostly True<div class=”progress”> <div class=”progress-bar” id=”MtrueProb_bar” role=”progressbar” aria-valuenow=”{{ fin_probabilities.2 }}” aria-valuemin=”0" aria-valuemax=”100" style=”width:{{ fin_probabilities.2 }}%”></div></div> <br>Probability of True: {{ fin_probabilities.3|floatformat }}% chance of True<div class=”progress”> <div class=”progress-bar” id=”trueProb_bar” role=”progressbar” aria-valuenow=”{{ fin_probabilities.3 }}” aria-valuemin=”0" aria-valuemax=”100" style=”width:{{ fin_probabilities.3 }}%”></div></div>
Repeat for any other models you want to display.
—
Recap
If you’ve made it this far, we’ve been on quite a journey. We started out with a hypothesis that seemed like something a machine couldn’t figure out. We found data to train our machine, coaxed that data into a form our machine could handle, and trained the machine. And then we tested it against live data and, much to the amazement of everyone, found that it actually has a sensible answer. Finishing a long project like this gives you a complete picture of the entire machine learning pipeline. This project, long as it was, still has a lot of room for improvements. More ideas include:
Ask the user if they think the bot was right or wrong, and record their answers for possible future training.
Find more data sets or get more data sets from more sources.
Write a crawler to dig through fake news sites gathering more and more examples.
Tune hyperparameters.
Expand domain knowledge to other countries or other subjects.
Use the domain name or headline as a data feature.
Find a way to count the number of advertisements on the page, on the hypothesis that fake news sites usually have more ads.
Now that you’ve seen the kind of things a classifier can potentially do, especially with a little help interpreting results, the sky is the limit. Thanks for coming, I hope I helped inspire and educate! | [
{
"code": null,
"e": 635,
"s": 171,
"text": "Too many articles on machine learning focus only on modeling. Those crucial middle bits of model building and validation are surely deserving of attention, but I want more — and I hope you do, too. I’ve written this complete review of my own project, to include data wrangling, the aforementioned model work, and creation of a public interface. If you want to skip right to the “punchline,” the finished program can be found at https://www.unslanted.net/newsbot/."
},
{
"code": null,
"e": 1138,
"s": 635,
"text": "I started with the idea that the wording of fake news is distinct from that of standard news, and that machine learning can detect this difference. In my own examination of fake news articles, I found relatively frequent use of terms seemingly intended to inspire outrage. I also found the writing skill evident in such articles was generally considerably lesser than that evident in standard news. With these things in mind, I had some basis to begin building my model to sort fake news from the rest."
},
{
"code": null,
"e": 2084,
"s": 1138,
"text": "To find out if this hypothesis is correct, we first need an objectively labeled data set that will give us examples of fake news and examples of real news as provided by professional fact checkers. The data needs to have URLs that point to news articles and a ruling on the truth or fiction of that article. I located 2 data sets that meet this criteria. The first is the interactive media bias chart from Ad Fontes Media. You can access their chart and get the first data set here: https://www.adfontesmedia.com/interactive-media-bias-chart/ The other data set we’ll be using is the FakeNewsNet data set available here: https://github.com/KaiDMML/FakeNewsNet. I did some manual changes to the data sets to eliminate PDFs and anything obviously not a URL, and standardized the scoring system by giving a ‘fake’ rating to all of the items from FakeNewsNet’s politifact_fake.csv, and a ‘real’ rating to all items from the politifact_real.csv file."
},
{
"code": null,
"e": 2547,
"s": 2084,
"text": "Once we have our data sets, our next task will be to combine those data sets into a single database table that we can then use to extract the text we’ll be working with. I use the Django ORM for managing a connection to my database. Later, this also makes it easier to provide a public interface to our models, because Django is a full featured MVC web framework. After starting our app via manage.py, I have to create the table via the Django.db models classes:"
},
{
"code": null,
"e": 3258,
"s": 2547,
"text": "from django.db import modelsclass ArticleExample(models.Model): # This will hold the visible text for this example body_text = models.TextField() # This bias score is a left-right bias provided by Media Bias # Chart, but not used in this project. bias_score = models.FloatField() bias_class = models.IntegerField() # quality_score comes from the Media Bias Chart data quality_score = models.FloatField() # quality_class is based on the quality score and allows us to # integrate politifact data in their # 4-class way, True = 4, Mostly True = 3, Mostly Fake = 2, # Fake = 1 quality_class = models.IntegerField() origin_url = models.TextField() origin_source = models.TextField()"
},
{
"code": null,
"e": 3368,
"s": 3258,
"text": "Easy, right? Next we go back to Django’s manage.py and run makemigrations and migrate to set up our database."
},
{
"code": null,
"e": 3628,
"s": 3368,
"text": "Now we have to get data into this table. This is a process of data wrangling, and is one of the most difficult and time consuming parts of machine learning. In large ML environments, there are data engineers who do little else than getting data sets together."
},
{
"code": null,
"e": 3688,
"s": 3628,
"text": "Let’s dig right into this problem. Essentially, we need to:"
},
{
"code": null,
"e": 3894,
"s": 3688,
"text": "Load up our list of URLs and scores.Load the page from the URL and parse itStore the parsed version along with the scoreAdd a class for any data point that doesn’t have one by splitting up the data evenly."
},
{
"code": null,
"e": 3931,
"s": 3894,
"text": "Load up our list of URLs and scores."
},
{
"code": null,
"e": 3971,
"s": 3931,
"text": "Load the page from the URL and parse it"
},
{
"code": null,
"e": 4017,
"s": 3971,
"text": "Store the parsed version along with the score"
},
{
"code": null,
"e": 4103,
"s": 4017,
"text": "Add a class for any data point that doesn’t have one by splitting up the data evenly."
},
{
"code": null,
"e": 4285,
"s": 4103,
"text": "First lets look at everything except the part about parsing the page. For now, you just need to know that SoupStrainer (which we’ll develop in a minute) will handle all that for us."
},
{
"code": null,
"e": 4490,
"s": 4285,
"text": "The main part of this program is harvester.py. In the first section of harvester, we have to do some initial setup to allow our django program to run from the command line rather than via a web interface."
},
{
"code": null,
"e": 4810,
"s": 4490,
"text": "import os, sys, re, timeproj_path = “/home/jwales/eclipse-workspace/crowdnews/”os.environ.setdefault(“DJANGO_SETTINGS_MODULE”, “crowdnews.settings”)sys.path.append(proj_path)os.chdir(proj_path)from django.core.wsgi import get_wsgi_applicationapplication = get_wsgi_application()from django.contrib.gis.views import feed"
},
{
"code": null,
"e": 5035,
"s": 4810,
"text": "Your mileage will vary a bit depending on the particulars of the project path on your machine. Next, we need to load and set up our models and SoupStrainer, our parser. We’ll explain what that means soon, just stick with me."
},
{
"code": null,
"e": 5176,
"s": 5035,
"text": "import pandas as pdfrom newsbot.strainer import *from newsbot.models import *ss = SoupStrainer()print(“Initializing dictionary...”)ss.init()"
},
{
"code": null,
"e": 5255,
"s": 5176,
"text": "Next we have the following method for loading the data we got from Politifact:"
},
{
"code": null,
"e": 6563,
"s": 5255,
"text": "def harvest_Politifact_data(): print(“Ready to harvest Politifact data.”) input(“[Enter to continue, Ctl+C to cancel]>>”) print(“Reading URLs file”) # Read the data file into a pandas dataframe df_csv = pd.read_csv(“newsbot/politifact_data.csv”, error_bad_lines=False, quotechar=’”’, thousands=’,’, low_memory=False) for index, row in df_csv.iterrows(): print(“Attempting URL: “ + row[‘news_url’]) if(ss.loadAddress(row[‘news_url’])): print(“Loaded OK”) # some of this data loads 404 pages b/c it is a little old, # some load login pages. I’ve found that # ignoring anything under 500 characters is a decent # strategy for weeding those out. if(len(ss.extractText)>500): ae = ArticleExample() ae.body_text = ss.extractText ae.origin_url = row[‘news_url’] ae.origin_source = ‘politifact data’ ae.bias_score = 0 # Politifact data doesn’t have this ae.bias_class = 5 # 5 is ‘no data’ ae.quality_score = row[‘score’] ae.quality_class = row[‘class’] ae.save() print(“Saved, napping for 1...”) time.sleep(1) else: print(“**** This URL produced insufficient data.”) else: print(“**** Error on that URL ^^^^^”)"
},
{
"code": null,
"e": 6969,
"s": 6563,
"text": "Going through this, you’ll see we first used Pandas to read in the CSV file with our URLs and scores. Then we send it off to our parser and save the resulting text in body_text. Then we nap for 1 second to be kind to the websites we’re harvesting from. The process for the Media Bias Chart data is similar, we just have to split up the quality_class by each 1/4 of the quality score from media bias chart."
},
{
"code": null,
"e": 7119,
"s": 6969,
"text": "The real meat of the work isn’t here yet, though! How are we getting the data from these websites, what does it look like, and how are we parsing it?"
},
{
"code": null,
"e": 7613,
"s": 7119,
"text": "For this task, we will need to limit the number of words we’re looking at. We want to be sure those words are real English words and we want to only save the word stem, so words like programmer, programming, and program can all be reduced to program. This will limit the size of our eventual training examples and make it manageable on an ordinary PC. This task will be in the class SoupStrainer we encountered in harvester, and I told you we’d explain in a minute. The big moment has arrived!"
},
{
"code": null,
"e": 7855,
"s": 7613,
"text": "First is our set of imports. We’ll use BeautifulSoup for parsing the HTML, urllib3 for loading the web pages from the net, and PorterStemmer to do the word stemming. Plus we’ll need a couple of other things tossed in for wrangling this data:"
},
{
"code": null,
"e": 8052,
"s": 7855,
"text": "import urllib3, re, string, json, htmlfrom bs4 import BeautifulSoupfrom bs4.element import Commentfrom urllib3.exceptions import HTTPErrorfrom io import StringIOfrom nltk.stem import PorterStemmer"
},
{
"code": null,
"e": 8189,
"s": 8052,
"text": "Next we’ll set up our class and initialize our dictionary from a full dictionary you can get from: https://github.com/dwyl/english-words"
},
{
"code": null,
"e": 8495,
"s": 8189,
"text": "class SoupStrainer(): englishDictionary = {} haveHeadline = False recHeadline = ‘’ locToGet = ‘’ pageData = None errMsg = None soup = None msgOutput = True def init(self): with open(‘newsbot/words_dictionary.json’) as json_file: self.englishDictionary = json.load(json_file)"
},
{
"code": null,
"e": 8661,
"s": 8495,
"text": "We are only interested in visible text on the page, so the next step is to build a filter that is capable of detecting which tags are visible and which ones are not:"
},
{
"code": null,
"e": 8876,
"s": 8661,
"text": "def tag_visible(self, element): if element.parent.name in [‘style’, ‘script’, ‘head’, ‘title’, ‘meta’, ‘[document]’]: return False if isinstance(element, Comment): return False return True"
},
{
"code": null,
"e": 8993,
"s": 8876,
"text": "We will use this in our next function, which does the actual loading and parsing. Buckle in, this one is a fun ride."
},
{
"code": null,
"e": 9076,
"s": 8993,
"text": "First, we’ll set some things up and be sure it looks at least somewhat like a URL:"
},
{
"code": null,
"e": 9427,
"s": 9076,
"text": "def loadAddress(self, address): self.locToGet = address self.haveHeadline = False htmatch = re.compile(‘.*http.*’) user_agent = {‘user-agent’: ‘Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/36.0’} ps = PorterStemmer() if(htmatch.match(self.locToGet) is None): self.locToGet = “http://” + self.locToGet"
},
{
"code": null,
"e": 9474,
"s": 9427,
"text": "Next, let's see if we can get the URL to load:"
},
{
"code": null,
"e": 10053,
"s": 9474,
"text": "if(len(self.locToGet) > 5): if(self.msgOutput): print(“Ready to load page data for: “ + self.locToGet + “which was derived from “ + address) try: urllib3.disable_warnings( urllib3.exceptions.InsecureRequestWarning) http = urllib3.PoolManager(2, headers=user_agent) r = http.request(‘GET’, self.locToGet) self.pageData = r.data if(self.msgOutput): print(“Page data loaded OK”) except: self.errMsg = ‘Error on HTTP request’ if(self.msgOutput): print(“Problem loading the page”) return False"
},
{
"code": null,
"e": 10354,
"s": 10053,
"text": "So far so good, we’re just loading up the web page and grabbing the resulting HTML file. Next, we should extract the visible text, strip it of punctuation, ensure it is a real word, then stem it. I left in a commented line showing how you might want to review any words that aren’t in the dictionary."
},
{
"code": null,
"e": 10951,
"s": 10354,
"text": " self.extractText = ‘’ self.recHeadline = self.locToGet self.soup = BeautifulSoup(self.pageData, ‘html.parser’) ttexts = self.soup.findAll(text=True) viz_text = filter(self.tag_visible, ttexts) allVisText = u””.join(t.strip() for t in viz_text) for word in allVisText.split(): canonWord = word.lower() canonWord = canonWord.translate( str.maketrans(‘’, ‘’, string.punctuation)) canonWord = canonWord.strip(string.punctuation) if(canonWord in self.englishDictionary): canonWord = ps.stem(canonWord) self.extractText = self.extractText + canonWord + “ “ return True"
},
{
"code": null,
"e": 11114,
"s": 10951,
"text": "Now when we run harvester.py, we will wind up with a full set of examples with stemmed real words, a URL, and a quality_class that tells us if it is fake or real."
},
{
"code": null,
"e": 11730,
"s": 11114,
"text": "We need to take a look at what model we’ll be building to understand this next part. The core of the plan is to create a matrix of examples where each row is 1 example. The row is made of a set of 1s and 0s indicating whether or not a word matching that index appears in the example. Therefore, the next step we need to go through is attaching a unique index for each word in all examples that we’ve just downloaded and put into our database. So we will need to build a dictionary. The first step there is to build the data models and tables needed for this task. Head back over to models.py, and add the following:"
},
{
"code": null,
"e": 11792,
"s": 11730,
"text": "class DictEntry(models.Model): canonWord = models.TextField()"
},
{
"code": null,
"e": 11982,
"s": 11792,
"text": "Go out to your terminal and do the makemigrations/migrate dance, and then we are ready to work on building out the dictionary. For that, we need to take a look at the script dictbuilder.py."
},
{
"code": null,
"e": 12572,
"s": 11982,
"text": "Once we have loaded the required django libraries, we build a python dictionary using any words currently in our canonical words dictionary table. This gives us a fast way to see if something is already in the dictionary without having to do a database lookup. If you do this by hitting the database for each individual word test, you will slow down by a factor of at least 10, so this part is definitely worth it. As it happens, we’ll be doing this repeatedly throughout the process, so here we will create a file util.py and create a function to return our dictionary of canonical words:"
},
{
"code": null,
"e": 12761,
"s": 12572,
"text": "def loadCanonDict(): canonDict = DictEntry.objects.all() dictSize = canonDict.count() + 1 cDict = {} for cw in canonDict: cDict[cw.canonWord] = cw.pk return cDict"
},
{
"code": null,
"e": 12861,
"s": 12761,
"text": "Finally we are ready to build out the dictionary table with all our words from all of our examples:"
},
{
"code": null,
"e": 13259,
"s": 12861,
"text": "qs_Examples = ArticleExample.objects.all() #filter(pk__gt = 2942)print(“Examples: “ + str(qs_Examples.count()))for ex in qs_Examples: cwords = ex.body_text.split() for cwrd in cwords: if(cwrd in cDict.keys()): print(‘.’, end=’’, flush=True) else: print(‘X’, end=’’, flush=True) nde = DictEntry(canonWord = cwrd) nde.save() cDict[cwrd] = nde.pk"
},
{
"code": null,
"e": 13760,
"s": 13259,
"text": "This will assign a primary key ID to each word, and those are going to be numbered sequentially. This way, when we are building an example, we can use the primary key as the column number to update for any particular example, and be sure the same column means the same thing for every example. Note that if you ever need to blow away the dictionary and rebuild, you’ll also need to go reset the primary key counter. I had to do that during development, maybe this article will save you that headache!"
},
{
"code": null,
"e": 14081,
"s": 13760,
"text": "Stepping back, we now have a data set to work with and we have a way to indicate which words exist in any particular example. We have (in my dataset) 20,870 words and 2,500 unique examples with scores. Now we are ready to begin learning our models. If you’re the kind of nerd I am, you’re absolutely giddy at this point."
},
{
"code": null,
"e": 14430,
"s": 14081,
"text": "The problem we face is to classify the news into 1 of 4 possible classes, Fake, Dodgy, Seems Legit, and Real. This is a problem for a classifier model. The library of models we’re using is scikit-learn. We’ll test several models and see which works well. I think this type of problem would be great for a support vector machine or a neural network."
},
{
"code": null,
"e": 14914,
"s": 14430,
"text": "For each article, we now have a copy of the text as stripped-down and stemmed words. Each of those words has a unique ID. We will build each example as a numpy row vector, with each example[n] will be 1 if word ID n appears in the article, and 0 otherwise. Then we stack all those row vectors into a huge 20,870 x 2,500 matrix. Then we will store the quality class provided by our data set in a column vector, and use this matrix and column vector for training and testing our model."
},
{
"code": null,
"e": 15102,
"s": 14914,
"text": "We will need a way to process an article into a row for one example. This is a task we’ll need to repeat again if we test any new example, so again we’ll create a utility function for it:"
},
{
"code": null,
"e": 15445,
"s": 15102,
"text": "def buildExampleRow(body_text, cDict): dictSize = len(cDict.keys()) one_ex_vector = np.zeros(dictSize+2) cwords = body_text.split() for word in cwords: if(word in cDict.keys()): one_ex_vector[cDict[word]-1] = 1 else: print(\"This word doesn't exist in the dict:\" + word) return(one_ex_vector)"
},
{
"code": null,
"e": 15513,
"s": 15445,
"text": "Next we build a function to load up our examples from the database."
},
{
"code": null,
"e": 16095,
"s": 15513,
"text": "def processExamples(qs_Examples, cDict): Y_vector = np.zeros(qs_Examples.count(), dtype=np.int8) Y_vec_count = 0 examplesMatrix = None for ex in qs_Examples: Y_vector[Y_vec_count] = int(ex.quality_class) Y_vec_count = Y_vec_count + 1 if(examplesMatrix is None): examplesMatrix = buildExampleRow(ex.body_text, cDict) else: examplesMatrix = np.vstack( [examplesMatrix, buildExampleRow(ex.body_text, cDict)]) print('.', end='', flush=True) return( (Y_vector, examplesMatrix))"
},
{
"code": null,
"e": 16166,
"s": 16095,
"text": "Now we can set up for training quickly and easily in class_learner.py:"
},
{
"code": null,
"e": 16395,
"s": 16166,
"text": "from newsbot.util import *print(\"Setting up..\")cDict = loadCanonDict()qs_Examples = ArticleExample.objects.filter(quality_class__lt = 5)print(\"Processing examples\")(Y_vector, examplesMatrix) = processExamples(qs_Examples, cDict)"
},
{
"code": null,
"e": 16579,
"s": 16395,
"text": "It is now time to train and test models. We will break our data into a training and testing set, then we will train our multi-layer perceptron classifier. Easy peasy, as it turns out:"
},
{
"code": null,
"e": 16772,
"s": 16579,
"text": "X_train, X_test, y_train, y_test = train_test_split(examplesMatrix, Y_vector, test_size=0.2)model = MLPClassifier(hidden_layer_sizes=(128,64,32,16,8), max_iter=2500)model.fit(X_train, y_train)"
},
{
"code": null,
"e": 17049,
"s": 16772,
"text": "The great thing about using a powerful library like SciKit is that the basics of this process are the same for several different models. When you want to change models, you can change the line model=MLPClassifier(...) to another model and you will often get a working program."
},
{
"code": null,
"e": 17379,
"s": 17049,
"text": "Now we have a trained model, and we finally get around to finding out if it worked and if we can build something cool from it. To find out, we’ll need to do some tests and understand them. Thus begins the process of model validation. For a classification model, we can get a great idea of how we’re doing at classifying our news."
},
{
"code": null,
"e": 17593,
"s": 17379,
"text": "print(“***************”)print(“Classification based:”)print(accuracy_score(predictions, y_test))print(confusion_matrix(predictions, y_test))print(classification_report(predictions, y_test))print(“***************”)"
},
{
"code": null,
"e": 17613,
"s": 17593,
"text": "Drumroll, please..."
},
{
"code": null,
"e": 18188,
"s": 17613,
"text": "***************Accuracy score: 0.546Confusion Matrix: [[ 35 8 3 2] [ 10 44 28 5] [ 21 40 83 58] [ 3 4 45 111]]Classification report: precision recall f1-score support1 0.51 0.73 0.60 48 2 0.46 0.51 0.48 87 3 0.52 0.41 0.46 202 4 0.63 0.68 0.65 163accuracy 0.55 500 macro avg 0.53 0.58 0.55 500weighted avg 0.54 0.55 0.54 500***************"
},
{
"code": null,
"e": 18224,
"s": 18188,
"text": "Interpreting these numbers, we get:"
},
{
"code": null,
"e": 18414,
"s": 18224,
"text": "Accuracy Score, 0.546: This means 54.6% of our predictions were accurate. Since we have 4 classes, a random guess would have produced an accuracy of 25%, so this is actually an improvement."
},
{
"code": null,
"e": 19334,
"s": 18414,
"text": "Confusion matrix: This set of 16 numbers gives us some very interesting information. I have plotted it below in a more readable format. The rows are each for a class predicted class, and each column has the true class. The number at the intersection of the row and column is the number of the real class predicted as each predicted class. So, for instance, the number 44 that you see on the second row, second column is the number of examples where the true class was 2, and the predicted value was also 2. The 28 you see in the next column of the same row is the number of examples that were actually a 2 but our model predicted a 3. Notice that among articles that are actually a 1, there is strong weighting toward the 1/2 end of the scale. Similarly, on the bottom row we have examples that are actually graded a 4, and notice that the last 2 columns are overwhelmingly bigger than the first two. This is good news!"
},
{
"code": null,
"e": 19357,
"s": 19334,
"text": "Classification Report:"
},
{
"code": null,
"e": 20128,
"s": 19357,
"text": "Here, each row represents a class, and shows precision, recall, and F1 score. The numbers you see here vary from great to not so great. Generally speaking, it looks like we’re better at locating true news than fake, but if we can do that, we may still get close enough to work with. If you continue down, you’ll see we also get an overall weighted average precision/recall/F1 score that give us a clearer idea of how the model performs overall. Our 0.54 F1 score gives us a balance between our precision and recall scores, and is a good single metric for evaluating classification models. If we get a substantially higher F1 on another model, we should choose it over this one. Accuracy score is also a good single metric, and in practice the two are usually very close."
},
{
"code": null,
"e": 20277,
"s": 20128,
"text": "Earlier, I noted in the confusion matrix that it seems like the classifier is often off by 1. If I also look at the mean absolute error of my model:"
},
{
"code": null,
"e": 20365,
"s": 20277,
"text": "mae = mean_absolute_error(y_test, predictions)print(“Mean absolute Error: “ + str(mae))"
},
{
"code": null,
"e": 20377,
"s": 20365,
"text": "I will get:"
},
{
"code": null,
"e": 20403,
"s": 20377,
"text": "Mean absolute Error: 0.54"
},
{
"code": null,
"e": 20895,
"s": 20403,
"text": "Which is further evidence that, on average, the model is within 1 class of the actual answer. This will inform our further development of our models and our end delivery. If we are going to deliver this model to the end user to give them a clear picture of what our model is thinking, we will need to produce probability estimates. Most models can handle that automatically, the support vector classifier requires the “probability=True” flag to produce a probability estimator when training."
},
{
"code": null,
"e": 21342,
"s": 20895,
"text": "Now that you know how to read a confusion matrix and a classification report, and we’ve picked out our single metric for model evaluation, we can now test out a whole bunch of different models. In the code available in the repository, I’ve just commented out calls for all the various models shown here so you can see that scikit allows you to switch learning models by simply changing the model declaration, and everything else remains the same."
},
{
"code": null,
"e": 21356,
"s": 21342,
"text": "3 hours later"
},
{
"code": null,
"e": 21486,
"s": 21356,
"text": "After a lot of training and cataloging of results, here is the outcome of our tests of various different models for this problem:"
},
{
"code": null,
"e": 21688,
"s": 21486,
"text": "Well, I’m pretty surprised that logistic regression took the 2nd spot. Not so surprised about K-Neighbors and Decision Tree, they didn’t seem like a good fit for this problem. SVC was the clear winner."
},
{
"code": null,
"e": 21717,
"s": 21688,
"text": "Thinking about our interface"
},
{
"code": null,
"e": 22118,
"s": 21717,
"text": "Now we have a clear picture of how well or poorly our models perform. Next we need to see how they perform on live examples. We know that the models tend to be close to correct even if they aren’t correct. We next need to know more about whether or not they provide conflicting answers or if they are giving us consistent answers. We’ll have to save our top 3 models and build something to test them."
},
{
"code": null,
"e": 22136,
"s": 22118,
"text": "Saving our models"
},
{
"code": null,
"e": 22407,
"s": 22136,
"text": "For this part of the task, I created a new file called class_saver.py. This way, I can load the data 1 time, run and test all three top models, and save them using pickle. We’ll set up our environment and then put our top three models into an iterable python dictionary:"
},
{
"code": null,
"e": 22971,
"s": 22407,
"text": "print(\"Setting up..\")cDict = loadCanonDict()qs_Examples = ArticleExample.objects.filter(quality_class__lt = 5)print(\"Processing examples\")(Y_vector, examplesMatrix) = processExamples(qs_Examples, cDict)X_train, X_test, y_train, y_test = train_test_split(examplesMatrix, Y_vector, test_size=0.2)chosen_models = {}chosen_models['newsbot/MLPC_model.sav'] = MLPClassifier(hidden_layer_sizes=(128,64,32,16,8), max_iter=2500)chosen_models['newsbot/svc_model.sav'] = SVC(gamma='scale', probability = True)chosen_models['newsbot/log_model.sav'] = LogisticRegression()"
},
{
"code": null,
"e": 23270,
"s": 22971,
"text": "Next we will cycle through the chosen models, train them, and decide if we want to keep them. Note that these models have random initializations and running them more than once will produce slightly different results, so you need to take a peek at their statistics to be sure you’ve got a good one."
},
{
"code": null,
"e": 23743,
"s": 23270,
"text": "for fname, model in chosen_models.items(): print(\"Working on \" + fname) model.fit(X_train, y_train) predictions = model.predict(X_test) print(\"Classification report: \") print(classification_report(predictions, y_test)) print(\"***************\") dosave = input(\"Save \" + fname + \"? \") if(dosave == 'y' or dosave == 'Y'): print(\"Saving...\") pickle.dump(model, open(fname, 'wb')) print(\"Saved!\") else: print(\"Not saved!\")"
},
{
"code": null,
"e": 23875,
"s": 23743,
"text": "After training your models and saving them, you’ll wind up with 3 files. My 3 files were very large, total of about 391MB together."
},
{
"code": null,
"e": 24093,
"s": 23875,
"text": "Now, let’s build a command-line interface that will give us our estimates on live examples. Here we can re-use a lot of code. If you’re following along in the repository, we’re now going to work with classify_news.py."
},
{
"code": null,
"e": 24251,
"s": 24093,
"text": "After we do our usual setup of adding in the required imports and setting up Django for our ORM access, we next need to load up our 3 models designed before."
},
{
"code": null,
"e": 24488,
"s": 24251,
"text": "print(“Loading brain...”)log_model = pickle.load(open(‘newsbot/log_model.sav’, ‘rb’))svc_model = pickle.load(open(‘newsbot/svc_model.sav’, ‘rb’))mlp_model = pickle.load(open(‘newsbot/mlp_model.sav’, ‘rb’))print(“Brain load successful.”)"
},
{
"code": null,
"e": 24584,
"s": 24488,
"text": "Next we need to initialize everything for turning an article into an example, as we did before:"
},
{
"code": null,
"e": 24673,
"s": 24584,
"text": "print(\"Initializing dictionaries...\")cDict = loadCanonDict()ss = SoupStrainer()ss.init()"
},
{
"code": null,
"e": 24732,
"s": 24673,
"text": "Then we turn our article into an input row for our models:"
},
{
"code": null,
"e": 24956,
"s": 24732,
"text": "url = input(\"URL to analyze: \")print(\"Attempting URL: \" + url)if(ss.loadAddress(url)): articleX = buildExampleRow(ss.extractText, cDict)else: print(\"Error on URL, exiting\") exit(0)articleX = articleX.reshape(1, -1)"
},
{
"code": null,
"e": 25076,
"s": 24956,
"text": "And finally, when we have a proper row vector set up, we can predict and generate probabilities for each of our models:"
},
{
"code": null,
"e": 25795,
"s": 25076,
"text": "log_prediction = log_model.predict(articleX)log_probabilities = log_model.predict_proba(articleX)svc_prediction = svc_model.predict(articleX)svc_probabilities = svc_model.predict_proba(articleX)mlp_prediction = mlp_model.predict(articleX)mlp_probabilities = mlp_model.predict_proba(articleX)# 6. Display the processed text and the resultsprint(“*** SVC “)print(“Prediction on this article is: “)print(svc_prediction)print(“Probabilities:”)print(svc_probabilities)print(“*** Logistic “)print(“Prediction on this article is: “)print(log_prediction)print(“Probabilities:”)print(log_probabilities)print(“*** MLP “)print(“Prediction on this article is: “)print(mlp_prediction)print(“Probabilities:”)print(mlp_probabilities)"
},
{
"code": null,
"e": 26227,
"s": 25795,
"text": "Now I run the classifier. It takes about 1 to 2 seconds load time to unpickle my models and load up dictionaries, which is a little long but still acceptable. If we are rolling this out at scale, we need to find a way to load the models and dictionaries in memory and have them persist there until removed. For our development version, this will still work. If I paste in an article URL I think is real, I get the following output:"
},
{
"code": null,
"e": 26573,
"s": 26227,
"text": "*** SVC Prediction on this article is: [3]Probabilities:[[0.01111608 0.0503078 0.70502378 0.23355233]]*** Logistic Prediction on this article is: [3]Probabilities:[[5.61033543e-04 5.89780773e-03 7.63196217e-01 2.30344942e-01]]*** MLP Prediction on this article is: [4]Probabilities:[[1.18020372e-04 1.93965844e-09 4.88694225e-01 5.11187753e-01]]"
},
{
"code": null,
"e": 27190,
"s": 26573,
"text": "These probabilities are showing me the probabilities associated with each of my 4 classes, with the first one being a ruling of fully fake, and the last being a ruling of fully real. In the support vector classifier, the odds of real or mostly real is 70.5+ 23.4 = 93.9%! Similar numbers are achieved with the other two. All of my classifiers agree, this article looks very real. It was the top article on Washington Post at the time of this writing. Next, I go to a very dodgy news source that is a known purveyor of fake and dodgy news stories and pick a story from their front page at random. Here is that output:"
},
{
"code": null,
"e": 27520,
"s": 27190,
"text": "*** SVC Prediction on this article is: [1]Probabilities:[[0.80220529 0.18501285 0.01051862 0.00226324]]*** Logistic Prediction on this article is: [1]Probabilities:[[0.53989611 0.45269964 0.0005857 0.00681855]]*** MLP Prediction on this article is: [1]Probabilities:[[8.38376936e-01 1.84104358e-03 1.59391877e-01 3.90143317e-04]]"
},
{
"code": null,
"e": 27783,
"s": 27520,
"text": "Eureka! All three classifiers agree, this article is fake. The probabilities are interesting here. the SVC and Logistic models are very sure on this being on the fake/dodgy end of things. Notice that the MLP gives a 15.9% chance of the article being mostly true."
},
{
"code": null,
"e": 28106,
"s": 27783,
"text": "Finally, I will test an article sent to me by one of my readers who I invited to be a beta tester. He found that it was producing inconsistent results in an earlier version of this project, specifically that the first version of my SVC and MLP models were disagreeing. In this version, it also comes up very controversial:"
},
{
"code": null,
"e": 28453,
"s": 28106,
"text": "*** SVC Prediction on this article is: [3]Probabilities:[[0.28233338 0.38757642 0.26880828 0.06128192]]*** Logistic Prediction on this article is: [3]Probabilities:[[3.93710544e-01 1.68049849e-01 4.38124141e-01 1.15466230e-04]]*** MLP Prediction on this article is: [3]Probabilities:[[3.67580348e-03 1.66093528e-05 9.96254861e-01 5.27264258e-05]]"
},
{
"code": null,
"e": 29234,
"s": 28453,
"text": "Notice that the SVC has almost no idea what to make of this, giving it a pretty equal rating in classes 1, 2, and 3, and then it chose to predict class 3 even though class 2 has the highest probability. The same basic outcome is seen in the logistic model: Somewhat similar probabilities for 1 and 3, plus a 16.8% chance of 2, and it ultimately predicted a 3. The MLP model is sure this article is a 3. Intriguingly, this article is about the economy, but it is from a dodgy source and uses a lot of very loaded language similar to fake news. I think the classifiers have a hard time because it is about a topic outside the training domain. The articles used in training were generally about US politics rather than about the economy, so that may be why we’re seeing this outcome."
},
{
"code": null,
"e": 29261,
"s": 29234,
"text": "Building the web interface"
},
{
"code": null,
"e": 29897,
"s": 29261,
"text": "Whew. It has been a long journey, folks. Now we have our 3 models that seem to work pretty well, and we want to deploy them so the public can use them. We know that in many cases where an article should be in class 4, our models usually put most of their weight into class 3 and 4, and that they work similarly on the other end of the scale. We know they sometimes disagree, especially on the finer point of the specific probabilities involved. And we know that the typical user isn’t going to install python and a huge batch of libraries to use this tool. We have to make it easy to use, easy to understand, and available to everyone."
},
{
"code": null,
"e": 30053,
"s": 29897,
"text": "Great news, we originally put this puppy together in the Django MVC framework, so from here it is a relatively simple process to build out a web interface."
},
{
"code": null,
"e": 30156,
"s": 30053,
"text": "First, we update the views.py provided by django when we used startapp to start up this whole process."
},
{
"code": null,
"e": 30373,
"s": 30156,
"text": "In this part, we see some familiar code we’ve worked with before in our command-line interface to set up the models, parse an example, and return our row vector representing the word content of the submitted article:"
},
{
"code": null,
"e": 31293,
"s": 30373,
"text": "from django.shortcuts import renderimport pandas as pdimport numpy as npimport picklefrom .models import *from .forms import *from newsbot.strainer import *from newsbot.util import *def index(request): url = request.GET.get('u') if((url is not None) and (len(url) > 5)): print(\"Setting up\") svc_model = pickle.load(open('newsbot/svc_model.sav', 'rb')) mlp_model = pickle.load(open('newsbot/MLPC_model.sav', 'rb')) log_model = pickle.load(open('newsbot/log_model.sav', 'rb')) cDict = loadCanonDict() ss = SoupStrainer() ss.init() print(\"Setup complete\") print(\"Attempting URL: \" + url) if(ss.loadAddress(url)): articleX = buildExampleRow(ss.extractText, cDict) else: print(\"Error on URL, exiting\") return render(request, 'urlFail.html', {'URL', url}) articleX = articleX.reshape(1, -1)"
},
{
"code": null,
"e": 31429,
"s": 31293,
"text": "Shazam, we’ve got articleX as our article in a numpy array of 1s and 0s that represents the canonical words that appear in the article."
},
{
"code": null,
"e": 31478,
"s": 31429,
"text": "Now we need to get a result from all our models:"
},
{
"code": null,
"e": 31778,
"s": 31478,
"text": " svc_prediction = svc_model.predict(articleX) svc_probabilities = svc_model.predict_proba(articleX) mlp_prediction = mlp_model.predict(articleX) mlp_probabilities = mlp_model.predict_proba(articleX) log_prediction = log_model.predict(articleX) log_probabilities = log_model.predict_proba(articleX)"
},
{
"code": null,
"e": 32129,
"s": 31778,
"text": "Next I need to set up some display variables we might want for our template. We want as little math and logic as we can in the template, so we’re setting up the probabilities in display-friending percentage points instead of the statistician’s familiar 0-to-1 float form. We create a total fake and total real metric for each of the models like this:"
},
{
"code": null,
"e": 32199,
"s": 32129,
"text": "Total Fake = Fake (class 0) probability + Dodgy (class 1) probability"
},
{
"code": null,
"e": 32275,
"s": 32199,
"text": "Total Real = Seems Legit (class 3) probability + True (class 3) probability"
},
{
"code": null,
"e": 32405,
"s": 32275,
"text": "This gives us just 1 comparison to do in our template to decide if we want to display “Seems Real” or “Seems Fake” as our ruling."
},
{
"code": null,
"e": 33242,
"s": 32405,
"text": "svc_prb = (svc_probabilities[0][0]*100, svc_probabilities[0][1]*100, svc_probabilities[0][2]*100, svc_probabilities[0][3]*100) svc_totFake = (svc_probabilities[0][0]*100) + (svc_probabilities[0][1]*100) svc_totReal = (svc_probabilities[0][2]*100) + (svc_probabilities[0][3]*100) mlp_prb = (mlp_probabilities[0][0]*100, mlp_probabilities[0][1]*100, mlp_probabilities[0][2]*100, mlp_probabilities[0][3]*100) mlp_totFake = (mlp_probabilities[0][0]*100) + (mlp_probabilities[0][1]*100) mlp_totReal = (mlp_probabilities[0][2]*100) + (mlp_probabilities[0][3]*100) log_prb = (log_probabilities[0][0]*100, log_probabilities[0][1]*100, log_probabilities[0][2]*100, log_probabilities[0][3]*100) log_totFake = (log_probabilities[0][0]*100) + (log_probabilities[0][1]*100) log_totReal = (log_probabilities[0][2]*100) + (log_probabilities[0][3]*100)"
},
{
"code": null,
"e": 33629,
"s": 33242,
"text": "Then we want to combine these three models. This will handle the cases of controversial rulings. If 2 of our 3 models are strongly leaning one way, and the other is leaning strongly the other, then averaging them together will settle the dispute. That gives us a probability distribution that we can use as the top-of-page, single prediction that our end user wants: Is it real or fake?"
},
{
"code": null,
"e": 34147,
"s": 33629,
"text": "fin_prb = ( (((svc_probabilities[0][0]*100)+(mlp_probabilities[0][0]*100)+(log_probabilities[0][0]*100))/3), (((svc_probabilities[0][1]*100)+(mlp_probabilities[0][1]*100)+(log_probabilities[0][1]*100))/3), (((svc_probabilities[0][2]*100)+(mlp_probabilities[0][2]*100)+(log_probabilities[0][2]*100))/3), (((svc_probabilities[0][3]*100)+(mlp_probabilities[0][3]*100)+(log_probabilities[0][3]*100))/3) ) fin_totFake = (svc_totFake + mlp_totFake + log_totFake)/3 fin_totReal = (svc_totReal + mlp_totReal + log_totReal)/3"
},
{
"code": null,
"e": 34225,
"s": 34147,
"text": "Then we dump all that into a context and send that puppy off to our template:"
},
{
"code": null,
"e": 34816,
"s": 34225,
"text": "context = {‘headline’:ss.recHeadline, ‘words’: ss.extractText, ‘url’ : url, ‘svc_totFake’: svc_totFake, ‘svc_totReal’: svc_totReal, ‘svc_prediction’: svc_prediction, ‘svc_probabilities’: svc_prb, ‘mlp_totFake’: mlp_totFake, ‘mlp_totReal’: mlp_totReal, ‘mlp_prediction’: mlp_prediction, ‘mlp_probabilities’: mlp_prb, ‘log_totFake’: log_totFake, ‘log_totReal’: log_totReal, ‘log_prediction’: log_prediction, ‘log_probabilities’: log_prb, ‘fin_totFake’: fin_totFake, ‘fin_totReal’: fin_totReal, ‘fin_probabilities’: fin_prb } return render(request, ‘newsbot/results.html’, context)"
},
{
"code": null,
"e": 34932,
"s": 34816,
"text": "And you’ll need to add this bit at the end to render the form asking the user to enter a URL if one isn’t provided:"
},
{
"code": null,
"e": 34985,
"s": 34932,
"text": "else: return render(request, ‘newsbot/urlForm.html’)"
},
{
"code": null,
"e": 35109,
"s": 34985,
"text": "Within the results.html, we just have to create a quick table with each outcome. Here’s the one for the final ruling table:"
},
{
"code": null,
"e": 36470,
"s": 35109,
"text": "<h3 style=”text-align: center;”> Combined Result:<br> {% if fin_totFake >= fin_totReal %} Fake/Dodgy {% else %} Seems Legit/True {% endif %} </h3> <br>Probability of Fake: {{ fin_probabilities.0|floatformat }}% chance of Fake<div class=”progress”> <div class=”progress-bar” id=”fakeProb_bar” role=”progressbar” aria-valuenow=”{{ fin_probabilities.0 }}” aria-valuemin=”0\" aria-valuemax=”100\" style=”width:{{ fin_probabilities.0 }}%”></div></div> <br>Probability of Dodgy: {{ fin_probabilities.1|floatformat }}% chance of Dodgy<div class=”progress”> <div class=”progress-bar” id=”MfakeProb_bar” role=”progressbar” aria-valuenow=”{{ fin_probabilities.1 }}” aria-valuemin=”0\" aria-valuemax=”100\" style=”width:{{ fin_probabilities.1 }}%”></div></div> <br>Probability of Mostly True: {{ fin_probabilities.2|floatformat }}% chance of Mostly True<div class=”progress”> <div class=”progress-bar” id=”MtrueProb_bar” role=”progressbar” aria-valuenow=”{{ fin_probabilities.2 }}” aria-valuemin=”0\" aria-valuemax=”100\" style=”width:{{ fin_probabilities.2 }}%”></div></div> <br>Probability of True: {{ fin_probabilities.3|floatformat }}% chance of True<div class=”progress”> <div class=”progress-bar” id=”trueProb_bar” role=”progressbar” aria-valuenow=”{{ fin_probabilities.3 }}” aria-valuemin=”0\" aria-valuemax=”100\" style=”width:{{ fin_probabilities.3 }}%”></div></div>"
},
{
"code": null,
"e": 36519,
"s": 36470,
"text": "Repeat for any other models you want to display."
},
{
"code": null,
"e": 36521,
"s": 36519,
"text": "—"
},
{
"code": null,
"e": 36527,
"s": 36521,
"text": "Recap"
},
{
"code": null,
"e": 37116,
"s": 36527,
"text": "If you’ve made it this far, we’ve been on quite a journey. We started out with a hypothesis that seemed like something a machine couldn’t figure out. We found data to train our machine, coaxed that data into a form our machine could handle, and trained the machine. And then we tested it against live data and, much to the amazement of everyone, found that it actually has a sensible answer. Finishing a long project like this gives you a complete picture of the entire machine learning pipeline. This project, long as it was, still has a lot of room for improvements. More ideas include:"
},
{
"code": null,
"e": 37226,
"s": 37116,
"text": "Ask the user if they think the bot was right or wrong, and record their answers for possible future training."
},
{
"code": null,
"e": 37287,
"s": 37226,
"text": "Find more data sets or get more data sets from more sources."
},
{
"code": null,
"e": 37368,
"s": 37287,
"text": "Write a crawler to dig through fake news sites gathering more and more examples."
},
{
"code": null,
"e": 37390,
"s": 37368,
"text": "Tune hyperparameters."
},
{
"code": null,
"e": 37452,
"s": 37390,
"text": "Expand domain knowledge to other countries or other subjects."
},
{
"code": null,
"e": 37503,
"s": 37452,
"text": "Use the domain name or headline as a data feature."
},
{
"code": null,
"e": 37627,
"s": 37503,
"text": "Find a way to count the number of advertisements on the page, on the hypothesis that fake news sites usually have more ads."
}
]
|
How to Detect Mouth Open for Face Login | by Peter Xie | Towards Data Science | Have you ever used bank/payment app face login and been asked to open mouth, nod or turn head? Such methods have been very popular, especially in China, to prevent deceiving/hacking using static face images or 3D prints. I spent about two days and finally figured out a quite simple way to detect mouth open utilizing the feature outputs from the face_recognition project.
Here is a quick look at the effect when applying the algorithm to real-time webcam video.
face_recognition is an awesome open source project for face recognition based on dlib, just as described by itself:
The world’s simplest facial recognition api for Python and the command line
With a few lines of Python code, you can detect a face, recognize who it is and output face features, such as chin, eyes, nose, and lips.
For example, run the sample find_facial_features_in_picture.py (only 40 lines of code) for an Obama image, you can get all facial features as shown below.
You will also get the facial feature details in standard output, including top lip and bottom lip. Each feature is a list of positional points.
You can follow the steps in the face_recognition project on github, or just simply download the pre-configured VM (strongly recommended).
The face_recognition provides APIs for static figure analysis, but it won’t tell you facial motions like mouth opening or nod. However, we can detect these motions by the feature outputs, i.e., mouth open/close in this case.
Both top lip and bottom lip feature outputs contain a list of 12 positional points, but in different orders.
top_lip points: [(181, 359), (192, 339), (211, 332), (225, 336), (243, 333), (271, 342), (291, 364), (282, 363), (242, 346), (225, 347), (211, 345), (188, 358)]bottom_lip points: [(291, 364), (270, 389), (243, 401), (223, 403), (207, 399), (190, 383), (181, 359), (188, 358), (210, 377), (225, 381), (243, 380), (282, 363)]
Plot the lip points with matplotlib and you can see clearly the point order as shown below. Check out the plot script here if interested.
My algorithm is very simple:
If mouth open height is greater than lip height * ratio, mouth is open.
ratio: is adjustable and define how much the mouth is open. You can simply put ratio = 1, which means the mouth is open more than lip height.
lip height: Average of the distances of the three pairs of points as follows:
2–103–94–8
These pairs are the same for both top and bottom lip points.
mouth height: Average of the distances of the three pairs of points as follows:
Top lip 8–10 Bottom lipTop lip 9–9 Bottom lipTop lip 10–8 Bottom lip
lip height function:
If you add up the indexes of each point pairs, you will find the sum is always 12. So if i is one point, the other point is 12-i.
The distance of two points (x1,y1) and (x2,y2) is defined as follows.
Thus we get the lip height function below.
mouth height function:
Add up the indexes of each mouth point pairs, the sum is 18.
check mouth open function:
With lip height and mouth height functions, we can define the check mouth open function as below.
I choose the min value of top lip height and bottom lip height as lip height. Or you can use the average value.
And I pick a ratio as 0.5, so I don’t need to open a big mouth to test it 😄.
Okay, everything is clear and ready. Let’s test it out.
Outputs:
top_lip height: 12.35bottom_lip height: 21.76mouth height: 33.34Is mouth open: True
Combine the face_recognition and the mouth open detection algorithm, we can develop a webcam real-time face recognition app with the ability to detect mouth open/close as you see from the video in the beginning of this post. It is just 80 lines of code and you can clone from github here. Note that you need to install face_recognition package first.
git clone https://github.com/peterjpxie/detect_mouth_open.gitcd detect_mouth_openpython facerec_from_webcam_mouth_open.py
This is just one way to detect mouth open. You will definitely find other approaches, similar or not, from other sources, or you can figure out your own method. It is just fun and exciting to work out a method yourself before searching for an answer.
Thanks for reading. | [
{
"code": null,
"e": 544,
"s": 171,
"text": "Have you ever used bank/payment app face login and been asked to open mouth, nod or turn head? Such methods have been very popular, especially in China, to prevent deceiving/hacking using static face images or 3D prints. I spent about two days and finally figured out a quite simple way to detect mouth open utilizing the feature outputs from the face_recognition project."
},
{
"code": null,
"e": 634,
"s": 544,
"text": "Here is a quick look at the effect when applying the algorithm to real-time webcam video."
},
{
"code": null,
"e": 750,
"s": 634,
"text": "face_recognition is an awesome open source project for face recognition based on dlib, just as described by itself:"
},
{
"code": null,
"e": 826,
"s": 750,
"text": "The world’s simplest facial recognition api for Python and the command line"
},
{
"code": null,
"e": 964,
"s": 826,
"text": "With a few lines of Python code, you can detect a face, recognize who it is and output face features, such as chin, eyes, nose, and lips."
},
{
"code": null,
"e": 1119,
"s": 964,
"text": "For example, run the sample find_facial_features_in_picture.py (only 40 lines of code) for an Obama image, you can get all facial features as shown below."
},
{
"code": null,
"e": 1263,
"s": 1119,
"text": "You will also get the facial feature details in standard output, including top lip and bottom lip. Each feature is a list of positional points."
},
{
"code": null,
"e": 1401,
"s": 1263,
"text": "You can follow the steps in the face_recognition project on github, or just simply download the pre-configured VM (strongly recommended)."
},
{
"code": null,
"e": 1626,
"s": 1401,
"text": "The face_recognition provides APIs for static figure analysis, but it won’t tell you facial motions like mouth opening or nod. However, we can detect these motions by the feature outputs, i.e., mouth open/close in this case."
},
{
"code": null,
"e": 1735,
"s": 1626,
"text": "Both top lip and bottom lip feature outputs contain a list of 12 positional points, but in different orders."
},
{
"code": null,
"e": 2059,
"s": 1735,
"text": "top_lip points: [(181, 359), (192, 339), (211, 332), (225, 336), (243, 333), (271, 342), (291, 364), (282, 363), (242, 346), (225, 347), (211, 345), (188, 358)]bottom_lip points: [(291, 364), (270, 389), (243, 401), (223, 403), (207, 399), (190, 383), (181, 359), (188, 358), (210, 377), (225, 381), (243, 380), (282, 363)]"
},
{
"code": null,
"e": 2197,
"s": 2059,
"text": "Plot the lip points with matplotlib and you can see clearly the point order as shown below. Check out the plot script here if interested."
},
{
"code": null,
"e": 2226,
"s": 2197,
"text": "My algorithm is very simple:"
},
{
"code": null,
"e": 2298,
"s": 2226,
"text": "If mouth open height is greater than lip height * ratio, mouth is open."
},
{
"code": null,
"e": 2440,
"s": 2298,
"text": "ratio: is adjustable and define how much the mouth is open. You can simply put ratio = 1, which means the mouth is open more than lip height."
},
{
"code": null,
"e": 2518,
"s": 2440,
"text": "lip height: Average of the distances of the three pairs of points as follows:"
},
{
"code": null,
"e": 2529,
"s": 2518,
"text": "2–103–94–8"
},
{
"code": null,
"e": 2590,
"s": 2529,
"text": "These pairs are the same for both top and bottom lip points."
},
{
"code": null,
"e": 2670,
"s": 2590,
"text": "mouth height: Average of the distances of the three pairs of points as follows:"
},
{
"code": null,
"e": 2740,
"s": 2670,
"text": "Top lip 8–10 Bottom lipTop lip 9–9 Bottom lipTop lip 10–8 Bottom lip"
},
{
"code": null,
"e": 2761,
"s": 2740,
"text": "lip height function:"
},
{
"code": null,
"e": 2891,
"s": 2761,
"text": "If you add up the indexes of each point pairs, you will find the sum is always 12. So if i is one point, the other point is 12-i."
},
{
"code": null,
"e": 2961,
"s": 2891,
"text": "The distance of two points (x1,y1) and (x2,y2) is defined as follows."
},
{
"code": null,
"e": 3004,
"s": 2961,
"text": "Thus we get the lip height function below."
},
{
"code": null,
"e": 3027,
"s": 3004,
"text": "mouth height function:"
},
{
"code": null,
"e": 3088,
"s": 3027,
"text": "Add up the indexes of each mouth point pairs, the sum is 18."
},
{
"code": null,
"e": 3115,
"s": 3088,
"text": "check mouth open function:"
},
{
"code": null,
"e": 3213,
"s": 3115,
"text": "With lip height and mouth height functions, we can define the check mouth open function as below."
},
{
"code": null,
"e": 3325,
"s": 3213,
"text": "I choose the min value of top lip height and bottom lip height as lip height. Or you can use the average value."
},
{
"code": null,
"e": 3402,
"s": 3325,
"text": "And I pick a ratio as 0.5, so I don’t need to open a big mouth to test it 😄."
},
{
"code": null,
"e": 3458,
"s": 3402,
"text": "Okay, everything is clear and ready. Let’s test it out."
},
{
"code": null,
"e": 3467,
"s": 3458,
"text": "Outputs:"
},
{
"code": null,
"e": 3551,
"s": 3467,
"text": "top_lip height: 12.35bottom_lip height: 21.76mouth height: 33.34Is mouth open: True"
},
{
"code": null,
"e": 3902,
"s": 3551,
"text": "Combine the face_recognition and the mouth open detection algorithm, we can develop a webcam real-time face recognition app with the ability to detect mouth open/close as you see from the video in the beginning of this post. It is just 80 lines of code and you can clone from github here. Note that you need to install face_recognition package first."
},
{
"code": null,
"e": 4024,
"s": 3902,
"text": "git clone https://github.com/peterjpxie/detect_mouth_open.gitcd detect_mouth_openpython facerec_from_webcam_mouth_open.py"
},
{
"code": null,
"e": 4275,
"s": 4024,
"text": "This is just one way to detect mouth open. You will definitely find other approaches, similar or not, from other sources, or you can figure out your own method. It is just fun and exciting to work out a method yourself before searching for an answer."
}
]
|
How to list the directory content in PowerShell? | To display the directory content, Get-ChildItem cmdlet is used. You need to provide the path of the directory or if you are in the same directory, you need to use only Get-ChildItem directly. In the below example, we need to display the contents of the D:\temp directory.
When Get-ChildItem command is run outside of this directory then the path of the directory should be provided. This is called the absolute path.
PS C:\> Get-ChildItem D:\Temp\
When this command is run directly within the directory then simply run this command. This is called a relative path.
PS D:\Temp> Get-ChildItem
Directory: D:\Temp
Mode LastWriteTime Length Name
---- ------------- ------ ----
d----- 13-12-2019 09:52 GPO_backup
d----- 24-11-2018 11:31 LGPO
-a---- 07-05-2018 23:00 301 cars.xml
-a---- 29-12-2017 15:16 4526 healthcheck.html
-a---- 29-12-2017 15:16 4526 healthcheck1.html
-a---- 08-12-2017 10:24 48362 servicereport.html
-a---- 08-12-2017 10:24 48362 servicereport1.html
-a---- 08-12-2017 10:16 393 style.css
-a---- 08-12-2017 11:29 7974 Test.xlsx
-a---- 25-10-2017 08:13 104 testcsv.csv
-a---- 12-12-2017 23:04 1034 testhtmoutput.html
Please note − Get-ChildItem command only displays the folders and files but not the content of the subfolders. To display the subfolders and their files, you need to use –Recursive parameter. | [
{
"code": null,
"e": 1334,
"s": 1062,
"text": "To display the directory content, Get-ChildItem cmdlet is used. You need to provide the path of the directory or if you are in the same directory, you need to use only Get-ChildItem directly. In the below example, we need to display the contents of the D:\\temp directory."
},
{
"code": null,
"e": 1479,
"s": 1334,
"text": "When Get-ChildItem command is run outside of this directory then the path of the directory should be provided. This is called the absolute path."
},
{
"code": null,
"e": 1510,
"s": 1479,
"text": "PS C:\\> Get-ChildItem D:\\Temp\\"
},
{
"code": null,
"e": 1627,
"s": 1510,
"text": "When this command is run directly within the directory then simply run this command. This is called a relative path."
},
{
"code": null,
"e": 1654,
"s": 1627,
"text": "PS D:\\Temp> Get-ChildItem\n"
},
{
"code": null,
"e": 2471,
"s": 1654,
"text": "Directory: D:\\Temp\n\nMode LastWriteTime Length Name\n---- ------------- ------ ----\nd----- 13-12-2019 09:52 GPO_backup\nd----- 24-11-2018 11:31 LGPO\n-a---- 07-05-2018 23:00 301 cars.xml\n-a---- 29-12-2017 15:16 4526 healthcheck.html\n-a---- 29-12-2017 15:16 4526 healthcheck1.html\n-a---- 08-12-2017 10:24 48362 servicereport.html\n-a---- 08-12-2017 10:24 48362 servicereport1.html\n-a---- 08-12-2017 10:16 393 style.css\n-a---- 08-12-2017 11:29 7974 Test.xlsx\n-a---- 25-10-2017 08:13 104 testcsv.csv\n-a---- 12-12-2017 23:04 1034 testhtmoutput.html"
},
{
"code": null,
"e": 2663,
"s": 2471,
"text": "Please note − Get-ChildItem command only displays the folders and files but not the content of the subfolders. To display the subfolders and their files, you need to use –Recursive parameter."
}
]
|
BufferedWriter write() method in Java with Examples - GeeksforGeeks | 28 May, 2020
The write() method in BufferedWriter class in Java is used in three ways:
1. The write(int) method of BufferedWriter class in Java is used to write a single character at a time in the buffer writer stream.
Syntax:
public void write(int ch)
throws IOException
Overrides: This method overrides the write() method of Writer class.
Parameters: This method accept single parameter ch which represents the character that is to be written.
Return value: This method does not return any value.
Exceptions: This method throws IOException if an I/O error occurs.
Below program illustrates write(int) method in BufferedWriter class in IO package:
Program:
// Java program to illustrate// BufferedWriter write(int) method import java.io.*; public class GFG { public static void main(String[] args) throws IOException { // Create the string Writer StringWriter stringWriter = new StringWriter(); // Convert stringWriter to // bufferedWriter BufferedWriter buffWriter = new BufferedWriter( stringWriter); // Write "G" to buffer writer buffWriter.write(71); // Write "E" to buffer writer buffWriter.write(69); // Write "E" to buffer writer buffWriter.write(69); // Write "K" to buffer writer buffWriter.write(75); // Write "S" to buffer writer buffWriter.write(83); buffWriter.flush(); System.out.println( stringWriter.getBuffer()); }}
GEEKS
2. The write(String s, int off, int len) method of BufferedWriter class in Java is used to write a part of a string passed as parameter in the buffer writer stream.
Syntax:
public void write(String s,
int off,
int len)
throws IOException
Overrides: This method overrides the write() method of Writer class.
Parameters: This method accept three parameters:
s – It represents the string, the part of which is to written.
off – It represents the index in the string from which writing is started.
len – It represents the length of portion of string to be written.
Return value: This method does not return any value.
Exceptions:
IndexOutOfBoundsException – This method throws IndexOutOfBoundsException if index passed is negative or passed length of portion is greater than the length of the given string.
IOException – This method throws IOException if IO error occurs.
Note: This method should throw an IndexOutOfBoundsException if the length of the portion of the string (len) is negative or index is negative but this method does not throw such an exception in these cases. It writes no characters instead of throwing an exception in such cases.
Below program illustrates write(String) method in BufferedWriter class in IO package:
Program:
// Java program to illustrate// BufferedWriter write(String) method import java.io.*; public class GFG { public static void main(String[] args) throws IOException { // Create the string Writer StringWriter stringWriter = new StringWriter(); // Convert stringWriter to // bufferedWriter BufferedWriter buffWriter = new BufferedWriter( stringWriter); // Write "GEEKS" to buffer writer buffWriter.write( "GEEKSFORGEEKS", 0, 5); buffWriter.flush(); System.out.println( stringWriter.getBuffer()); }}
GEEKS
3. The write(char[ ] cbuf, int off, int len) method of BufferedWriter class in Java is used to write a part of an array of characters passed as parameter in the buffer writer stream. This method generally stores the characters from the array into the stream and flushes the buffer to the mainstream. It can directly use the mainstream when the length of the buffer is equal to length of the array.
Syntax:
public void write(char[ ] cbuf,
int off,
int len)
throws IOException
Specified By: This method is specified by the write() method of Writer class.
Parameters: This method accept three parameters:
cbuf – It represents the array of characters, the part of which is to written.
off – It represents the index of the array from which writing is started.
len – It represents the length of portion of array to be written.
Return value: This method does not return any value.
Exceptions:
IndexOutOfBoundsException – This method throws IndexOutOfBoundsException if index passed is negative or passed length of portion is greater than the length of the given character array.
IOException – This method throws IOException if IO error occurs.
Below program illustrates write(char[ ]) method in BufferedWriter class in IO package:
Program:
// Java program to illustrate// BufferedWriter write(char[ ]) method import java.io.*; public class GFG { public static void main(String[] args) throws IOException { // Create the string Writer StringWriter stringWriter = new StringWriter(); // Convert stringWriter to // bufferedWriter BufferedWriter buffWriter = new BufferedWriter( stringWriter); // Create character array char cbuf[] = { 'G', 'E', 'E', 'K', 'S', 'F', 'O', 'R' }; // Write "GEEKS" to buffer writer buffWriter.write(cbuf, 0, 5); // Write "FOR" to buffer writer buffWriter.write(cbuf, 5, 3); // Again write "GEEKS" to buffer writer buffWriter.write(cbuf, 0, 5); buffWriter.flush(); System.out.println( stringWriter.getBuffer()); }}
GEEKSFORGEEKS
References:1. https://docs.oracle.com/javase/10/docs/api/java/io/BufferedWriter.html#write(int)2. https://docs.oracle.com/javase/10/docs/api/java/io/BufferedWriter.html#write(java.lang.String, int, int)3. https://docs.oracle.com/javase/10/docs/api/java/io/BufferedWriter.html#write(char%5B%5D, int, int)
Java-Functions
Java-IO package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Different ways of Reading a text file in Java
Constructors in Java
Stream In Java
Generics in Java
Exceptions in Java
Functional Interfaces in Java
Comparator Interface in Java with Examples
HashMap get() Method in Java
Strings in Java
StringBuilder Class in Java with Examples | [
{
"code": null,
"e": 23948,
"s": 23920,
"text": "\n28 May, 2020"
},
{
"code": null,
"e": 24022,
"s": 23948,
"text": "The write() method in BufferedWriter class in Java is used in three ways:"
},
{
"code": null,
"e": 24154,
"s": 24022,
"text": "1. The write(int) method of BufferedWriter class in Java is used to write a single character at a time in the buffer writer stream."
},
{
"code": null,
"e": 24162,
"s": 24154,
"text": "Syntax:"
},
{
"code": null,
"e": 24220,
"s": 24162,
"text": "public void write(int ch)\n throws IOException\n"
},
{
"code": null,
"e": 24289,
"s": 24220,
"text": "Overrides: This method overrides the write() method of Writer class."
},
{
"code": null,
"e": 24394,
"s": 24289,
"text": "Parameters: This method accept single parameter ch which represents the character that is to be written."
},
{
"code": null,
"e": 24447,
"s": 24394,
"text": "Return value: This method does not return any value."
},
{
"code": null,
"e": 24514,
"s": 24447,
"text": "Exceptions: This method throws IOException if an I/O error occurs."
},
{
"code": null,
"e": 24597,
"s": 24514,
"text": "Below program illustrates write(int) method in BufferedWriter class in IO package:"
},
{
"code": null,
"e": 24606,
"s": 24597,
"text": "Program:"
},
{
"code": "// Java program to illustrate// BufferedWriter write(int) method import java.io.*; public class GFG { public static void main(String[] args) throws IOException { // Create the string Writer StringWriter stringWriter = new StringWriter(); // Convert stringWriter to // bufferedWriter BufferedWriter buffWriter = new BufferedWriter( stringWriter); // Write \"G\" to buffer writer buffWriter.write(71); // Write \"E\" to buffer writer buffWriter.write(69); // Write \"E\" to buffer writer buffWriter.write(69); // Write \"K\" to buffer writer buffWriter.write(75); // Write \"S\" to buffer writer buffWriter.write(83); buffWriter.flush(); System.out.println( stringWriter.getBuffer()); }}",
"e": 25485,
"s": 24606,
"text": null
},
{
"code": null,
"e": 25492,
"s": 25485,
"text": "GEEKS\n"
},
{
"code": null,
"e": 25657,
"s": 25492,
"text": "2. The write(String s, int off, int len) method of BufferedWriter class in Java is used to write a part of a string passed as parameter in the buffer writer stream."
},
{
"code": null,
"e": 25665,
"s": 25657,
"text": "Syntax:"
},
{
"code": null,
"e": 25778,
"s": 25665,
"text": "public void write(String s,\n int off,\n int len)\n throws IOException\n"
},
{
"code": null,
"e": 25847,
"s": 25778,
"text": "Overrides: This method overrides the write() method of Writer class."
},
{
"code": null,
"e": 25896,
"s": 25847,
"text": "Parameters: This method accept three parameters:"
},
{
"code": null,
"e": 25959,
"s": 25896,
"text": "s – It represents the string, the part of which is to written."
},
{
"code": null,
"e": 26034,
"s": 25959,
"text": "off – It represents the index in the string from which writing is started."
},
{
"code": null,
"e": 26101,
"s": 26034,
"text": "len – It represents the length of portion of string to be written."
},
{
"code": null,
"e": 26154,
"s": 26101,
"text": "Return value: This method does not return any value."
},
{
"code": null,
"e": 26166,
"s": 26154,
"text": "Exceptions:"
},
{
"code": null,
"e": 26343,
"s": 26166,
"text": "IndexOutOfBoundsException – This method throws IndexOutOfBoundsException if index passed is negative or passed length of portion is greater than the length of the given string."
},
{
"code": null,
"e": 26408,
"s": 26343,
"text": "IOException – This method throws IOException if IO error occurs."
},
{
"code": null,
"e": 26687,
"s": 26408,
"text": "Note: This method should throw an IndexOutOfBoundsException if the length of the portion of the string (len) is negative or index is negative but this method does not throw such an exception in these cases. It writes no characters instead of throwing an exception in such cases."
},
{
"code": null,
"e": 26773,
"s": 26687,
"text": "Below program illustrates write(String) method in BufferedWriter class in IO package:"
},
{
"code": null,
"e": 26782,
"s": 26773,
"text": "Program:"
},
{
"code": "// Java program to illustrate// BufferedWriter write(String) method import java.io.*; public class GFG { public static void main(String[] args) throws IOException { // Create the string Writer StringWriter stringWriter = new StringWriter(); // Convert stringWriter to // bufferedWriter BufferedWriter buffWriter = new BufferedWriter( stringWriter); // Write \"GEEKS\" to buffer writer buffWriter.write( \"GEEKSFORGEEKS\", 0, 5); buffWriter.flush(); System.out.println( stringWriter.getBuffer()); }}",
"e": 27427,
"s": 26782,
"text": null
},
{
"code": null,
"e": 27434,
"s": 27427,
"text": "GEEKS\n"
},
{
"code": null,
"e": 27832,
"s": 27434,
"text": "3. The write(char[ ] cbuf, int off, int len) method of BufferedWriter class in Java is used to write a part of an array of characters passed as parameter in the buffer writer stream. This method generally stores the characters from the array into the stream and flushes the buffer to the mainstream. It can directly use the mainstream when the length of the buffer is equal to length of the array."
},
{
"code": null,
"e": 27840,
"s": 27832,
"text": "Syntax:"
},
{
"code": null,
"e": 27957,
"s": 27840,
"text": "public void write(char[ ] cbuf,\n int off,\n int len)\n throws IOException\n"
},
{
"code": null,
"e": 28035,
"s": 27957,
"text": "Specified By: This method is specified by the write() method of Writer class."
},
{
"code": null,
"e": 28084,
"s": 28035,
"text": "Parameters: This method accept three parameters:"
},
{
"code": null,
"e": 28163,
"s": 28084,
"text": "cbuf – It represents the array of characters, the part of which is to written."
},
{
"code": null,
"e": 28237,
"s": 28163,
"text": "off – It represents the index of the array from which writing is started."
},
{
"code": null,
"e": 28303,
"s": 28237,
"text": "len – It represents the length of portion of array to be written."
},
{
"code": null,
"e": 28356,
"s": 28303,
"text": "Return value: This method does not return any value."
},
{
"code": null,
"e": 28368,
"s": 28356,
"text": "Exceptions:"
},
{
"code": null,
"e": 28554,
"s": 28368,
"text": "IndexOutOfBoundsException – This method throws IndexOutOfBoundsException if index passed is negative or passed length of portion is greater than the length of the given character array."
},
{
"code": null,
"e": 28619,
"s": 28554,
"text": "IOException – This method throws IOException if IO error occurs."
},
{
"code": null,
"e": 28706,
"s": 28619,
"text": "Below program illustrates write(char[ ]) method in BufferedWriter class in IO package:"
},
{
"code": null,
"e": 28715,
"s": 28706,
"text": "Program:"
},
{
"code": "// Java program to illustrate// BufferedWriter write(char[ ]) method import java.io.*; public class GFG { public static void main(String[] args) throws IOException { // Create the string Writer StringWriter stringWriter = new StringWriter(); // Convert stringWriter to // bufferedWriter BufferedWriter buffWriter = new BufferedWriter( stringWriter); // Create character array char cbuf[] = { 'G', 'E', 'E', 'K', 'S', 'F', 'O', 'R' }; // Write \"GEEKS\" to buffer writer buffWriter.write(cbuf, 0, 5); // Write \"FOR\" to buffer writer buffWriter.write(cbuf, 5, 3); // Again write \"GEEKS\" to buffer writer buffWriter.write(cbuf, 0, 5); buffWriter.flush(); System.out.println( stringWriter.getBuffer()); }}",
"e": 29623,
"s": 28715,
"text": null
},
{
"code": null,
"e": 29638,
"s": 29623,
"text": "GEEKSFORGEEKS\n"
},
{
"code": null,
"e": 29942,
"s": 29638,
"text": "References:1. https://docs.oracle.com/javase/10/docs/api/java/io/BufferedWriter.html#write(int)2. https://docs.oracle.com/javase/10/docs/api/java/io/BufferedWriter.html#write(java.lang.String, int, int)3. https://docs.oracle.com/javase/10/docs/api/java/io/BufferedWriter.html#write(char%5B%5D, int, int)"
},
{
"code": null,
"e": 29957,
"s": 29942,
"text": "Java-Functions"
},
{
"code": null,
"e": 29973,
"s": 29957,
"text": "Java-IO package"
},
{
"code": null,
"e": 29978,
"s": 29973,
"text": "Java"
},
{
"code": null,
"e": 29983,
"s": 29978,
"text": "Java"
},
{
"code": null,
"e": 30081,
"s": 29983,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30090,
"s": 30081,
"text": "Comments"
},
{
"code": null,
"e": 30103,
"s": 30090,
"text": "Old Comments"
},
{
"code": null,
"e": 30149,
"s": 30103,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 30170,
"s": 30149,
"text": "Constructors in Java"
},
{
"code": null,
"e": 30185,
"s": 30170,
"text": "Stream In Java"
},
{
"code": null,
"e": 30202,
"s": 30185,
"text": "Generics in Java"
},
{
"code": null,
"e": 30221,
"s": 30202,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 30251,
"s": 30221,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 30294,
"s": 30251,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 30323,
"s": 30294,
"text": "HashMap get() Method in Java"
},
{
"code": null,
"e": 30339,
"s": 30323,
"text": "Strings in Java"
}
]
|
Android - Best Practices | There are some practices that you can follow while developing android application. These are suggested by the android itself and they keep on improving with respect to time.
These best practices include interaction design features, performance, security and privacy, compatibility, testing, distributing and monetizing tips. They are narrowed down and are listed as below.
Every text field is intended for a different job. For example, some text fields are for text and some are for numbers. If it is for numbers then it is better to display the numeric keypad when that textfield is focused. Its syntax is.
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:hint="User Name"
android:layout_below="@+id/imageView"
android:layout_alignLeft="@+id/imageView"
android:layout_alignStart="@+id/imageView"
android:numeric="integer" />
Other then that if your field is for password, then it must show a password hint, so that the user can easily remember the password. It can be achieved as.
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText2"
android:layout_alignLeft="@+id/editText"
android:layout_alignStart="@+id/editText"
android:hint="Pass Word"
android:layout_below="@+id/editText"
android:layout_alignRight="@+id/editText"
android:layout_alignEnd="@+id/editText"
android:password="true" />
There are certain jobs in an application that are running in an application background. Their job might be to fetch some thing from the internet , playing music e.t.c. It is recommended that the long awaiting tasks should not be done in the UI thread and rather in the background by services or AsyncTask.
Both are used for doing background tasks , but the service is not affected by most user interface life cycle events, so it continues to run in circumstances that would shut down an AsyncTask.
Your application performance should be up-to the mark. But it should perform differently not on the front end , but on the back end when it the device is connected to a power source or charging. Charging could be of from USB and from wire cable.
When your device is charging itself , it is recommended to update your application settings if any, such as maximizing your refresh rate whenever the device is connected. It can be done as this.
IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = context.registerReceiver(null, ifilter);
// Are we charging / charged? Full or charging.
int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
// How are we charging? From AC or USB.
int chargePlug = batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
It is very important that your application should be secure and not only the application , but the user data and the application data should also be secured. The security can be increased by the following factors.
Use internal storage rather then external for storing applications files
Use internal storage rather then external for storing applications files
Use content providers wherever possible
Use content providers wherever possible
Use SSl when connecting to the web
Use SSl when connecting to the web
Use appropriate permissions for accessing different functionalities of device
Use appropriate permissions for accessing different functionalities of device
The below example demonstrates some of the best practices you should follow when developing android application. It crates a basic application that allows you to specify how to use text fields and how to increase performance by checking the charging status of the phone.
To experiment with this example , you need to run this on an actual device.
Here is the content of src/MainActivity.java
package com.example.sairamkrishna.myapplication;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
EditText ed1,ed2;
Button b1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ed1=(EditText)findViewById(R.id.editText);
ed2=(EditText)findViewById(R.id.editText2);
b1=(Button)findViewById(R.id.button);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = registerReceiver(null, ifilter);
int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
status == BatteryManager.BATTERY_STATUS_FULL;
int chargePlug = batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED,-1);
boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;
if(usbCharge){
Toast.makeText(getApplicationContext(),"Mobile is charging on USB",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),"Mobile is charging on AC",
Toast.LENGTH_LONG).show();
}
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
}
}
Here is the content of 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:text="Bluetooth Example"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textview"
android:textSize="35dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials point"
android:id="@+id/textView"
android:layout_below="@+id/textview"
android:layout_centerHorizontal="true"
android:textColor="#ff7aff24"
android:textSize="35dp" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:src="@drawable/abc"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:hint="User Name"
android:layout_below="@+id/imageView"
android:layout_alignLeft="@+id/imageView"
android:layout_alignStart="@+id/imageView"
android:numeric="integer" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText2"
android:layout_alignLeft="@+id/editText"
android:layout_alignStart="@+id/editText"
android:hint="Pass Word"
android:layout_below="@+id/editText"
android:layout_alignRight="@+id/editText"
android:layout_alignEnd="@+id/editText"
android:password="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Check"
android:id="@+id/button"
android:layout_below="@+id/editText2"
android:layout_centerHorizontal="true" />
</RelativeLayout>
Here is the content of Strings.xml
<resources>
<string name="app_name">My Application</string>
</resources>
Here is the content of AndroidManifest.xml
<?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="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.sairamkrishna.myapplication.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 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 tool bar. Android Studio will display following Images.
Above image shows an output of application
Now just type on the username field and you will see the built in android suggestions from the dictionary will start coming up. This is shown Above.
Now you will see the password field. It would disappear as soon as you start writing in the field. It is shown above.
In the end , just connect your device to AC cable or USB cable and press on charging check button. In my case , i connect AC power,it shows the following message.
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": 3781,
"s": 3607,
"text": "There are some practices that you can follow while developing android application. These are suggested by the android itself and they keep on improving with respect to time."
},
{
"code": null,
"e": 3980,
"s": 3781,
"text": "These best practices include interaction design features, performance, security and privacy, compatibility, testing, distributing and monetizing tips. They are narrowed down and are listed as below."
},
{
"code": null,
"e": 4215,
"s": 3980,
"text": "Every text field is intended for a different job. For example, some text fields are for text and some are for numbers. If it is for numbers then it is better to display the numeric keypad when that textfield is focused. Its syntax is."
},
{
"code": null,
"e": 4608,
"s": 4215,
"text": "<EditText\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:id=\"@+id/editText\"\n android:layout_alignParentRight=\"true\"\n android:layout_alignParentEnd=\"true\"\n android:hint=\"User Name\"\n android:layout_below=\"@+id/imageView\"\n android:layout_alignLeft=\"@+id/imageView\"\n android:layout_alignStart=\"@+id/imageView\"\n android:numeric=\"integer\" />"
},
{
"code": null,
"e": 4764,
"s": 4608,
"text": "Other then that if your field is for password, then it must show a password hint, so that the user can easily remember the password. It can be achieved as."
},
{
"code": null,
"e": 5159,
"s": 4764,
"text": "<EditText\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:id=\"@+id/editText2\"\n android:layout_alignLeft=\"@+id/editText\"\n android:layout_alignStart=\"@+id/editText\"\n android:hint=\"Pass Word\"\n android:layout_below=\"@+id/editText\"\n android:layout_alignRight=\"@+id/editText\"\n android:layout_alignEnd=\"@+id/editText\"\n android:password=\"true\" />"
},
{
"code": null,
"e": 5465,
"s": 5159,
"text": "There are certain jobs in an application that are running in an application background. Their job might be to fetch some thing from the internet , playing music e.t.c. It is recommended that the long awaiting tasks should not be done in the UI thread and rather in the background by services or AsyncTask."
},
{
"code": null,
"e": 5657,
"s": 5465,
"text": "Both are used for doing background tasks , but the service is not affected by most user interface life cycle events, so it continues to run in circumstances that would shut down an AsyncTask."
},
{
"code": null,
"e": 5903,
"s": 5657,
"text": "Your application performance should be up-to the mark. But it should perform differently not on the front end , but on the back end when it the device is connected to a power source or charging. Charging could be of from USB and from wire cable."
},
{
"code": null,
"e": 6098,
"s": 5903,
"text": "When your device is charging itself , it is recommended to update your application settings if any, such as maximizing your refresh rate whenever the device is connected. It can be done as this."
},
{
"code": null,
"e": 6475,
"s": 6098,
"text": "IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);\nIntent batteryStatus = context.registerReceiver(null, ifilter);\n\n// Are we charging / charged? Full or charging.\nint status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);\n\n// How are we charging? From AC or USB.\nint chargePlug = batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);"
},
{
"code": null,
"e": 6689,
"s": 6475,
"text": "It is very important that your application should be secure and not only the application , but the user data and the application data should also be secured. The security can be increased by the following factors."
},
{
"code": null,
"e": 6762,
"s": 6689,
"text": "Use internal storage rather then external for storing applications files"
},
{
"code": null,
"e": 6835,
"s": 6762,
"text": "Use internal storage rather then external for storing applications files"
},
{
"code": null,
"e": 6875,
"s": 6835,
"text": "Use content providers wherever possible"
},
{
"code": null,
"e": 6915,
"s": 6875,
"text": "Use content providers wherever possible"
},
{
"code": null,
"e": 6950,
"s": 6915,
"text": "Use SSl when connecting to the web"
},
{
"code": null,
"e": 6985,
"s": 6950,
"text": "Use SSl when connecting to the web"
},
{
"code": null,
"e": 7063,
"s": 6985,
"text": "Use appropriate permissions for accessing different functionalities of device"
},
{
"code": null,
"e": 7141,
"s": 7063,
"text": "Use appropriate permissions for accessing different functionalities of device"
},
{
"code": null,
"e": 7412,
"s": 7141,
"text": "The below example demonstrates some of the best practices you should follow when developing android application. It crates a basic application that allows you to specify how to use text fields and how to increase performance by checking the charging status of the phone."
},
{
"code": null,
"e": 7488,
"s": 7412,
"text": "To experiment with this example , you need to run this on an actual device."
},
{
"code": null,
"e": 7533,
"s": 7488,
"text": "Here is the content of src/MainActivity.java"
},
{
"code": null,
"e": 9450,
"s": 7533,
"text": "package com.example.sairamkrishna.myapplication;\n\nimport android.content.Intent;\nimport android.content.IntentFilter;\nimport android.os.BatteryManager;\nimport android.support.v7.app.ActionBarActivity;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.EditText;\nimport android.widget.Toast;\n\npublic class MainActivity extends ActionBarActivity {\n EditText ed1,ed2;\n Button b1;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n\n ed1=(EditText)findViewById(R.id.editText);\n ed2=(EditText)findViewById(R.id.editText2);\n b1=(Button)findViewById(R.id.button);\n\n b1.setOnClickListener(new View.OnClickListener() {\n @Override\n \n public void onClick(View v) {\n IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);\n Intent batteryStatus = registerReceiver(null, ifilter);\n\n int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);\n boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||\n status == BatteryManager.BATTERY_STATUS_FULL;\n\n int chargePlug = batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED,-1);\n boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;\n boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;\n\n if(usbCharge){\n Toast.makeText(getApplicationContext(),\"Mobile is charging on USB\",\n Toast.LENGTH_LONG).show();\n } else {\n Toast.makeText(getApplicationContext(),\"Mobile is charging on AC\",\n Toast.LENGTH_LONG).show();\n }\n }\n });\n }\n\n @Override\n protected void onDestroy() {\n super.onDestroy();\n }\n}"
},
{
"code": null,
"e": 9491,
"s": 9450,
"text": "Here is the content of activity_main.xml"
},
{
"code": null,
"e": 12044,
"s": 9491,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n <RelativeLayout \n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\" \n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:paddingLeft=\"@dimen/activity_horizontal_margin\"\n android:paddingRight=\"@dimen/activity_horizontal_margin\"\n android:paddingTop=\"@dimen/activity_vertical_margin\"\n android:paddingBottom=\"@dimen/activity_vertical_margin\" \n tools:context=\".MainActivity\">\n \n <TextView android:text=\"Bluetooth Example\" \n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:id=\"@+id/textview\"\n android:textSize=\"35dp\"\n android:layout_alignParentTop=\"true\"\n android:layout_centerHorizontal=\"true\" />\n \n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Tutorials point\"\n android:id=\"@+id/textView\"\n android:layout_below=\"@+id/textview\"\n android:layout_centerHorizontal=\"true\"\n android:textColor=\"#ff7aff24\"\n android:textSize=\"35dp\" />\n \n <ImageView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:id=\"@+id/imageView\"\n android:src=\"@drawable/abc\"\n android:layout_below=\"@+id/textView\"\n android:layout_centerHorizontal=\"true\" />\n \n <EditText\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:id=\"@+id/editText\"\n android:layout_alignParentRight=\"true\"\n android:layout_alignParentEnd=\"true\"\n android:hint=\"User Name\"\n android:layout_below=\"@+id/imageView\"\n android:layout_alignLeft=\"@+id/imageView\"\n android:layout_alignStart=\"@+id/imageView\"\n android:numeric=\"integer\" />\n \n <EditText\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:id=\"@+id/editText2\"\n android:layout_alignLeft=\"@+id/editText\"\n android:layout_alignStart=\"@+id/editText\"\n android:hint=\"Pass Word\"\n android:layout_below=\"@+id/editText\"\n android:layout_alignRight=\"@+id/editText\"\n android:layout_alignEnd=\"@+id/editText\"\n android:password=\"true\" />\n \n <Button\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Check\"\n android:id=\"@+id/button\"\n android:layout_below=\"@+id/editText2\"\n android:layout_centerHorizontal=\"true\" />\n \n</RelativeLayout>"
},
{
"code": null,
"e": 12079,
"s": 12044,
"text": "Here is the content of Strings.xml"
},
{
"code": null,
"e": 12156,
"s": 12079,
"text": "<resources>\n <string name=\"app_name\">My Application</string>\n</resources>"
},
{
"code": null,
"e": 12199,
"s": 12156,
"text": "Here is the content of AndroidManifest.xml"
},
{
"code": null,
"e": 12939,
"s": 12199,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"com.example.sairamkrishna.myapplication\" >\n\n <application\n android:allowBackup=\"true\"\n android:icon=\"@drawable/ic_launcher\"\n android:label=\"@string/app_name\"\n android:theme=\"@style/AppTheme\" >\n \n <activity\n android:name=\"com.example.sairamkrishna.myapplication.MainActivity\"\n android:label=\"@string/app_name\" >\n \n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n \n </activity>\n \n </application>\n</manifest>"
},
{
"code": null,
"e": 13220,
"s": 12939,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from Android studio, open one of your project's activity files and click Run icon from the tool bar. Android Studio will display following Images."
},
{
"code": null,
"e": 13263,
"s": 13220,
"text": "Above image shows an output of application"
},
{
"code": null,
"e": 13412,
"s": 13263,
"text": "Now just type on the username field and you will see the built in android suggestions from the dictionary will start coming up. This is shown Above."
},
{
"code": null,
"e": 13530,
"s": 13412,
"text": "Now you will see the password field. It would disappear as soon as you start writing in the field. It is shown above."
},
{
"code": null,
"e": 13693,
"s": 13530,
"text": "In the end , just connect your device to AC cable or USB cable and press on charging check button. In my case , i connect AC power,it shows the following message."
},
{
"code": null,
"e": 13728,
"s": 13693,
"text": "\n 46 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 13740,
"s": 13728,
"text": " Aditya Dua"
},
{
"code": null,
"e": 13775,
"s": 13740,
"text": "\n 32 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 13789,
"s": 13775,
"text": " Sharad Kumar"
},
{
"code": null,
"e": 13821,
"s": 13789,
"text": "\n 9 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 13838,
"s": 13821,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 13873,
"s": 13838,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 13890,
"s": 13873,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 13925,
"s": 13890,
"text": "\n 15 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 13942,
"s": 13925,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 13975,
"s": 13942,
"text": "\n 10 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 13992,
"s": 13975,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 13999,
"s": 13992,
"text": " Print"
},
{
"code": null,
"e": 14010,
"s": 13999,
"text": " Add Notes"
}
]
|
Spring - MVC Framework Overview | The Spring Web MVC framework provides a model-view-controller architecture and ready components that can be used to develop flexible and loosely coupled web applications. The MVC pattern results in separating the different aspects of the application (input logic, business logic, and UI logic), while providing a loose coupling between these elements.
The Model encapsulates the application data and in general, they will consist of POJO.
The Model encapsulates the application data and in general, they will consist of POJO.
The View is responsible for rendering the model data and in general, it generates HTML output that the client's browser can interpret.
The View is responsible for rendering the model data and in general, it generates HTML output that the client's browser can interpret.
The Controller is responsible for processing User Requests and Building Appropriate Model and passes it to the view for rendering.
The Controller is responsible for processing User Requests and Building Appropriate Model and passes it to the view for rendering.
The Spring Web model-view-controller (MVC) framework is designed around a DispatcherServlet that handles all the HTTP requests and responses. The request processing workflow of the Spring Web MVC DispatcherServlet is shown in the following illustration.
Following is the sequence of events corresponding to an incoming HTTP request to DispatcherServlet −
After receiving an HTTP request, DispatcherServlet consults the HandlerMapping to call the appropriate Controller.
After receiving an HTTP request, DispatcherServlet consults the HandlerMapping to call the appropriate Controller.
The Controller takes the request and calls the appropriate service methods based on used GET or POST method. The service method will set model data based on defined business logic and returns view name to the DispatcherServlet.
The Controller takes the request and calls the appropriate service methods based on used GET or POST method. The service method will set model data based on defined business logic and returns view name to the DispatcherServlet.
The DispatcherServlet will take help from ViewResolver to pick up the defined view for the request.
The DispatcherServlet will take help from ViewResolver to pick up the defined view for the request.
Once view is finalized, The DispatcherServlet passes the model data to the view, which is finally rendered, on the browsers.
Once view is finalized, The DispatcherServlet passes the model data to the view, which is finally rendered, on the browsers.
All the above-mentioned components, i.e. HandlerMapping, Controller and ViewResolver are parts of WebApplicationContext, which is an extension of the plain ApplicationContext with some extra features necessary for web applications.
We need to map requests that you want the DispatcherServlet to handle, by using a URL mapping in the web.xml file. The following is an example to show declaration and mapping for HelloWeb DispatcherServlet −
<web-app id = "WebApp_ID" version = "2.4"
xmlns = "http://java.sun.com/xml/ns/j2ee"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Spring MVC Application</display-name>
<servlet>
<servlet-name>HelloWeb</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>HelloWeb</servlet-name>
<url-pattern>*.jsp</url-pattern>
</servlet-mapping>
</web-app>
The web.xml file will be kept in the WebContent/WEB-INF directory of your web application. Upon initialization of the HelloWeb DispatcherServlet, the framework will try to load the application context from a file named [servlet-name]-servlet.xml located in the application's WebContent/WEB-INF directory. In this case, our file will be HelloWeb-servlet.xml.
Next, the <servlet-mapping> tag indicates which URLs will be handled by which DispatcherServlet. Here, all the HTTP requests ending with .jsp will be handled by the HelloWeb DispatcherServlet.
If you do not want to go with the default filename as [servlet-name]-servlet.xml and default location as WebContent/WEB-INF, you can customize this file name and location by adding the servlet listener ContextLoaderListener in your web.xml file as follows −
<web-app...>
<!-------- DispatcherServlet definition goes here----->
....
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/HelloWeb-servlet.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
</web-app>
Now, let us check the required configuration for HelloWeb-servlet.xml file, placed in your web application's WebContent/WEB-INF directory.
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:context = "http://www.springframework.org/schema/context"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package = "com.tutorialspoint" />
<bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name = "prefix" value = "/WEB-INF/jsp/" />
<property name = "suffix" value = ".jsp" />
</bean>
</beans>
Following are some important points about HelloWeb-servlet.xml file −
The [servlet-name]-servlet.xml file will be used to create the beans defined, overriding the definitions of any beans defined with the same name in the global scope.
The [servlet-name]-servlet.xml file will be used to create the beans defined, overriding the definitions of any beans defined with the same name in the global scope.
The <context:component-scan...> tag will be used to activate the Spring MVC annotation scanning capability, which allows to make use of annotations like @Controller and @RequestMapping, etc.
The <context:component-scan...> tag will be used to activate the Spring MVC annotation scanning capability, which allows to make use of annotations like @Controller and @RequestMapping, etc.
The InternalResourceViewResolver will have rules defined to resolve the view names. As per the above-defined rule, a logical view named hello is delegated to a view implementation located at /WEB-INF/jsp/hello.jsp.
The InternalResourceViewResolver will have rules defined to resolve the view names. As per the above-defined rule, a logical view named hello is delegated to a view implementation located at /WEB-INF/jsp/hello.jsp.
Let us now understand how to create the actual components i.e., Controller, Model and View.
The DispatcherServlet delegates the request to the controllers to execute the functionality specific to it. The @Controller annotation indicates that a particular class serves the role of a controller. The @RequestMapping annotation is used to map a URL to either an entire class or a particular handler method.
@Controller
@RequestMapping("/hello")
public class HelloController{
@RequestMapping(method = RequestMethod.GET)
public String printHello(ModelMap model) {
model.addAttribute("message", "Hello Spring MVC Framework!");
return "hello";
}
}
The @Controller annotation defines the class as a Spring MVC controller. Here, the first usage of @RequestMapping indicates that all handling methods on this controller are relative to the /hello path.
The next annotation @RequestMapping (method = RequestMethod.GET) is used to declare the printHello() method as the controller's default service method to handle HTTP GET request. We can define another method to handle any POST request at the same URL.
We can also write the above controller in another form, where we can add additional attributes in the @RequestMapping as follows −
@Controller
public class HelloController{
@RequestMapping(value = "/hello", method = RequestMethod.GET)
public String printHello(ModelMap model) {
model.addAttribute("message", "Hello Spring MVC Framework!");
return "hello";
}
}
The value attribute indicates the URL to which the handler method is mapped and the method attribute defines the service method to handle the HTTP GET request.
Following are some important points to be noted regarding the controller defined above −
You will define the required business logic inside a service method. You can call another method inside this method as per the requirement.
You will define the required business logic inside a service method. You can call another method inside this method as per the requirement.
Based on the business logic defined, you will create a model within this method. You can set different model attributes and these attributes will be accessed by the view to present the result. This example creates a model with its attribute "message".
Based on the business logic defined, you will create a model within this method. You can set different model attributes and these attributes will be accessed by the view to present the result. This example creates a model with its attribute "message".
A defined service method can return a String, which contains the name of the view to be used to render the model. This example returns "hello" as the logical view name.
A defined service method can return a String, which contains the name of the view to be used to render the model. This example returns "hello" as the logical view name.
Spring MVC supports many types of views for different presentation technologies. These include - JSPs, HTML, PDF, Excel Worksheets, XML, Velocity Templates, XSLT, JSON, Atom and RSS feeds, JasperReports, etc. However, the most common ones are the JSP templates written with JSTL. So, let us write a simple hello view in /WEB-INF/hello/hello.jsp −
<html>
<head>
<title>Hello Spring MVC</title>
</head>
<body>
<h2>${message}</h2>
</body>
</html>
Here ${message} Here is the attribute, which we have setup inside the Controller. You can have multiple attributes to be displayed inside your view.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 3143,
"s": 2791,
"text": "The Spring Web MVC framework provides a model-view-controller architecture and ready components that can be used to develop flexible and loosely coupled web applications. The MVC pattern results in separating the different aspects of the application (input logic, business logic, and UI logic), while providing a loose coupling between these elements."
},
{
"code": null,
"e": 3230,
"s": 3143,
"text": "The Model encapsulates the application data and in general, they will consist of POJO."
},
{
"code": null,
"e": 3317,
"s": 3230,
"text": "The Model encapsulates the application data and in general, they will consist of POJO."
},
{
"code": null,
"e": 3453,
"s": 3317,
"text": "The View is responsible for rendering the model data and in general, it generates HTML output that the client's browser can interpret."
},
{
"code": null,
"e": 3589,
"s": 3453,
"text": "The View is responsible for rendering the model data and in general, it generates HTML output that the client's browser can interpret."
},
{
"code": null,
"e": 3720,
"s": 3589,
"text": "The Controller is responsible for processing User Requests and Building Appropriate Model and passes it to the view for rendering."
},
{
"code": null,
"e": 3851,
"s": 3720,
"text": "The Controller is responsible for processing User Requests and Building Appropriate Model and passes it to the view for rendering."
},
{
"code": null,
"e": 4105,
"s": 3851,
"text": "The Spring Web model-view-controller (MVC) framework is designed around a DispatcherServlet that handles all the HTTP requests and responses. The request processing workflow of the Spring Web MVC DispatcherServlet is shown in the following illustration."
},
{
"code": null,
"e": 4206,
"s": 4105,
"text": "Following is the sequence of events corresponding to an incoming HTTP request to DispatcherServlet −"
},
{
"code": null,
"e": 4321,
"s": 4206,
"text": "After receiving an HTTP request, DispatcherServlet consults the HandlerMapping to call the appropriate Controller."
},
{
"code": null,
"e": 4436,
"s": 4321,
"text": "After receiving an HTTP request, DispatcherServlet consults the HandlerMapping to call the appropriate Controller."
},
{
"code": null,
"e": 4664,
"s": 4436,
"text": "The Controller takes the request and calls the appropriate service methods based on used GET or POST method. The service method will set model data based on defined business logic and returns view name to the DispatcherServlet."
},
{
"code": null,
"e": 4892,
"s": 4664,
"text": "The Controller takes the request and calls the appropriate service methods based on used GET or POST method. The service method will set model data based on defined business logic and returns view name to the DispatcherServlet."
},
{
"code": null,
"e": 4992,
"s": 4892,
"text": "The DispatcherServlet will take help from ViewResolver to pick up the defined view for the request."
},
{
"code": null,
"e": 5092,
"s": 4992,
"text": "The DispatcherServlet will take help from ViewResolver to pick up the defined view for the request."
},
{
"code": null,
"e": 5217,
"s": 5092,
"text": "Once view is finalized, The DispatcherServlet passes the model data to the view, which is finally rendered, on the browsers."
},
{
"code": null,
"e": 5342,
"s": 5217,
"text": "Once view is finalized, The DispatcherServlet passes the model data to the view, which is finally rendered, on the browsers."
},
{
"code": null,
"e": 5574,
"s": 5342,
"text": "All the above-mentioned components, i.e. HandlerMapping, Controller and ViewResolver are parts of WebApplicationContext, which is an extension of the plain ApplicationContext with some extra features necessary for web applications."
},
{
"code": null,
"e": 5782,
"s": 5574,
"text": "We need to map requests that you want the DispatcherServlet to handle, by using a URL mapping in the web.xml file. The following is an example to show declaration and mapping for HelloWeb DispatcherServlet −"
},
{
"code": null,
"e": 6454,
"s": 5782,
"text": "<web-app id = \"WebApp_ID\" version = \"2.4\"\n xmlns = \"http://java.sun.com/xml/ns/j2ee\" \n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://java.sun.com/xml/ns/j2ee \n http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd\">\n \n <display-name>Spring MVC Application</display-name>\n\n <servlet>\n <servlet-name>HelloWeb</servlet-name>\n <servlet-class>\n org.springframework.web.servlet.DispatcherServlet\n </servlet-class>\n <load-on-startup>1</load-on-startup>\n </servlet>\n\n <servlet-mapping>\n <servlet-name>HelloWeb</servlet-name>\n <url-pattern>*.jsp</url-pattern>\n </servlet-mapping>\n</web-app>"
},
{
"code": null,
"e": 6812,
"s": 6454,
"text": "The web.xml file will be kept in the WebContent/WEB-INF directory of your web application. Upon initialization of the HelloWeb DispatcherServlet, the framework will try to load the application context from a file named [servlet-name]-servlet.xml located in the application's WebContent/WEB-INF directory. In this case, our file will be HelloWeb-servlet.xml."
},
{
"code": null,
"e": 7005,
"s": 6812,
"text": "Next, the <servlet-mapping> tag indicates which URLs will be handled by which DispatcherServlet. Here, all the HTTP requests ending with .jsp will be handled by the HelloWeb DispatcherServlet."
},
{
"code": null,
"e": 7263,
"s": 7005,
"text": "If you do not want to go with the default filename as [servlet-name]-servlet.xml and default location as WebContent/WEB-INF, you can customize this file name and location by adding the servlet listener ContextLoaderListener in your web.xml file as follows −"
},
{
"code": null,
"e": 7650,
"s": 7263,
"text": "<web-app...>\n\n <!-------- DispatcherServlet definition goes here----->\n ....\n <context-param>\n <param-name>contextConfigLocation</param-name>\n <param-value>/WEB-INF/HelloWeb-servlet.xml</param-value>\n </context-param>\n\n <listener>\n <listener-class>\n org.springframework.web.context.ContextLoaderListener\n </listener-class>\n </listener>\n</web-app>"
},
{
"code": null,
"e": 7789,
"s": 7650,
"text": "Now, let us check the required configuration for HelloWeb-servlet.xml file, placed in your web application's WebContent/WEB-INF directory."
},
{
"code": null,
"e": 8530,
"s": 7789,
"text": "<beans xmlns = \"http://www.springframework.org/schema/beans\"\n xmlns:context = \"http://www.springframework.org/schema/context\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"\n http://www.springframework.org/schema/beans \n http://www.springframework.org/schema/beans/spring-beans-3.0.xsd\n http://www.springframework.org/schema/context \n http://www.springframework.org/schema/context/spring-context-3.0.xsd\">\n\n <context:component-scan base-package = \"com.tutorialspoint\" />\n\n <bean class = \"org.springframework.web.servlet.view.InternalResourceViewResolver\">\n <property name = \"prefix\" value = \"/WEB-INF/jsp/\" />\n <property name = \"suffix\" value = \".jsp\" />\n </bean>\n\n</beans>"
},
{
"code": null,
"e": 8600,
"s": 8530,
"text": "Following are some important points about HelloWeb-servlet.xml file −"
},
{
"code": null,
"e": 8766,
"s": 8600,
"text": "The [servlet-name]-servlet.xml file will be used to create the beans defined, overriding the definitions of any beans defined with the same name in the global scope."
},
{
"code": null,
"e": 8932,
"s": 8766,
"text": "The [servlet-name]-servlet.xml file will be used to create the beans defined, overriding the definitions of any beans defined with the same name in the global scope."
},
{
"code": null,
"e": 9123,
"s": 8932,
"text": "The <context:component-scan...> tag will be used to activate the Spring MVC annotation scanning capability, which allows to make use of annotations like @Controller and @RequestMapping, etc."
},
{
"code": null,
"e": 9314,
"s": 9123,
"text": "The <context:component-scan...> tag will be used to activate the Spring MVC annotation scanning capability, which allows to make use of annotations like @Controller and @RequestMapping, etc."
},
{
"code": null,
"e": 9529,
"s": 9314,
"text": "The InternalResourceViewResolver will have rules defined to resolve the view names. As per the above-defined rule, a logical view named hello is delegated to a view implementation located at /WEB-INF/jsp/hello.jsp."
},
{
"code": null,
"e": 9744,
"s": 9529,
"text": "The InternalResourceViewResolver will have rules defined to resolve the view names. As per the above-defined rule, a logical view named hello is delegated to a view implementation located at /WEB-INF/jsp/hello.jsp."
},
{
"code": null,
"e": 9836,
"s": 9744,
"text": "Let us now understand how to create the actual components i.e., Controller, Model and View."
},
{
"code": null,
"e": 10148,
"s": 9836,
"text": "The DispatcherServlet delegates the request to the controllers to execute the functionality specific to it. The @Controller annotation indicates that a particular class serves the role of a controller. The @RequestMapping annotation is used to map a URL to either an entire class or a particular handler method."
},
{
"code": null,
"e": 10409,
"s": 10148,
"text": "@Controller\n@RequestMapping(\"/hello\")\npublic class HelloController{\n \n @RequestMapping(method = RequestMethod.GET)\n public String printHello(ModelMap model) {\n model.addAttribute(\"message\", \"Hello Spring MVC Framework!\");\n return \"hello\";\n }\n\n}"
},
{
"code": null,
"e": 10611,
"s": 10409,
"text": "The @Controller annotation defines the class as a Spring MVC controller. Here, the first usage of @RequestMapping indicates that all handling methods on this controller are relative to the /hello path."
},
{
"code": null,
"e": 10863,
"s": 10611,
"text": "The next annotation @RequestMapping (method = RequestMethod.GET) is used to declare the printHello() method as the controller's default service method to handle HTTP GET request. We can define another method to handle any POST request at the same URL."
},
{
"code": null,
"e": 10994,
"s": 10863,
"text": "We can also write the above controller in another form, where we can add additional attributes in the @RequestMapping as follows −"
},
{
"code": null,
"e": 11247,
"s": 10994,
"text": "@Controller\npublic class HelloController{\n \n @RequestMapping(value = \"/hello\", method = RequestMethod.GET)\n public String printHello(ModelMap model) {\n model.addAttribute(\"message\", \"Hello Spring MVC Framework!\");\n return \"hello\";\n }\n\n}"
},
{
"code": null,
"e": 11407,
"s": 11247,
"text": "The value attribute indicates the URL to which the handler method is mapped and the method attribute defines the service method to handle the HTTP GET request."
},
{
"code": null,
"e": 11496,
"s": 11407,
"text": "Following are some important points to be noted regarding the controller defined above −"
},
{
"code": null,
"e": 11636,
"s": 11496,
"text": "You will define the required business logic inside a service method. You can call another method inside this method as per the requirement."
},
{
"code": null,
"e": 11776,
"s": 11636,
"text": "You will define the required business logic inside a service method. You can call another method inside this method as per the requirement."
},
{
"code": null,
"e": 12028,
"s": 11776,
"text": "Based on the business logic defined, you will create a model within this method. You can set different model attributes and these attributes will be accessed by the view to present the result. This example creates a model with its attribute \"message\"."
},
{
"code": null,
"e": 12280,
"s": 12028,
"text": "Based on the business logic defined, you will create a model within this method. You can set different model attributes and these attributes will be accessed by the view to present the result. This example creates a model with its attribute \"message\"."
},
{
"code": null,
"e": 12449,
"s": 12280,
"text": "A defined service method can return a String, which contains the name of the view to be used to render the model. This example returns \"hello\" as the logical view name."
},
{
"code": null,
"e": 12618,
"s": 12449,
"text": "A defined service method can return a String, which contains the name of the view to be used to render the model. This example returns \"hello\" as the logical view name."
},
{
"code": null,
"e": 12965,
"s": 12618,
"text": "Spring MVC supports many types of views for different presentation technologies. These include - JSPs, HTML, PDF, Excel Worksheets, XML, Velocity Templates, XSLT, JSON, Atom and RSS feeds, JasperReports, etc. However, the most common ones are the JSP templates written with JSTL. So, let us write a simple hello view in /WEB-INF/hello/hello.jsp −"
},
{
"code": null,
"e": 13086,
"s": 12965,
"text": "<html>\n <head>\n <title>Hello Spring MVC</title>\n </head>\n <body>\n <h2>${message}</h2>\n </body>\n</html>"
},
{
"code": null,
"e": 13235,
"s": 13086,
"text": "Here ${message} Here is the attribute, which we have setup inside the Controller. You can have multiple attributes to be displayed inside your view."
},
{
"code": null,
"e": 13242,
"s": 13235,
"text": " Print"
},
{
"code": null,
"e": 13253,
"s": 13242,
"text": " Add Notes"
}
]
|
Visualizing NYC Bike Share Trips with a Chord Diagram | by Clif Kranish | Towards Data Science | The New York City bike share system Citi Bike provides trip data files that allow anyone to analyze the use of the system. Chord diagrams provide a way to visualize flows between entities. In this article I will show that once you have the data in the required format it is easy to create an interactive chord diagram that helps to understand how these shared bikes are used.
The diagram above was created using the Holoviews Chord element. If you are using Anaconda you can install the Holoviews library with the command:
conda install holoviews
For this article I’m also using Jupyter Notebook, Pandas, Seaborn, and Pyarrow. See my previous article Exploring NYC Bike Share Data for instructions on how to install these libraries.
All of the Python code used in this article and the output it generates can be found on GitHub in the Jupyter Notebook chords.ipynb.
The Citi Bike System Data page describes the information provided and has a link to a page where you can download the data. For this article I’m using data from September 2020. From Windows find the NYC file for 202009, download it and unzip it to a bikeshare directory. On Linux issue these commands:
mkdir bikeshare && cd bikeshare wget https://s3.amazonaws.com/tripdata/202009-citibike-tripdata.csv.zipunzip 202009-citibike-tripdata.csv.ziprm 2020009-citibike-tripdata.csv.zip
Citi Bike is a traditional system with fixed stations where users pick up and drop off the shared bikes. Each record in the trip data files is a single trip and has a starting and ending station name and ID. However the only geographical data included is latitude and longitude.
In order to make sense of the trip data I created a file with the borough, neighborhood, and zip code for each station. (In New York City a borough is an administrative unit. While there are five, the four with Citi Bike stations are Manhattan, Brooklyn, Queens and the Bronx).
You can download the file from 202009-stations.parquet. On Linux issue the command:
wget https://github.com/ckran/bikeshare/raw/main/202009-stations.parquet
To read a Parquet file from Python install pyarrow. If you are using conda you can install with:
conda install -c conda-forge pyarrow
This file was created using data from OpenStreetMaps. If you want to see how, read my article Reverse Geocoding with NYC Bike Share Data.
Start Jupyter and create a new notebook in your bikeshare directory. Enter each block of code into a cell and run it.
Import these libraries and set options as shown:
import pandas as pdimport seaborn as snsimport matplotlib.pyplot as pltfrom holoviews import opts, dimimport holoviews as hvhv.extension('bokeh')hv.output(size=200)
Then read the Citi Bike trip data file. These files have one record for each trip, and include information about the ride (trip duration, station names and geographical coordinates) and the rider (birth year, gender, user type). If I wanted to analyze trips by time or day, or by type of rider, I would read the entire file. However for this analysis I just need to count the number of rides by starting and ending location so all I need is the start station id and end station id.
dfa = pd.read_csv('202009-citibike-tripdata.csv',\ usecols=['start station id','end station id'])dfa.shape
The output shows the number of rows (rides) and columns. There were almost 21⁄2 million rides this month!
(2488225, 2)
Then read the stations file into a DataFrame and look at the first ten rows.
dfstations=pd.read_parquet('202009-stations.parquet')dfstations.head(10)
Then we can join the tripdata table (with start and end station IDs) to the stations table (on the station ID) using the Pandas merge function. We’ll do this twice, once for start stations and once for end stations.
dfa = pd.merge(dfa, dfstations[['boro','neighborhood','zipcode']],\ how = 'left', left_on='start station id', right_on='stationid')dfa = pd.merge(dfa, dfstations[['boro','neighborhood','zipcode']],\ how = 'left', left_on='end station id', right_on='stationid')dfa.head(10)
Note in the output below two columns were created for each attribute. For example boro_x for the starting location and boro_y for the ending location.
Now I need to put the data into the format required by the Holoviews Chord diagram, while limiting the data to only trips that start and end in Manhattan. For this analysis I’m using the starting and ending neighborhood, but I could also use zip code for more detailed analysis if I restricted the data further. The use of value_counts() returns a sorted list of the count of rides between neighborhoods.
trips=dfa[['neighborhood_x','neighborhood_y']]\.loc[((dfa['boro_x']=='Manhattan')&(dfa['boro_y']=='Manhattan'))]\.value_counts()trips.head()
Now I need to format the data in a three column Pandas DataFrame. I’ll call the columns start , end and trips.
links=pd.DataFrame.from_records(list(trips.index),\columns=['start','end']) links['trips']=trips.valueslinks.head(10)
This data can be easily viewed in a bar chat. First I’ll create a list names combining the start and end neighborhood names, then plot the trips.
names = links.start + '/' + links.endplt.figure(figsize=(12,10))sns.barplot( x=links.trips[:60], y=names[:60], orient="h") ; ;
We see a classic “long tail” here; I limited the chart to the first 60 of the start/end pairs.
I can easily see that the second most popular trips are those that start and end in Chelsea. But what about the trips that start or end in Chelsea? I’d have to read the labels on the chart to find them. If I just wanted to see the trip counts I could see them by pivoting the data.
pd.pivot_table(links,index='start',values='trips',columns='end')
But what if I want to see a graphical representation of this data?
This is where a chord diagram comes in. It easily lets me create a single chart that shows the start and end stations.
But if I try to use the entire table I get an incomprehensible cats cradle of chords, it’s literally too much information.
So I’m going to limit this diagram to the sixty pairs with the most rides. The options here set the colors for the edges and nodes.
chord=hv.Chord(links[:60])chord.opts(node_color='index', edge_color='start',\label_index='index',cmap='Category10', edge_cmap='Category10' )
Here I can clearly see the amount of Citi Bike usage between the most popular neighborhoods.
In Jupyter this diagram is automatically enabled for exploration. So when I hover over the node for Chelsea, the trips starting there are highlighted in green and I can see their destinations around the circle.
And if I click on a node the rest of the diagram is dimmed so that I can see the volume of trips starting and ending at the selected locate. Here I see that most trips that start in Chelsea also end there, and those that don’t mostly go to adjacent neighborhoods.
And what if I don’t want to go to Chelsea? I just click on a different node.
When you are exploring data that includes flows between entities such as docking stations in a bike share system, a chord diagram is a great way to visualize data and one that leads to further exploration. | [
{
"code": null,
"e": 548,
"s": 172,
"text": "The New York City bike share system Citi Bike provides trip data files that allow anyone to analyze the use of the system. Chord diagrams provide a way to visualize flows between entities. In this article I will show that once you have the data in the required format it is easy to create an interactive chord diagram that helps to understand how these shared bikes are used."
},
{
"code": null,
"e": 695,
"s": 548,
"text": "The diagram above was created using the Holoviews Chord element. If you are using Anaconda you can install the Holoviews library with the command:"
},
{
"code": null,
"e": 719,
"s": 695,
"text": "conda install holoviews"
},
{
"code": null,
"e": 905,
"s": 719,
"text": "For this article I’m also using Jupyter Notebook, Pandas, Seaborn, and Pyarrow. See my previous article Exploring NYC Bike Share Data for instructions on how to install these libraries."
},
{
"code": null,
"e": 1038,
"s": 905,
"text": "All of the Python code used in this article and the output it generates can be found on GitHub in the Jupyter Notebook chords.ipynb."
},
{
"code": null,
"e": 1340,
"s": 1038,
"text": "The Citi Bike System Data page describes the information provided and has a link to a page where you can download the data. For this article I’m using data from September 2020. From Windows find the NYC file for 202009, download it and unzip it to a bikeshare directory. On Linux issue these commands:"
},
{
"code": null,
"e": 1518,
"s": 1340,
"text": "mkdir bikeshare && cd bikeshare wget https://s3.amazonaws.com/tripdata/202009-citibike-tripdata.csv.zipunzip 202009-citibike-tripdata.csv.ziprm 2020009-citibike-tripdata.csv.zip"
},
{
"code": null,
"e": 1797,
"s": 1518,
"text": "Citi Bike is a traditional system with fixed stations where users pick up and drop off the shared bikes. Each record in the trip data files is a single trip and has a starting and ending station name and ID. However the only geographical data included is latitude and longitude."
},
{
"code": null,
"e": 2075,
"s": 1797,
"text": "In order to make sense of the trip data I created a file with the borough, neighborhood, and zip code for each station. (In New York City a borough is an administrative unit. While there are five, the four with Citi Bike stations are Manhattan, Brooklyn, Queens and the Bronx)."
},
{
"code": null,
"e": 2159,
"s": 2075,
"text": "You can download the file from 202009-stations.parquet. On Linux issue the command:"
},
{
"code": null,
"e": 2232,
"s": 2159,
"text": "wget https://github.com/ckran/bikeshare/raw/main/202009-stations.parquet"
},
{
"code": null,
"e": 2329,
"s": 2232,
"text": "To read a Parquet file from Python install pyarrow. If you are using conda you can install with:"
},
{
"code": null,
"e": 2366,
"s": 2329,
"text": "conda install -c conda-forge pyarrow"
},
{
"code": null,
"e": 2504,
"s": 2366,
"text": "This file was created using data from OpenStreetMaps. If you want to see how, read my article Reverse Geocoding with NYC Bike Share Data."
},
{
"code": null,
"e": 2622,
"s": 2504,
"text": "Start Jupyter and create a new notebook in your bikeshare directory. Enter each block of code into a cell and run it."
},
{
"code": null,
"e": 2671,
"s": 2622,
"text": "Import these libraries and set options as shown:"
},
{
"code": null,
"e": 2836,
"s": 2671,
"text": "import pandas as pdimport seaborn as snsimport matplotlib.pyplot as pltfrom holoviews import opts, dimimport holoviews as hvhv.extension('bokeh')hv.output(size=200)"
},
{
"code": null,
"e": 3318,
"s": 2836,
"text": "Then read the Citi Bike trip data file. These files have one record for each trip, and include information about the ride (trip duration, station names and geographical coordinates) and the rider (birth year, gender, user type). If I wanted to analyze trips by time or day, or by type of rider, I would read the entire file. However for this analysis I just need to count the number of rides by starting and ending location so all I need is the start station id and end station id."
},
{
"code": null,
"e": 3425,
"s": 3318,
"text": "dfa = pd.read_csv('202009-citibike-tripdata.csv',\\ usecols=['start station id','end station id'])dfa.shape"
},
{
"code": null,
"e": 3531,
"s": 3425,
"text": "The output shows the number of rows (rides) and columns. There were almost 21⁄2 million rides this month!"
},
{
"code": null,
"e": 3544,
"s": 3531,
"text": "(2488225, 2)"
},
{
"code": null,
"e": 3621,
"s": 3544,
"text": "Then read the stations file into a DataFrame and look at the first ten rows."
},
{
"code": null,
"e": 3694,
"s": 3621,
"text": "dfstations=pd.read_parquet('202009-stations.parquet')dfstations.head(10)"
},
{
"code": null,
"e": 3910,
"s": 3694,
"text": "Then we can join the tripdata table (with start and end station IDs) to the stations table (on the station ID) using the Pandas merge function. We’ll do this twice, once for start stations and once for end stations."
},
{
"code": null,
"e": 4183,
"s": 3910,
"text": "dfa = pd.merge(dfa, dfstations[['boro','neighborhood','zipcode']],\\ how = 'left', left_on='start station id', right_on='stationid')dfa = pd.merge(dfa, dfstations[['boro','neighborhood','zipcode']],\\ how = 'left', left_on='end station id', right_on='stationid')dfa.head(10)"
},
{
"code": null,
"e": 4334,
"s": 4183,
"text": "Note in the output below two columns were created for each attribute. For example boro_x for the starting location and boro_y for the ending location."
},
{
"code": null,
"e": 4739,
"s": 4334,
"text": "Now I need to put the data into the format required by the Holoviews Chord diagram, while limiting the data to only trips that start and end in Manhattan. For this analysis I’m using the starting and ending neighborhood, but I could also use zip code for more detailed analysis if I restricted the data further. The use of value_counts() returns a sorted list of the count of rides between neighborhoods."
},
{
"code": null,
"e": 4880,
"s": 4739,
"text": "trips=dfa[['neighborhood_x','neighborhood_y']]\\.loc[((dfa['boro_x']=='Manhattan')&(dfa['boro_y']=='Manhattan'))]\\.value_counts()trips.head()"
},
{
"code": null,
"e": 4991,
"s": 4880,
"text": "Now I need to format the data in a three column Pandas DataFrame. I’ll call the columns start , end and trips."
},
{
"code": null,
"e": 5109,
"s": 4991,
"text": "links=pd.DataFrame.from_records(list(trips.index),\\columns=['start','end']) links['trips']=trips.valueslinks.head(10)"
},
{
"code": null,
"e": 5255,
"s": 5109,
"text": "This data can be easily viewed in a bar chat. First I’ll create a list names combining the start and end neighborhood names, then plot the trips."
},
{
"code": null,
"e": 5382,
"s": 5255,
"text": "names = links.start + '/' + links.endplt.figure(figsize=(12,10))sns.barplot( x=links.trips[:60], y=names[:60], orient=\"h\") ; ;"
},
{
"code": null,
"e": 5477,
"s": 5382,
"text": "We see a classic “long tail” here; I limited the chart to the first 60 of the start/end pairs."
},
{
"code": null,
"e": 5759,
"s": 5477,
"text": "I can easily see that the second most popular trips are those that start and end in Chelsea. But what about the trips that start or end in Chelsea? I’d have to read the labels on the chart to find them. If I just wanted to see the trip counts I could see them by pivoting the data."
},
{
"code": null,
"e": 5824,
"s": 5759,
"text": "pd.pivot_table(links,index='start',values='trips',columns='end')"
},
{
"code": null,
"e": 5891,
"s": 5824,
"text": "But what if I want to see a graphical representation of this data?"
},
{
"code": null,
"e": 6010,
"s": 5891,
"text": "This is where a chord diagram comes in. It easily lets me create a single chart that shows the start and end stations."
},
{
"code": null,
"e": 6133,
"s": 6010,
"text": "But if I try to use the entire table I get an incomprehensible cats cradle of chords, it’s literally too much information."
},
{
"code": null,
"e": 6265,
"s": 6133,
"text": "So I’m going to limit this diagram to the sixty pairs with the most rides. The options here set the colors for the edges and nodes."
},
{
"code": null,
"e": 6406,
"s": 6265,
"text": "chord=hv.Chord(links[:60])chord.opts(node_color='index', edge_color='start',\\label_index='index',cmap='Category10', edge_cmap='Category10' )"
},
{
"code": null,
"e": 6499,
"s": 6406,
"text": "Here I can clearly see the amount of Citi Bike usage between the most popular neighborhoods."
},
{
"code": null,
"e": 6710,
"s": 6499,
"text": "In Jupyter this diagram is automatically enabled for exploration. So when I hover over the node for Chelsea, the trips starting there are highlighted in green and I can see their destinations around the circle."
},
{
"code": null,
"e": 6974,
"s": 6710,
"text": "And if I click on a node the rest of the diagram is dimmed so that I can see the volume of trips starting and ending at the selected locate. Here I see that most trips that start in Chelsea also end there, and those that don’t mostly go to adjacent neighborhoods."
},
{
"code": null,
"e": 7051,
"s": 6974,
"text": "And what if I don’t want to go to Chelsea? I just click on a different node."
}
]
|
Print the matrix diagonally downwards in C Program. | Given with an array of size n x n and the task is to print the matrix elements of integer type diagonally downwards.
Diagonally downwards means printing the array of any size of n x n in diagonally moving downward like in the figure given below −
Firstly it will print 1 and then move to 2 print it and moves down to 4 diagonally and print it and so on.
Input: Matrix [3][3] = {
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 }}
Output: 1 2 4 3 5 7 6 8 9
int diagonally_down(int mat[n][n])
START
STEP 1: DECLARE i, j, row, col AS INT
STEP 2: LOOP FOR i = 0 AND i < n AND i++
SET row = 0
SET col = i
LOOP WHILE col >= 0
PRINT mat[row][col]
INCREMENT row BY 1 AND DECREMENT col BY 1
END WHILE
END FOR
STEP 3: LOOP FOR j = 1 AND j < n AND j++
SET row = j
SET col = n-1
LOOP WHILE row < n
PRINT mat[row][col]
INCREMENT row BY 1 AND DECREMENT col BY 1
END WHILE
END FOR
STOP
#include <stdio.h>
#define n 3
int diagonally_down(int mat[n][n]){
int i, j, row, col;
//printing above elements
for (i = 0; i < n; i++){
row = 0;
col = i;
while(col >= 0) //Moving downwards from the first row{
printf("%d ", mat[row++][col--]);
}
}
//printing below elements
for (j = 1; j < n; j++){
row = j;
col = n-1;
while(row<n) //Moving from the last column{
printf("%d ", mat[row++][col--]);
}
}
}
int main(int argc, char const *argv[]){
int mat[][n] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
diagonally_down(mat);
return 0;
}
If we run above program then it will generate following output −
1 2 4 3 5 7 6 8 9 | [
{
"code": null,
"e": 1179,
"s": 1062,
"text": "Given with an array of size n x n and the task is to print the matrix elements of integer type diagonally downwards."
},
{
"code": null,
"e": 1309,
"s": 1179,
"text": "Diagonally downwards means printing the array of any size of n x n in diagonally moving downward like in the figure given below −"
},
{
"code": null,
"e": 1416,
"s": 1309,
"text": "Firstly it will print 1 and then move to 2 print it and moves down to 4 diagonally and print it and so on."
},
{
"code": null,
"e": 1515,
"s": 1416,
"text": "Input: Matrix [3][3] = {\n { 1, 2, 3 },\n { 4, 5, 6 },\n { 7, 8, 9 }}\nOutput: 1 2 4 3 5 7 6 8 9"
},
{
"code": null,
"e": 1978,
"s": 1515,
"text": "int diagonally_down(int mat[n][n])\nSTART\nSTEP 1: DECLARE i, j, row, col AS INT\nSTEP 2: LOOP FOR i = 0 AND i < n AND i++\n SET row = 0\n SET col = i\n LOOP WHILE col >= 0\n PRINT mat[row][col]\n INCREMENT row BY 1 AND DECREMENT col BY 1\n END WHILE\nEND FOR\nSTEP 3: LOOP FOR j = 1 AND j < n AND j++\n SET row = j\n SET col = n-1\n LOOP WHILE row < n\n PRINT mat[row][col]\n INCREMENT row BY 1 AND DECREMENT col BY 1\n END WHILE\nEND FOR\nSTOP"
},
{
"code": null,
"e": 2625,
"s": 1978,
"text": "#include <stdio.h>\n#define n 3\nint diagonally_down(int mat[n][n]){\n int i, j, row, col;\n //printing above elements\n for (i = 0; i < n; i++){\n row = 0;\n col = i;\n while(col >= 0) //Moving downwards from the first row{\n printf(\"%d \", mat[row++][col--]);\n }\n }\n //printing below elements\n for (j = 1; j < n; j++){\n row = j;\n col = n-1;\n while(row<n) //Moving from the last column{\n printf(\"%d \", mat[row++][col--]);\n }\n }\n}\nint main(int argc, char const *argv[]){\n int mat[][n] = {\n {1, 2, 3},\n {4, 5, 6},\n {7, 8, 9}\n };\n diagonally_down(mat);\n return 0;\n}"
},
{
"code": null,
"e": 2690,
"s": 2625,
"text": "If we run above program then it will generate following output −"
},
{
"code": null,
"e": 2708,
"s": 2690,
"text": "1 2 4 3 5 7 6 8 9"
}
]
|
How do I declare global variables on Android? | This example demonstrates how to declare global variables 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"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:gravity = "center"
android:orientation="vertical">
<TextView
android:id = "@+id/tvEvent"
android:textSize = "40sp"
android:layout_marginTop = "30dp"
android:layout_width = "wrap_content"
android:layout_height = "match_parent" />
</LinearLayout>
Step 3 − Add the following code to src/MainActivity.java
package com.example.sample;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView tvEvent;
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvEvent = findViewById(R.id.tvEvent);
tvEvent.setText("Click");
tvEvent.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
singleToneClass singleToneClass = com.example.sample.singleToneClass.getInstance();
singleToneClass.setData("this is sample");
tvEvent.setText(singleToneClass.getData());
}
});
}
}
Step 4 − Create a class called singToneClass and Add the following code to src/SingleToneClass.java
package com.example.sample;
public class singleToneClass {
String s;
private static final singleToneClass ourInstance = new singleToneClass();
public static singleToneClass getInstance() {
return ourInstance;
}
private singleToneClass() {
}
public void setData(String s) {
this.s = s;
}
public String getData() {
return s;
}
}
Step 5 – Add the following code to app/manifests/AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.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 android studio, open one of your project's activity files and click Run Icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen – | [
{
"code": null,
"e": 1132,
"s": 1062,
"text": "This example demonstrates how to declare global variables in Android."
},
{
"code": null,
"e": 1262,
"s": 1132,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1328,
"s": 1262,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1949,
"s": 1328,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\"\n android:gravity = \"center\"\n android:orientation=\"vertical\">\n <TextView\n android:id = \"@+id/tvEvent\"\n android:textSize = \"40sp\"\n android:layout_marginTop = \"30dp\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"match_parent\" />\n</LinearLayout>"
},
{
"code": null,
"e": 2007,
"s": 1949,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 2955,
"s": 2007,
"text": "package com.example.sample;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.support.annotation.RequiresApi;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.widget.TextView;\npublic class MainActivity extends AppCompatActivity {\n TextView tvEvent;\n @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n tvEvent = findViewById(R.id.tvEvent);\n tvEvent.setText(\"Click\");\n tvEvent.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n singleToneClass singleToneClass = com.example.sample.singleToneClass.getInstance();\n singleToneClass.setData(\"this is sample\");\n tvEvent.setText(singleToneClass.getData());\n }\n });\n }\n}"
},
{
"code": null,
"e": 3056,
"s": 2955,
"text": "Step 4 − Create a class called singToneClass and Add the following code to src/SingleToneClass.java"
},
{
"code": null,
"e": 3431,
"s": 3056,
"text": "package com.example.sample;\npublic class singleToneClass {\n String s;\n private static final singleToneClass ourInstance = new singleToneClass();\n public static singleToneClass getInstance() {\n return ourInstance;\n }\n private singleToneClass() {\n }\n public void setData(String s) {\n this.s = s;\n }\n public String getData() {\n return s;\n }\n}"
},
{
"code": null,
"e": 3501,
"s": 3431,
"text": "Step 5 – Add the following code to app/manifests/AndroidManifest.xml"
},
{
"code": null,
"e": 4179,
"s": 3501,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"com.example.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>\n"
},
{
"code": null,
"e": 4526,
"s": 4179,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run Icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –"
}
]
|
Count of seats booked on each of the given N flights - GeeksforGeeks | 23 Jul, 2021
Given an integer N denoting the number of flights and array bookings[][3] with each row of the form {a, b, K} denoting that there are K seats booked from flight a to flight b ( consider 1-based indexing), the task is to find the sequence of the number of seats booked in N flights.
Examples:
Input: bookings[][] = {{1, 2, 10}, {2, 3, 20}, {2, 5, 25}}Output: 10 55 45 25 25Explanation:Initially, there are no seats booked in any of the flights. So the resultant sequence is {0, 0, 0, 0, 0}Book 10 seats in flights 1 to 2. The sequence becomes {10, 10, 0, 0, 0}.Book 20 seats in flights 2 to 3. The sequence becomes {10, 30, 20, 0, 0}.Book 25 seats in flights 2 to 5. The sequence becomes {10, 55, 45, 25, 25}.
Input: bookings[][] = {{1, 3, 100}, {2, 6, 100}, {3, 4, 100}}Output: 100 200 300 200 100 100
Naive Approach: Follow the steps below to solve the problem in simplest approach possible:
Initialize an array seq[] of size N to store the count of allocated seats in each flight.
Traverse the array bookings[].
For each query {a, b, K}, add the element K in the array seq[] from the index a to b.
After completing the above steps, print the array seq[] as the result.
Time Complexity: O(N2)Auxiliary Space: O(N)
Efficient Approach: To optimize the above approach, the idea is to use the concept of Prefix Sum. Follow the steps below to solve the problem:
Initialize an array seq[] of size (N + 2) to store all the allocated seats.
Traverse the array bookings[].
For each query {a, b, K}, increment the array seq[] at index (a – 1) by K and decrement the element at index (b + 1) by K.
For the resulting sequence, find the prefix sum of the array seq[].
After completing the above steps, print the array seq[] as the 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 find the total of the// seats booked in each of the flightsvoid corpFlightBookings( vector<vector<int> >& Bookings, int N){ // Stores the resultant sequence vector<int> res(N, 0); // Traverse the array for (int i = 0; i < Bookings.size(); i++) { // Store the first booked flight int l = Bookings[i][0]; // Store the last booked flight int r = Bookings[i][1]; // Store the total number of // seats booked in flights [l, r] int K = Bookings[i][2]; // Add K to the flight L res[l - 1] = res[l - 1] + K; // Subtract K from flight // number R + 1 if (r <= res.size() - 1) res[r] = (-K) + res[r]; } // Find the prefix sum of the array for (int i = 1; i < res.size(); i++) res[i] = res[i] + res[i - 1]; // Print the total number of seats // booked in each flight for (int i = 0; i < res.size(); i++) { cout << res[i] << " "; }} // Driver Codeint main(){ // Given list of bookings vector<vector<int> > bookings{ { 1, 3, 100 }, { 2, 6, 100 }, { 3, 4, 100 } }; int N = 6; // Function Call corpFlightBookings(bookings, N); return 0;}
// Java program for the above approachimport java.util.*; class GFG{ // Function to find the total of the// seats booked in each of the flightsstatic void corpFlightBookings(int [][]Bookings, int N){ // Stores the resultant sequence int res[] = new int[N]; // Traverse the array for (int i = 0; i < Bookings.length; i++) { // Store the first booked flight int l = Bookings[i][0]; // Store the last booked flight int r = Bookings[i][1]; // Store the total number of // seats booked in flights [l, r] int K = Bookings[i][2]; // Add K to the flight L res[l - 1] = res[l - 1] + K; // Subtract K from flight // number R + 1 if (r <= res.length - 1) res[r] = (-K) + res[r]; } // Find the prefix sum of the array for (int i = 1; i < res.length; i++) res[i] = res[i] + res[i - 1]; // Print the total number of seats // booked in each flight for (int i = 0; i < res.length; i++) { System.out.print(res[i] + " "); }} // Driver Codepublic static void main(String[] args){ // Given list of bookings int bookings[][] = { { 1, 3, 100 }, { 2, 6, 100 }, { 3, 4, 100 } }; int N = 6; // Function Call corpFlightBookings(bookings, N);}} // This code is contributed by 29AjayKumar
# Python3 program for the above approach # Function to find the total of the# seats booked in each of the flightsdef corpFlightBookings(Bookings, N): # Stores the resultant sequence res = [0] * N # Traverse the array for i in range(len(Bookings)): # Store the first booked flight l = Bookings[i][0] # Store the last booked flight r = Bookings[i][1] # Store the total number of # seats booked in flights [l, r] K = Bookings[i][2] # Add K to the flight L res[l - 1] = res[l - 1] + K # Subtract K from flight # number R + 1 if (r <= len(res) - 1): res[r] = (-K) + res[r] # Find the prefix sum of the array for i in range(1, len(res)): res[i] = res[i] + res[i - 1] # Print total number of seats # booked in each flight for i in range(len(res)): print(res[i], end = " ") # Driver Codeif __name__ == '__main__': # Given list of bookings bookings = [ [ 1, 3, 100 ], [ 2, 6, 100 ], [ 3, 4, 100 ] ] N = 6 # Function Call corpFlightBookings(bookings, N) # This code is contributed by mohit kumar 29
// C# program for the above approachusing System;class GFG{ // Function to find the total of the// seats booked in each of the flightsstatic void corpFlightBookings(int [,]Bookings, int N){ // Stores the resultant sequence int []res = new int[N]; // Traverse the array for (int i = 0; i < Bookings.GetLength(0); i++) { // Store the first booked flight int l = Bookings[i,0]; // Store the last booked flight int r = Bookings[i,1]; // Store the total number of // seats booked in flights [l, r] int K = Bookings[i,2]; // Add K to the flight L res[l - 1] = res[l - 1] + K; // Subtract K from flight // number R + 1 if (r <= res.Length - 1) res[r] = (-K) + res[r]; } // Find the prefix sum of the array for (int i = 1; i < res.Length; i++) res[i] = res[i] + res[i - 1]; // Print the total number of seats // booked in each flight for (int i = 0; i < res.Length; i++) { Console.Write(res[i] + " "); }} // Driver Codepublic static void Main(String[] args){ // Given list of bookings int [,]bookings = { { 1, 3, 100 }, { 2, 6, 100 }, { 3, 4, 100 } }; int N = 6; // Function Call corpFlightBookings(bookings, N);}} // This code is contributed by shikhasingrajput
<script> // Javascript program for the above approach // Function to find the total of the// seats booked in each of the flightsfunction corpFlightBookings(Bookings, N){ // Stores the resultant sequence let res = new Array(N).fill(0); // Traverse the array for(let i = 0; i < Bookings.length; i++) { // Store the first booked flight let l = Bookings[i][0]; // Store the last booked flight let r = Bookings[i][1]; // Store the total number of // seats booked in flights [l, r] let K = Bookings[i][2]; // Add K to the flight L res[l - 1] = res[l - 1] + K; // Subtract K from flight // number R + 1 if (r <= res.length - 1) res[r] = (-K) + res[r]; } // Find the prefix sum of the array for(let i = 1; i < res.length; i++) res[i] = res[i] + res[i - 1]; // Print the total number of seats // booked in each flight for(let i = 0; i < res.length; i++) { document.write(res[i] + " "); }} // Driver Code // Given list of bookingslet bookings = [ [ 1, 3, 100 ], [ 2, 6, 100 ], [ 3, 4, 100 ] ];let N = 6; // Function CallcorpFlightBookings(bookings, N); // This code is contributed by splevel62 </script>
100 200 300 200 100 100
Time Complexity: O(N)Auxiliary Space: O(N)
mohit kumar 29
29AjayKumar
shikhasingrajput
splevel62
bunnyram19
interview-preparation
prefix-sum
Arrays
Greedy
Mathematical
prefix-sum
Arrays
Greedy
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Multidimensional Arrays in Java
Introduction to Arrays
Linear Search
Python | Using 2D arrays/lists the right way
Dijkstra's shortest path algorithm | Greedy Algo-7
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
Huffman Coding | Greedy Algo-3
Write a program to print all permutations of a given string | [
{
"code": null,
"e": 25220,
"s": 25192,
"text": "\n23 Jul, 2021"
},
{
"code": null,
"e": 25502,
"s": 25220,
"text": "Given an integer N denoting the number of flights and array bookings[][3] with each row of the form {a, b, K} denoting that there are K seats booked from flight a to flight b ( consider 1-based indexing), the task is to find the sequence of the number of seats booked in N flights."
},
{
"code": null,
"e": 25512,
"s": 25502,
"text": "Examples:"
},
{
"code": null,
"e": 25929,
"s": 25512,
"text": "Input: bookings[][] = {{1, 2, 10}, {2, 3, 20}, {2, 5, 25}}Output: 10 55 45 25 25Explanation:Initially, there are no seats booked in any of the flights. So the resultant sequence is {0, 0, 0, 0, 0}Book 10 seats in flights 1 to 2. The sequence becomes {10, 10, 0, 0, 0}.Book 20 seats in flights 2 to 3. The sequence becomes {10, 30, 20, 0, 0}.Book 25 seats in flights 2 to 5. The sequence becomes {10, 55, 45, 25, 25}."
},
{
"code": null,
"e": 26022,
"s": 25929,
"text": "Input: bookings[][] = {{1, 3, 100}, {2, 6, 100}, {3, 4, 100}}Output: 100 200 300 200 100 100"
},
{
"code": null,
"e": 26113,
"s": 26022,
"text": "Naive Approach: Follow the steps below to solve the problem in simplest approach possible:"
},
{
"code": null,
"e": 26203,
"s": 26113,
"text": "Initialize an array seq[] of size N to store the count of allocated seats in each flight."
},
{
"code": null,
"e": 26234,
"s": 26203,
"text": "Traverse the array bookings[]."
},
{
"code": null,
"e": 26320,
"s": 26234,
"text": "For each query {a, b, K}, add the element K in the array seq[] from the index a to b."
},
{
"code": null,
"e": 26391,
"s": 26320,
"text": "After completing the above steps, print the array seq[] as the result."
},
{
"code": null,
"e": 26435,
"s": 26391,
"text": "Time Complexity: O(N2)Auxiliary Space: O(N)"
},
{
"code": null,
"e": 26578,
"s": 26435,
"text": "Efficient Approach: To optimize the above approach, the idea is to use the concept of Prefix Sum. Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 26654,
"s": 26578,
"text": "Initialize an array seq[] of size (N + 2) to store all the allocated seats."
},
{
"code": null,
"e": 26685,
"s": 26654,
"text": "Traverse the array bookings[]."
},
{
"code": null,
"e": 26808,
"s": 26685,
"text": "For each query {a, b, K}, increment the array seq[] at index (a – 1) by K and decrement the element at index (b + 1) by K."
},
{
"code": null,
"e": 26876,
"s": 26808,
"text": "For the resulting sequence, find the prefix sum of the array seq[]."
},
{
"code": null,
"e": 26947,
"s": 26876,
"text": "After completing the above steps, print the array seq[] as the result."
},
{
"code": null,
"e": 26998,
"s": 26947,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 27002,
"s": 26998,
"text": "C++"
},
{
"code": null,
"e": 27007,
"s": 27002,
"text": "Java"
},
{
"code": null,
"e": 27015,
"s": 27007,
"text": "Python3"
},
{
"code": null,
"e": 27018,
"s": 27015,
"text": "C#"
},
{
"code": null,
"e": 27029,
"s": 27018,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find the total of the// seats booked in each of the flightsvoid corpFlightBookings( vector<vector<int> >& Bookings, int N){ // Stores the resultant sequence vector<int> res(N, 0); // Traverse the array for (int i = 0; i < Bookings.size(); i++) { // Store the first booked flight int l = Bookings[i][0]; // Store the last booked flight int r = Bookings[i][1]; // Store the total number of // seats booked in flights [l, r] int K = Bookings[i][2]; // Add K to the flight L res[l - 1] = res[l - 1] + K; // Subtract K from flight // number R + 1 if (r <= res.size() - 1) res[r] = (-K) + res[r]; } // Find the prefix sum of the array for (int i = 1; i < res.size(); i++) res[i] = res[i] + res[i - 1]; // Print the total number of seats // booked in each flight for (int i = 0; i < res.size(); i++) { cout << res[i] << \" \"; }} // Driver Codeint main(){ // Given list of bookings vector<vector<int> > bookings{ { 1, 3, 100 }, { 2, 6, 100 }, { 3, 4, 100 } }; int N = 6; // Function Call corpFlightBookings(bookings, N); return 0;}",
"e": 28402,
"s": 27029,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*; class GFG{ // Function to find the total of the// seats booked in each of the flightsstatic void corpFlightBookings(int [][]Bookings, int N){ // Stores the resultant sequence int res[] = new int[N]; // Traverse the array for (int i = 0; i < Bookings.length; i++) { // Store the first booked flight int l = Bookings[i][0]; // Store the last booked flight int r = Bookings[i][1]; // Store the total number of // seats booked in flights [l, r] int K = Bookings[i][2]; // Add K to the flight L res[l - 1] = res[l - 1] + K; // Subtract K from flight // number R + 1 if (r <= res.length - 1) res[r] = (-K) + res[r]; } // Find the prefix sum of the array for (int i = 1; i < res.length; i++) res[i] = res[i] + res[i - 1]; // Print the total number of seats // booked in each flight for (int i = 0; i < res.length; i++) { System.out.print(res[i] + \" \"); }} // Driver Codepublic static void main(String[] args){ // Given list of bookings int bookings[][] = { { 1, 3, 100 }, { 2, 6, 100 }, { 3, 4, 100 } }; int N = 6; // Function Call corpFlightBookings(bookings, N);}} // This code is contributed by 29AjayKumar",
"e": 29825,
"s": 28402,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to find the total of the# seats booked in each of the flightsdef corpFlightBookings(Bookings, N): # Stores the resultant sequence res = [0] * N # Traverse the array for i in range(len(Bookings)): # Store the first booked flight l = Bookings[i][0] # Store the last booked flight r = Bookings[i][1] # Store the total number of # seats booked in flights [l, r] K = Bookings[i][2] # Add K to the flight L res[l - 1] = res[l - 1] + K # Subtract K from flight # number R + 1 if (r <= len(res) - 1): res[r] = (-K) + res[r] # Find the prefix sum of the array for i in range(1, len(res)): res[i] = res[i] + res[i - 1] # Print total number of seats # booked in each flight for i in range(len(res)): print(res[i], end = \" \") # Driver Codeif __name__ == '__main__': # Given list of bookings bookings = [ [ 1, 3, 100 ], [ 2, 6, 100 ], [ 3, 4, 100 ] ] N = 6 # Function Call corpFlightBookings(bookings, N) # This code is contributed by mohit kumar 29",
"e": 31008,
"s": 29825,
"text": null
},
{
"code": "// C# program for the above approachusing System;class GFG{ // Function to find the total of the// seats booked in each of the flightsstatic void corpFlightBookings(int [,]Bookings, int N){ // Stores the resultant sequence int []res = new int[N]; // Traverse the array for (int i = 0; i < Bookings.GetLength(0); i++) { // Store the first booked flight int l = Bookings[i,0]; // Store the last booked flight int r = Bookings[i,1]; // Store the total number of // seats booked in flights [l, r] int K = Bookings[i,2]; // Add K to the flight L res[l - 1] = res[l - 1] + K; // Subtract K from flight // number R + 1 if (r <= res.Length - 1) res[r] = (-K) + res[r]; } // Find the prefix sum of the array for (int i = 1; i < res.Length; i++) res[i] = res[i] + res[i - 1]; // Print the total number of seats // booked in each flight for (int i = 0; i < res.Length; i++) { Console.Write(res[i] + \" \"); }} // Driver Codepublic static void Main(String[] args){ // Given list of bookings int [,]bookings = { { 1, 3, 100 }, { 2, 6, 100 }, { 3, 4, 100 } }; int N = 6; // Function Call corpFlightBookings(bookings, N);}} // This code is contributed by shikhasingrajput",
"e": 32425,
"s": 31008,
"text": null
},
{
"code": "<script> // Javascript program for the above approach // Function to find the total of the// seats booked in each of the flightsfunction corpFlightBookings(Bookings, N){ // Stores the resultant sequence let res = new Array(N).fill(0); // Traverse the array for(let i = 0; i < Bookings.length; i++) { // Store the first booked flight let l = Bookings[i][0]; // Store the last booked flight let r = Bookings[i][1]; // Store the total number of // seats booked in flights [l, r] let K = Bookings[i][2]; // Add K to the flight L res[l - 1] = res[l - 1] + K; // Subtract K from flight // number R + 1 if (r <= res.length - 1) res[r] = (-K) + res[r]; } // Find the prefix sum of the array for(let i = 1; i < res.length; i++) res[i] = res[i] + res[i - 1]; // Print the total number of seats // booked in each flight for(let i = 0; i < res.length; i++) { document.write(res[i] + \" \"); }} // Driver Code // Given list of bookingslet bookings = [ [ 1, 3, 100 ], [ 2, 6, 100 ], [ 3, 4, 100 ] ];let N = 6; // Function CallcorpFlightBookings(bookings, N); // This code is contributed by splevel62 </script>",
"e": 33731,
"s": 32425,
"text": null
},
{
"code": null,
"e": 33755,
"s": 33731,
"text": "100 200 300 200 100 100"
},
{
"code": null,
"e": 33800,
"s": 33757,
"text": "Time Complexity: O(N)Auxiliary Space: O(N)"
},
{
"code": null,
"e": 33815,
"s": 33800,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 33827,
"s": 33815,
"text": "29AjayKumar"
},
{
"code": null,
"e": 33844,
"s": 33827,
"text": "shikhasingrajput"
},
{
"code": null,
"e": 33854,
"s": 33844,
"text": "splevel62"
},
{
"code": null,
"e": 33865,
"s": 33854,
"text": "bunnyram19"
},
{
"code": null,
"e": 33887,
"s": 33865,
"text": "interview-preparation"
},
{
"code": null,
"e": 33898,
"s": 33887,
"text": "prefix-sum"
},
{
"code": null,
"e": 33905,
"s": 33898,
"text": "Arrays"
},
{
"code": null,
"e": 33912,
"s": 33905,
"text": "Greedy"
},
{
"code": null,
"e": 33925,
"s": 33912,
"text": "Mathematical"
},
{
"code": null,
"e": 33936,
"s": 33925,
"text": "prefix-sum"
},
{
"code": null,
"e": 33943,
"s": 33936,
"text": "Arrays"
},
{
"code": null,
"e": 33950,
"s": 33943,
"text": "Greedy"
},
{
"code": null,
"e": 33963,
"s": 33950,
"text": "Mathematical"
},
{
"code": null,
"e": 34061,
"s": 33963,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34129,
"s": 34061,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 34161,
"s": 34129,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 34184,
"s": 34161,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 34198,
"s": 34184,
"text": "Linear Search"
},
{
"code": null,
"e": 34243,
"s": 34198,
"text": "Python | Using 2D arrays/lists the right way"
},
{
"code": null,
"e": 34294,
"s": 34243,
"text": "Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 34352,
"s": 34294,
"text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2"
},
{
"code": null,
"e": 34403,
"s": 34352,
"text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5"
},
{
"code": null,
"e": 34434,
"s": 34403,
"text": "Huffman Coding | Greedy Algo-3"
}
]
|
Firebase - Write List Data | In our last chapter, we showed you how to write data in Firebase. Sometimes you need to have a unique identifier for your data. When you want to create unique identifiers for your data, you need to use the push method instead of the set method.
The push() method will create a unique id when the data is pushed. If we want to create our players from the previous chapters with a unique id, we could use the code snippet given below.
var ref = new Firebase('https://tutorialsfirebase.firebaseio.com');
var playersRef = ref.child("players");
playersRef.push ({
name: "John",
number: 1,
age: 30
});
playersRef.push ({
name: "Amanda",
number: 2,
age: 20
});
Now our data will look differently. The name will just be a name/value pair like the rest of the properties.
We can get any key from Firebase by using the key() method. For example, if we want to get our collection name, we could use the following snippet.
var ref = new Firebase('https://tutorialsfirebase.firebaseio.com');
var playersRef = ref.child("players");
var playersKey = playersRef.key();
console.log(playersKey);
The console will log our collection name (players).
More on this in our next chapters.
60 Lectures
5 hours
University Code
28 Lectures
2.5 hours
Appeteria
85 Lectures
14.5 hours
Appeteria
46 Lectures
2.5 hours
Gautham Vijayan
13 Lectures
1.5 hours
Nishant Kumar
85 Lectures
16.5 hours
Rahul Agarwal
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2411,
"s": 2166,
"text": "In our last chapter, we showed you how to write data in Firebase. Sometimes you need to have a unique identifier for your data. When you want to create unique identifiers for your data, you need to use the push method instead of the set method."
},
{
"code": null,
"e": 2599,
"s": 2411,
"text": "The push() method will create a unique id when the data is pushed. If we want to create our players from the previous chapters with a unique id, we could use the code snippet given below."
},
{
"code": null,
"e": 2840,
"s": 2599,
"text": "var ref = new Firebase('https://tutorialsfirebase.firebaseio.com');\n\nvar playersRef = ref.child(\"players\");\nplayersRef.push ({\n name: \"John\",\n number: 1,\n age: 30\n});\n\nplayersRef.push ({\n name: \"Amanda\",\n number: 2,\n age: 20\n});"
},
{
"code": null,
"e": 2949,
"s": 2840,
"text": "Now our data will look differently. The name will just be a name/value pair like the rest of the properties."
},
{
"code": null,
"e": 3097,
"s": 2949,
"text": "We can get any key from Firebase by using the key() method. For example, if we want to get our collection name, we could use the following snippet."
},
{
"code": null,
"e": 3266,
"s": 3097,
"text": "var ref = new Firebase('https://tutorialsfirebase.firebaseio.com');\n\nvar playersRef = ref.child(\"players\");\n\nvar playersKey = playersRef.key();\nconsole.log(playersKey);"
},
{
"code": null,
"e": 3318,
"s": 3266,
"text": "The console will log our collection name (players)."
},
{
"code": null,
"e": 3353,
"s": 3318,
"text": "More on this in our next chapters."
},
{
"code": null,
"e": 3386,
"s": 3353,
"text": "\n 60 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 3403,
"s": 3386,
"text": " University Code"
},
{
"code": null,
"e": 3438,
"s": 3403,
"text": "\n 28 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3449,
"s": 3438,
"text": " Appeteria"
},
{
"code": null,
"e": 3485,
"s": 3449,
"text": "\n 85 Lectures \n 14.5 hours \n"
},
{
"code": null,
"e": 3496,
"s": 3485,
"text": " Appeteria"
},
{
"code": null,
"e": 3531,
"s": 3496,
"text": "\n 46 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3548,
"s": 3531,
"text": " Gautham Vijayan"
},
{
"code": null,
"e": 3583,
"s": 3548,
"text": "\n 13 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3598,
"s": 3583,
"text": " Nishant Kumar"
},
{
"code": null,
"e": 3634,
"s": 3598,
"text": "\n 85 Lectures \n 16.5 hours \n"
},
{
"code": null,
"e": 3649,
"s": 3634,
"text": " Rahul Agarwal"
},
{
"code": null,
"e": 3656,
"s": 3649,
"text": " Print"
},
{
"code": null,
"e": 3667,
"s": 3656,
"text": " Add Notes"
}
]
|
Smarter Ways to Encode Categorical Data for Machine Learning | by Jeff Hale | Towards Data Science | Better encoding of categorical data can mean better model performance. In this article I’ll introduce you to a wide range of encoding options from the Category Encoders package for use with scikit-learn machine learning in Python.
Use Category Encoders to improve model performance when you have nominal or ordinal data that may provide value.
For nominal columns try OneHot, Hashing, LeaveOneOut, and Target encoding. Avoid OneHot for high cardinality columns and decision tree-based algorithms.
For ordinal columns try Ordinal (Integer), Binary, OneHot, LeaveOneOut, and Target. Helmert, Sum, BackwardDifference and Polynomial are less likely to be helpful, but if you have time or theoretic reason you might want to try them.
For regression tasks, Target and LeaveOneOut probably won’t work well.
In this article I’ll discuss terms, general usage and five classic encoding options: Ordinal, One Hot, Binary, BaseN, and Hashing. In the future I may evaluate Bayesian encoders and contrast encoders with roots in statistical hypothesis testing. 🚀
In an earlier article I argued we should classify data as one of seven types to make better models faster. Here are the seven data types:
Useless — useless for machine learning algorithms, that is — discreteNominal — groups without order — discreteBinary — either/or — discreteOrdinal — groups with order — discreteCount — the number of occurrences — discreteTime — cyclical numbers with a temporal component — continuousInterval — positive and/or negative numbers without a temporal component — continuous
Here we’re concerned with encoding nominal and ordinal data. A column with nominal data has values that cannot be ordered in any meaningful way. Nominal data is most often one-hot (aka dummy) encoded, but there are many options that might perform better for machine learning.
In contrast, ordinal data can be rank ordered. Ordinal data can be encoded in one of three ways, broadly speaking, but I think it’s safe to say that its encoding is often not carefully considered.
It can be assumed to be close enough to interval data — with relatively equal magnitudes between the values — to treat it as such. Social scientists make this assumption all the time with Likert scales. For example, “On a scale from 1 to 7, 1 being extremely unlikely, 4 being neither likely nor unlikely and 7 being extremely likely, how likely are you to recommend this movie to a friend?” Here the difference between 3 and 4 and the difference between 6 and 7 can be reasonably assumed to be similar.It can be treated as nominal data, where each category has no numeric relationship to another. You can try one-hot encoding and other encodings appropriate for nominal data.The magnitude of the difference between the numbers can be ignored. You can just train your model with different encodings and see which encoding works best.
It can be assumed to be close enough to interval data — with relatively equal magnitudes between the values — to treat it as such. Social scientists make this assumption all the time with Likert scales. For example, “On a scale from 1 to 7, 1 being extremely unlikely, 4 being neither likely nor unlikely and 7 being extremely likely, how likely are you to recommend this movie to a friend?” Here the difference between 3 and 4 and the difference between 6 and 7 can be reasonably assumed to be similar.
It can be treated as nominal data, where each category has no numeric relationship to another. You can try one-hot encoding and other encodings appropriate for nominal data.
The magnitude of the difference between the numbers can be ignored. You can just train your model with different encodings and see which encoding works best.
In this series we’ll look at Categorical Encoders 11 encoders as of version 1.2.8. **Update: Version 1.3.0 is the latest version on PyPI as of April 11, 2019.**
Many of these encoding methods go by more than one name in the statistics world and sometimes one name can mean different things. We’ll follow the Category Encoders usage.
Big thanks to Will McGinnis for creating and maintaining this package. It is largely derived from StatsModel’s Patsy package, which in turn is based on this UCLA statistics reference.
There are an infinite number of ways to encode categorical information. The ones in Category Encoders should be sufficient for most uses. 👍
Here’s the list of Category Encoders functions with their descriptions and the type of data they would be most appropriate to encode.
The first group of five classic encoders can be seen on a continuum of embedding information in one column (Ordinal) up to k columns (OneHot). These are very useful encodings for machine learning practitioners to understand.
Ordinal — convert string labels to integer values 1 through k. Ordinal.OneHot — one column for each value to compare vs. all other values. Nominal, ordinal.Binary — convert each integer to binary digits. Each binary digit gets one column. Some info loss but fewer dimensions. Ordinal.BaseN — Ordinal, Binary, or higher encoding. Nominal, ordinal. Doesn’t add much functionality. Probably avoid.Hashing — Like OneHot but fewer dimensions, some info loss due to collisions. Nominal, ordinal.Sum — Just like OneHot except one value is held constant and encoded as -1 across all columns.
The five contrast encoders all have multiple issues that I argue make them unlikely to be useful for machine learning. They all output one column for each value found in a column. Their stated intents are below.
Helmert (reverse) — The mean of the dependent variable for a level is compared to the mean of the dependent variable over all previous levels.Backward Difference — the mean of the dependent variable for a level is compared with the mean of the dependent variable for the prior level. Polynomial — orthogonal polynomial contrasts. The coefficients taken on by polynomial coding for k=4 levels are the linear, quadratic, and cubic trends in the categorical variable.
The Bayesian encoders use information from the dependent variable in their encodings. They output one column and can work well with high cardinality data.
Target — use the mean of the DV, must take steps to avoid overfitting/ response leakage. Nominal, ordinal. For classification tasks.LeaveOneOut — similar to target but avoids contamination. Nominal, ordinal. For classification tasks.WeightOfEvidence — added in v1.3. Not documented in the docs as of April 11, 2019. The method is explained in this post.James-Stein — forthcoming in v1.4. Described in the code here.M-estimator — forthcoming in v1.4. Described in the code here. Simplified target encoder.
Category Encoders follow the same API as scikit-learn’s preprocessors. They have some added conveniences, such as the ability to easily add an encoder to a pipeline. Additionally, the encoder returns a pandas DataFrame if a DataFrame is passed to it. Here’s an example of the code with the BinaryEncoder:
We’ll tackle a few gotchas with implementation in the future. But you should be able to jump right into the first five if you are familiar with scikit-learn’s API.
Note that all Category Encoders impute missing values automatically by default. However, I recommend filling missing data data yourself prior to encoding so you can test the results of several methods. I plan to discuss imputing options in a forthcoming article, so follow me on Medium if you want to make sure you don’t miss it.
You might see commentators use the following terms interchangeably: dimension, feature, vector, series, independent variable, and column. I will too :) Similarly, you might see row and observation used interchangeably.
k is the original number of unique values in your data column. High cardinality means a lot of unique values (a large k). A column with hundreds of zip codes is an example of a high cardinality feature.
High dimensionality means a matrix with many dimensions. High dimensionality comes with the Curse of Dimensionality — a thorough treatment of this topic can be found here. The take away is that high dimensionality requires many observations and often results in overfitting.
Sparse data is a matrix with lots of zeroes relative to other values. If your encoders transform your data so that it becomes sparse, some algorithms may not work well. Sparsity can often be managed by flagging it, but many algorithms don’t work well unless the data is dense.
Without further ado, let’s encode!
OrdinalEncoder converts each string value to a whole number. The first unique value in your column becomes 1, the second becomes 2, the third becomes 3, and so on.
What the actual value was prior to encoding does not affect what it becomes when you fit_transform with OrdinalEncoder. The first value could have been 10 and the second value could have been 3. Now they will be 1 and 2, respectively.
If the column contains nominal data, stopping after you use OrdinalEncoder is a bad idea. Your machine learning algorithm will treat the variable as continuous and assume the values are on a meaningful scale. Instead, if you have a column with values car, bus, and truck you should first encode this nominal data using OrdinalEncoder. Then encode it again using one of the methods appropriate to nominal data that we’ll explore below.
In contrast, if your column values are truly ordinal, that means that the integer assigned to each value is meaningful. Assignment should be done with intention. Say your column had the string values “First”, “Third”, and “Second” in it. Those values should be mapped to the corresponding integers by passing OrdinalEncoder a list of dicts like so:
[{"col": "finished_race_order", "mapping": [("First", 1), ("Second", 2), ("Third", 3)]}]
Here’s the basic setup for all the code samples to follow. You can get the full notebook at this Kaggle Kernel.
Here’s the untransformed X column.
And here’s the OrdinalEncoder code to transform the color column values from letters to integers.
All the string values are now integers.
Scikit-learn’s OrdinalEncoder does pretty much the same thing as Category Encoder’s OrdinalEncoder, but is not quite as user friendly. Scikit-learn’s encoder won’t return a pandas DataFrame. Instead it returns a NumPy array if you pass a DataFrame. It also outputs values starting with 0, compared to OrdinalEncoder’s default of outputting values starting with 1.
You could accomplish ordinal encoding by mapping string values to integers in pandas. But that’s extra work once you know how to use Category Encoders.
One-hot encoding is the classic approach to dealing with nominal, and maybe ordinal, data. It’s referred to as the “The Standard Approach for Categorical Data” in Kaggle’s Machine Learning tutorial series. It also goes by the names dummy encoding, indicator encoding, and occasionally binary encoding. Yes, this is confusing. 😉
The one-hot encoder creates one column for each value to compare against all other values. For each new column, a row gets a 1 if the row contained that column’s value and a 0 if it did not. Here’s how it looks:
color_-1 is actually an extraneous column, because it’s all 0s — with no variation, it’s not helping your model learn anything. It may have been intended for missing values, but in version 1.2.8 of Category Encoders it doesn’t serve a purpose.
One-hot encoding can perform very well, but the number of new features is equal to k, the number of unique values. This feature expansion can create serious memory problems if your dataset has high cardinality features. One-hot-encoded data can also be difficult for decision-tree-based algorithms — see discussion here.
The pandas GetDummies and scikit-learn’s OneHotEncoder functions perform the same role as the Category Encoders OneHotEncoder. I find Category Encoders OneHotEncoder a bit nicer to use.
Binary encoding can be thought of as a hybrid of one-hot and hashing encoders. Binary creates fewer features than one-hot, while preserving some uniqueness of values in the column. It can work well with higher dimensionality ordinal data.
Here’s how it works:
The categories are encoded by OrdinalEncoder if they aren’t already in numeric form.
Then those integers are converted into binary code, so for example 5 becomes 101 and 10 becomes 1010
Then the digits from that binary string are split into separate columns. So if there are 4–7 values in an ordinal column then 3 new columns are created: one for the first bit, one for the second, and one for the third.
Each observation is encoded across the columns in its binary form.
Here’s how it looks:
The first column has no variance, so it isn’t doing anything to help the model.
With only three levels, the information embedded becomes muddled. There are many collisions and the model can’t glean much information from the features. Just one-hot encode a column if it only has a few values.
In contrast, binary really shines when the cardinality of the column is higher — with the 50 US states, for example.
Binary encoding creates fewer columns than one-hot encoding. It is more memory efficient. It also reduces the chances of dimensionality problems with higher cardinality.
For ordinal data, most values that were close to each other when in ordinal form will share many of the same values in the new columns. Many machine learning algorithms can learn that the features are similar. Binary encoding is a decent compromise for ordinal data with high cardinality.
If you’ve used binary encoding successfully, please share in the comment. For nominal data a hashing algorithm with more fine-grained control usually makes more sense.
When the BaseN base = 1 it is basically the same as one hot encoding. When base = 2 it is basically the same as binary encoding. McGinnis said of this encoder, “Practically, this adds very little new functionality, rarely do people use base-3 or base-8 or any base other than ordinal or binary in real problems.”
The main reason for BaseN’s existence is to possibly make grid searching easier. You could use BaseN with scikit-learn’s GridSearchCV. However, if you’re going to grid search with these encoding options, you can make the encoder part of your scikit-learn pipeline and put the options in your parameter grid. I don’t see a compelling reason to use BaseN. If you do, please share in the comments.
The default base for BaseNEncoder is 2, which is the equivalent of BinaryEncoder.
HashingEncoder implements the hashing trick. It is similar to one-hot encoding but with fewer new dimensions and some info loss due to collisions. The collisions do not significantly affect performance unless there is a great deal of overlap. An excellent discussion of the hashing trick and guidelines for selecting the number of output features can be found here.
Here’s the ordinal column again for a refresher.
And here’s the HashingEncoder with output.
The n_components parameter controls the number of expanded columns. The default is eight columns. In our example column with three values the default results in five columns full of 0s.
If you set n_components less than k you’ll have a small reduction in the value provided by the encoded data. You’ll also have fewer dimensions.
You can pass a hashing algorithm of your choice to HashingEncoder; the default is md5. Hashing algorithms have been very successful in some Kaggle competitions. It’s worth trying HashingEncoder for nominal and ordinal data if you have high cardinality features. 👍
That’s all for now. Here’s a recap and suggestions for when to use the encoders.
For nominal columns try OneHot, Hashing, LeaveOneOut, and Target encoding. Avoid OneHot for high cardinality columns.
For ordinal columns try Ordinal (Integer), Binary, OneHot, LeaveOneOut, and Target. Helmert, Sum, BackwardDifference and Polynomial are less likely to be helpful, but if you have time or theoretic reason you might want to try them.
The Bayesian encoders can work well for some machine learning tasks. For example, Owen Zhang used the leave one out encoding method to perform well in a Kaggle classification challenge.
*Update April 2019: I updated this article to include information about forthcoming encoders and reworked the conclusion.**
I write about data science, Python, SQL, and DevOps. Check out my other articles and follow me here if you’re into that stuff. 😀
Thanks for reading! | [
{
"code": null,
"e": 403,
"s": 172,
"text": "Better encoding of categorical data can mean better model performance. In this article I’ll introduce you to a wide range of encoding options from the Category Encoders package for use with scikit-learn machine learning in Python."
},
{
"code": null,
"e": 516,
"s": 403,
"text": "Use Category Encoders to improve model performance when you have nominal or ordinal data that may provide value."
},
{
"code": null,
"e": 669,
"s": 516,
"text": "For nominal columns try OneHot, Hashing, LeaveOneOut, and Target encoding. Avoid OneHot for high cardinality columns and decision tree-based algorithms."
},
{
"code": null,
"e": 901,
"s": 669,
"text": "For ordinal columns try Ordinal (Integer), Binary, OneHot, LeaveOneOut, and Target. Helmert, Sum, BackwardDifference and Polynomial are less likely to be helpful, but if you have time or theoretic reason you might want to try them."
},
{
"code": null,
"e": 972,
"s": 901,
"text": "For regression tasks, Target and LeaveOneOut probably won’t work well."
},
{
"code": null,
"e": 1220,
"s": 972,
"text": "In this article I’ll discuss terms, general usage and five classic encoding options: Ordinal, One Hot, Binary, BaseN, and Hashing. In the future I may evaluate Bayesian encoders and contrast encoders with roots in statistical hypothesis testing. 🚀"
},
{
"code": null,
"e": 1358,
"s": 1220,
"text": "In an earlier article I argued we should classify data as one of seven types to make better models faster. Here are the seven data types:"
},
{
"code": null,
"e": 1727,
"s": 1358,
"text": "Useless — useless for machine learning algorithms, that is — discreteNominal — groups without order — discreteBinary — either/or — discreteOrdinal — groups with order — discreteCount — the number of occurrences — discreteTime — cyclical numbers with a temporal component — continuousInterval — positive and/or negative numbers without a temporal component — continuous"
},
{
"code": null,
"e": 2003,
"s": 1727,
"text": "Here we’re concerned with encoding nominal and ordinal data. A column with nominal data has values that cannot be ordered in any meaningful way. Nominal data is most often one-hot (aka dummy) encoded, but there are many options that might perform better for machine learning."
},
{
"code": null,
"e": 2200,
"s": 2003,
"text": "In contrast, ordinal data can be rank ordered. Ordinal data can be encoded in one of three ways, broadly speaking, but I think it’s safe to say that its encoding is often not carefully considered."
},
{
"code": null,
"e": 3034,
"s": 2200,
"text": "It can be assumed to be close enough to interval data — with relatively equal magnitudes between the values — to treat it as such. Social scientists make this assumption all the time with Likert scales. For example, “On a scale from 1 to 7, 1 being extremely unlikely, 4 being neither likely nor unlikely and 7 being extremely likely, how likely are you to recommend this movie to a friend?” Here the difference between 3 and 4 and the difference between 6 and 7 can be reasonably assumed to be similar.It can be treated as nominal data, where each category has no numeric relationship to another. You can try one-hot encoding and other encodings appropriate for nominal data.The magnitude of the difference between the numbers can be ignored. You can just train your model with different encodings and see which encoding works best."
},
{
"code": null,
"e": 3538,
"s": 3034,
"text": "It can be assumed to be close enough to interval data — with relatively equal magnitudes between the values — to treat it as such. Social scientists make this assumption all the time with Likert scales. For example, “On a scale from 1 to 7, 1 being extremely unlikely, 4 being neither likely nor unlikely and 7 being extremely likely, how likely are you to recommend this movie to a friend?” Here the difference between 3 and 4 and the difference between 6 and 7 can be reasonably assumed to be similar."
},
{
"code": null,
"e": 3712,
"s": 3538,
"text": "It can be treated as nominal data, where each category has no numeric relationship to another. You can try one-hot encoding and other encodings appropriate for nominal data."
},
{
"code": null,
"e": 3870,
"s": 3712,
"text": "The magnitude of the difference between the numbers can be ignored. You can just train your model with different encodings and see which encoding works best."
},
{
"code": null,
"e": 4031,
"s": 3870,
"text": "In this series we’ll look at Categorical Encoders 11 encoders as of version 1.2.8. **Update: Version 1.3.0 is the latest version on PyPI as of April 11, 2019.**"
},
{
"code": null,
"e": 4203,
"s": 4031,
"text": "Many of these encoding methods go by more than one name in the statistics world and sometimes one name can mean different things. We’ll follow the Category Encoders usage."
},
{
"code": null,
"e": 4387,
"s": 4203,
"text": "Big thanks to Will McGinnis for creating and maintaining this package. It is largely derived from StatsModel’s Patsy package, which in turn is based on this UCLA statistics reference."
},
{
"code": null,
"e": 4527,
"s": 4387,
"text": "There are an infinite number of ways to encode categorical information. The ones in Category Encoders should be sufficient for most uses. 👍"
},
{
"code": null,
"e": 4661,
"s": 4527,
"text": "Here’s the list of Category Encoders functions with their descriptions and the type of data they would be most appropriate to encode."
},
{
"code": null,
"e": 4886,
"s": 4661,
"text": "The first group of five classic encoders can be seen on a continuum of embedding information in one column (Ordinal) up to k columns (OneHot). These are very useful encodings for machine learning practitioners to understand."
},
{
"code": null,
"e": 5470,
"s": 4886,
"text": "Ordinal — convert string labels to integer values 1 through k. Ordinal.OneHot — one column for each value to compare vs. all other values. Nominal, ordinal.Binary — convert each integer to binary digits. Each binary digit gets one column. Some info loss but fewer dimensions. Ordinal.BaseN — Ordinal, Binary, or higher encoding. Nominal, ordinal. Doesn’t add much functionality. Probably avoid.Hashing — Like OneHot but fewer dimensions, some info loss due to collisions. Nominal, ordinal.Sum — Just like OneHot except one value is held constant and encoded as -1 across all columns."
},
{
"code": null,
"e": 5682,
"s": 5470,
"text": "The five contrast encoders all have multiple issues that I argue make them unlikely to be useful for machine learning. They all output one column for each value found in a column. Their stated intents are below."
},
{
"code": null,
"e": 6147,
"s": 5682,
"text": "Helmert (reverse) — The mean of the dependent variable for a level is compared to the mean of the dependent variable over all previous levels.Backward Difference — the mean of the dependent variable for a level is compared with the mean of the dependent variable for the prior level. Polynomial — orthogonal polynomial contrasts. The coefficients taken on by polynomial coding for k=4 levels are the linear, quadratic, and cubic trends in the categorical variable."
},
{
"code": null,
"e": 6302,
"s": 6147,
"text": "The Bayesian encoders use information from the dependent variable in their encodings. They output one column and can work well with high cardinality data."
},
{
"code": null,
"e": 6807,
"s": 6302,
"text": "Target — use the mean of the DV, must take steps to avoid overfitting/ response leakage. Nominal, ordinal. For classification tasks.LeaveOneOut — similar to target but avoids contamination. Nominal, ordinal. For classification tasks.WeightOfEvidence — added in v1.3. Not documented in the docs as of April 11, 2019. The method is explained in this post.James-Stein — forthcoming in v1.4. Described in the code here.M-estimator — forthcoming in v1.4. Described in the code here. Simplified target encoder."
},
{
"code": null,
"e": 7112,
"s": 6807,
"text": "Category Encoders follow the same API as scikit-learn’s preprocessors. They have some added conveniences, such as the ability to easily add an encoder to a pipeline. Additionally, the encoder returns a pandas DataFrame if a DataFrame is passed to it. Here’s an example of the code with the BinaryEncoder:"
},
{
"code": null,
"e": 7276,
"s": 7112,
"text": "We’ll tackle a few gotchas with implementation in the future. But you should be able to jump right into the first five if you are familiar with scikit-learn’s API."
},
{
"code": null,
"e": 7606,
"s": 7276,
"text": "Note that all Category Encoders impute missing values automatically by default. However, I recommend filling missing data data yourself prior to encoding so you can test the results of several methods. I plan to discuss imputing options in a forthcoming article, so follow me on Medium if you want to make sure you don’t miss it."
},
{
"code": null,
"e": 7825,
"s": 7606,
"text": "You might see commentators use the following terms interchangeably: dimension, feature, vector, series, independent variable, and column. I will too :) Similarly, you might see row and observation used interchangeably."
},
{
"code": null,
"e": 8028,
"s": 7825,
"text": "k is the original number of unique values in your data column. High cardinality means a lot of unique values (a large k). A column with hundreds of zip codes is an example of a high cardinality feature."
},
{
"code": null,
"e": 8303,
"s": 8028,
"text": "High dimensionality means a matrix with many dimensions. High dimensionality comes with the Curse of Dimensionality — a thorough treatment of this topic can be found here. The take away is that high dimensionality requires many observations and often results in overfitting."
},
{
"code": null,
"e": 8580,
"s": 8303,
"text": "Sparse data is a matrix with lots of zeroes relative to other values. If your encoders transform your data so that it becomes sparse, some algorithms may not work well. Sparsity can often be managed by flagging it, but many algorithms don’t work well unless the data is dense."
},
{
"code": null,
"e": 8615,
"s": 8580,
"text": "Without further ado, let’s encode!"
},
{
"code": null,
"e": 8779,
"s": 8615,
"text": "OrdinalEncoder converts each string value to a whole number. The first unique value in your column becomes 1, the second becomes 2, the third becomes 3, and so on."
},
{
"code": null,
"e": 9014,
"s": 8779,
"text": "What the actual value was prior to encoding does not affect what it becomes when you fit_transform with OrdinalEncoder. The first value could have been 10 and the second value could have been 3. Now they will be 1 and 2, respectively."
},
{
"code": null,
"e": 9449,
"s": 9014,
"text": "If the column contains nominal data, stopping after you use OrdinalEncoder is a bad idea. Your machine learning algorithm will treat the variable as continuous and assume the values are on a meaningful scale. Instead, if you have a column with values car, bus, and truck you should first encode this nominal data using OrdinalEncoder. Then encode it again using one of the methods appropriate to nominal data that we’ll explore below."
},
{
"code": null,
"e": 9798,
"s": 9449,
"text": "In contrast, if your column values are truly ordinal, that means that the integer assigned to each value is meaningful. Assignment should be done with intention. Say your column had the string values “First”, “Third”, and “Second” in it. Those values should be mapped to the corresponding integers by passing OrdinalEncoder a list of dicts like so:"
},
{
"code": null,
"e": 9917,
"s": 9798,
"text": "[{\"col\": \"finished_race_order\", \"mapping\": [(\"First\", 1), (\"Second\", 2), (\"Third\", 3)]}]"
},
{
"code": null,
"e": 10029,
"s": 9917,
"text": "Here’s the basic setup for all the code samples to follow. You can get the full notebook at this Kaggle Kernel."
},
{
"code": null,
"e": 10064,
"s": 10029,
"text": "Here’s the untransformed X column."
},
{
"code": null,
"e": 10162,
"s": 10064,
"text": "And here’s the OrdinalEncoder code to transform the color column values from letters to integers."
},
{
"code": null,
"e": 10202,
"s": 10162,
"text": "All the string values are now integers."
},
{
"code": null,
"e": 10566,
"s": 10202,
"text": "Scikit-learn’s OrdinalEncoder does pretty much the same thing as Category Encoder’s OrdinalEncoder, but is not quite as user friendly. Scikit-learn’s encoder won’t return a pandas DataFrame. Instead it returns a NumPy array if you pass a DataFrame. It also outputs values starting with 0, compared to OrdinalEncoder’s default of outputting values starting with 1."
},
{
"code": null,
"e": 10718,
"s": 10566,
"text": "You could accomplish ordinal encoding by mapping string values to integers in pandas. But that’s extra work once you know how to use Category Encoders."
},
{
"code": null,
"e": 11046,
"s": 10718,
"text": "One-hot encoding is the classic approach to dealing with nominal, and maybe ordinal, data. It’s referred to as the “The Standard Approach for Categorical Data” in Kaggle’s Machine Learning tutorial series. It also goes by the names dummy encoding, indicator encoding, and occasionally binary encoding. Yes, this is confusing. 😉"
},
{
"code": null,
"e": 11258,
"s": 11046,
"text": "The one-hot encoder creates one column for each value to compare against all other values. For each new column, a row gets a 1 if the row contained that column’s value and a 0 if it did not. Here’s how it looks:"
},
{
"code": null,
"e": 11502,
"s": 11258,
"text": "color_-1 is actually an extraneous column, because it’s all 0s — with no variation, it’s not helping your model learn anything. It may have been intended for missing values, but in version 1.2.8 of Category Encoders it doesn’t serve a purpose."
},
{
"code": null,
"e": 11823,
"s": 11502,
"text": "One-hot encoding can perform very well, but the number of new features is equal to k, the number of unique values. This feature expansion can create serious memory problems if your dataset has high cardinality features. One-hot-encoded data can also be difficult for decision-tree-based algorithms — see discussion here."
},
{
"code": null,
"e": 12009,
"s": 11823,
"text": "The pandas GetDummies and scikit-learn’s OneHotEncoder functions perform the same role as the Category Encoders OneHotEncoder. I find Category Encoders OneHotEncoder a bit nicer to use."
},
{
"code": null,
"e": 12248,
"s": 12009,
"text": "Binary encoding can be thought of as a hybrid of one-hot and hashing encoders. Binary creates fewer features than one-hot, while preserving some uniqueness of values in the column. It can work well with higher dimensionality ordinal data."
},
{
"code": null,
"e": 12269,
"s": 12248,
"text": "Here’s how it works:"
},
{
"code": null,
"e": 12354,
"s": 12269,
"text": "The categories are encoded by OrdinalEncoder if they aren’t already in numeric form."
},
{
"code": null,
"e": 12455,
"s": 12354,
"text": "Then those integers are converted into binary code, so for example 5 becomes 101 and 10 becomes 1010"
},
{
"code": null,
"e": 12674,
"s": 12455,
"text": "Then the digits from that binary string are split into separate columns. So if there are 4–7 values in an ordinal column then 3 new columns are created: one for the first bit, one for the second, and one for the third."
},
{
"code": null,
"e": 12741,
"s": 12674,
"text": "Each observation is encoded across the columns in its binary form."
},
{
"code": null,
"e": 12762,
"s": 12741,
"text": "Here’s how it looks:"
},
{
"code": null,
"e": 12842,
"s": 12762,
"text": "The first column has no variance, so it isn’t doing anything to help the model."
},
{
"code": null,
"e": 13054,
"s": 12842,
"text": "With only three levels, the information embedded becomes muddled. There are many collisions and the model can’t glean much information from the features. Just one-hot encode a column if it only has a few values."
},
{
"code": null,
"e": 13171,
"s": 13054,
"text": "In contrast, binary really shines when the cardinality of the column is higher — with the 50 US states, for example."
},
{
"code": null,
"e": 13341,
"s": 13171,
"text": "Binary encoding creates fewer columns than one-hot encoding. It is more memory efficient. It also reduces the chances of dimensionality problems with higher cardinality."
},
{
"code": null,
"e": 13630,
"s": 13341,
"text": "For ordinal data, most values that were close to each other when in ordinal form will share many of the same values in the new columns. Many machine learning algorithms can learn that the features are similar. Binary encoding is a decent compromise for ordinal data with high cardinality."
},
{
"code": null,
"e": 13798,
"s": 13630,
"text": "If you’ve used binary encoding successfully, please share in the comment. For nominal data a hashing algorithm with more fine-grained control usually makes more sense."
},
{
"code": null,
"e": 14111,
"s": 13798,
"text": "When the BaseN base = 1 it is basically the same as one hot encoding. When base = 2 it is basically the same as binary encoding. McGinnis said of this encoder, “Practically, this adds very little new functionality, rarely do people use base-3 or base-8 or any base other than ordinal or binary in real problems.”"
},
{
"code": null,
"e": 14506,
"s": 14111,
"text": "The main reason for BaseN’s existence is to possibly make grid searching easier. You could use BaseN with scikit-learn’s GridSearchCV. However, if you’re going to grid search with these encoding options, you can make the encoder part of your scikit-learn pipeline and put the options in your parameter grid. I don’t see a compelling reason to use BaseN. If you do, please share in the comments."
},
{
"code": null,
"e": 14588,
"s": 14506,
"text": "The default base for BaseNEncoder is 2, which is the equivalent of BinaryEncoder."
},
{
"code": null,
"e": 14954,
"s": 14588,
"text": "HashingEncoder implements the hashing trick. It is similar to one-hot encoding but with fewer new dimensions and some info loss due to collisions. The collisions do not significantly affect performance unless there is a great deal of overlap. An excellent discussion of the hashing trick and guidelines for selecting the number of output features can be found here."
},
{
"code": null,
"e": 15003,
"s": 14954,
"text": "Here’s the ordinal column again for a refresher."
},
{
"code": null,
"e": 15046,
"s": 15003,
"text": "And here’s the HashingEncoder with output."
},
{
"code": null,
"e": 15232,
"s": 15046,
"text": "The n_components parameter controls the number of expanded columns. The default is eight columns. In our example column with three values the default results in five columns full of 0s."
},
{
"code": null,
"e": 15376,
"s": 15232,
"text": "If you set n_components less than k you’ll have a small reduction in the value provided by the encoded data. You’ll also have fewer dimensions."
},
{
"code": null,
"e": 15640,
"s": 15376,
"text": "You can pass a hashing algorithm of your choice to HashingEncoder; the default is md5. Hashing algorithms have been very successful in some Kaggle competitions. It’s worth trying HashingEncoder for nominal and ordinal data if you have high cardinality features. 👍"
},
{
"code": null,
"e": 15721,
"s": 15640,
"text": "That’s all for now. Here’s a recap and suggestions for when to use the encoders."
},
{
"code": null,
"e": 15839,
"s": 15721,
"text": "For nominal columns try OneHot, Hashing, LeaveOneOut, and Target encoding. Avoid OneHot for high cardinality columns."
},
{
"code": null,
"e": 16071,
"s": 15839,
"text": "For ordinal columns try Ordinal (Integer), Binary, OneHot, LeaveOneOut, and Target. Helmert, Sum, BackwardDifference and Polynomial are less likely to be helpful, but if you have time or theoretic reason you might want to try them."
},
{
"code": null,
"e": 16257,
"s": 16071,
"text": "The Bayesian encoders can work well for some machine learning tasks. For example, Owen Zhang used the leave one out encoding method to perform well in a Kaggle classification challenge."
},
{
"code": null,
"e": 16381,
"s": 16257,
"text": "*Update April 2019: I updated this article to include information about forthcoming encoders and reworked the conclusion.**"
},
{
"code": null,
"e": 16510,
"s": 16381,
"text": "I write about data science, Python, SQL, and DevOps. Check out my other articles and follow me here if you’re into that stuff. 😀"
}
]
|
Reversing a List in Python - GeeksforGeeks | 19 Feb, 2022
Python provides us with various ways of reversing a list. We will go through few of the many techniques on how a list in python can be reversed. Examples:
Input : list = [10, 11, 12, 13, 14, 15]
Output : [15, 14, 13, 12, 11, 10]
Input : list = [4, 5, 6, 7, 8, 9]
Output : [9, 8, 7, 6, 5, 4]
Method 1: Using the reversed() built-in function. In this method, we neither reverse a list in-place(modify the original list), nor we create any copy of the list. Instead, we get a reverse iterator which we use to cycle through the list.
Python3
# Reversing a list using reversed()def Reverse(lst): return [ele for ele in reversed(lst)] # Driver Codelst = [10, 11, 12, 13, 14, 15]print(Reverse(lst))
Output:
[15, 14, 13, 12, 11, 10]
Method 2: Using the reverse() built-in function. Using the reverse() method we can reverse the contents of the list object in-place i.e., we don’t need to create a new list instead we just copy the existing elements to the original list in reverse order. This method directly modifies the original list.
Python3
# Reversing a list using reverse()def Reverse(lst): lst.reverse() return lst lst = [10, 11, 12, 13, 14, 15]print(Reverse(lst))
Output:
[15, 14, 13, 12, 11, 10]
Method 3: Using the slicing technique. In this technique, a copy of the list is made and the list is not sorted in-place. Creating a copy requires more space to hold all of the existing elements. This exhausts more memory.
Python3
# Reversing a list using slicing techniquedef Reverse(lst): new_lst = lst[::-1] return new_lst lst = [10, 11, 12, 13, 14, 15]print(Reverse(lst))
Output:
[15, 14, 13, 12, 11, 10]
To get a better understanding on the slicing technique refer Slicing Techniques in Python.
aminitindas
Python list-programs
python-list
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
How to Install PIP on Windows ?
Read a file line by line in Python
Enumerate() in Python
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Create a Pandas DataFrame from Lists
Python String | replace()
Reading and Writing to text files in Python | [
{
"code": null,
"e": 24040,
"s": 24012,
"text": "\n19 Feb, 2022"
},
{
"code": null,
"e": 24197,
"s": 24040,
"text": "Python provides us with various ways of reversing a list. We will go through few of the many techniques on how a list in python can be reversed. Examples: "
},
{
"code": null,
"e": 24334,
"s": 24197,
"text": "Input : list = [10, 11, 12, 13, 14, 15]\nOutput : [15, 14, 13, 12, 11, 10]\n\nInput : list = [4, 5, 6, 7, 8, 9]\nOutput : [9, 8, 7, 6, 5, 4]"
},
{
"code": null,
"e": 24577,
"s": 24336,
"text": "Method 1: Using the reversed() built-in function. In this method, we neither reverse a list in-place(modify the original list), nor we create any copy of the list. Instead, we get a reverse iterator which we use to cycle through the list. "
},
{
"code": null,
"e": 24585,
"s": 24577,
"text": "Python3"
},
{
"code": "# Reversing a list using reversed()def Reverse(lst): return [ele for ele in reversed(lst)] # Driver Codelst = [10, 11, 12, 13, 14, 15]print(Reverse(lst))",
"e": 24746,
"s": 24585,
"text": null
},
{
"code": null,
"e": 24756,
"s": 24746,
"text": "Output: "
},
{
"code": null,
"e": 24781,
"s": 24756,
"text": "[15, 14, 13, 12, 11, 10]"
},
{
"code": null,
"e": 25087,
"s": 24781,
"text": "Method 2: Using the reverse() built-in function. Using the reverse() method we can reverse the contents of the list object in-place i.e., we don’t need to create a new list instead we just copy the existing elements to the original list in reverse order. This method directly modifies the original list. "
},
{
"code": null,
"e": 25095,
"s": 25087,
"text": "Python3"
},
{
"code": "# Reversing a list using reverse()def Reverse(lst): lst.reverse() return lst lst = [10, 11, 12, 13, 14, 15]print(Reverse(lst))",
"e": 25232,
"s": 25095,
"text": null
},
{
"code": null,
"e": 25242,
"s": 25232,
"text": "Output: "
},
{
"code": null,
"e": 25267,
"s": 25242,
"text": "[15, 14, 13, 12, 11, 10]"
},
{
"code": null,
"e": 25492,
"s": 25267,
"text": "Method 3: Using the slicing technique. In this technique, a copy of the list is made and the list is not sorted in-place. Creating a copy requires more space to hold all of the existing elements. This exhausts more memory. "
},
{
"code": null,
"e": 25500,
"s": 25492,
"text": "Python3"
},
{
"code": "# Reversing a list using slicing techniquedef Reverse(lst): new_lst = lst[::-1] return new_lst lst = [10, 11, 12, 13, 14, 15]print(Reverse(lst))",
"e": 25655,
"s": 25500,
"text": null
},
{
"code": null,
"e": 25665,
"s": 25655,
"text": "Output: "
},
{
"code": null,
"e": 25690,
"s": 25665,
"text": "[15, 14, 13, 12, 11, 10]"
},
{
"code": null,
"e": 25782,
"s": 25690,
"text": "To get a better understanding on the slicing technique refer Slicing Techniques in Python. "
},
{
"code": null,
"e": 25794,
"s": 25782,
"text": "aminitindas"
},
{
"code": null,
"e": 25815,
"s": 25794,
"text": "Python list-programs"
},
{
"code": null,
"e": 25827,
"s": 25815,
"text": "python-list"
},
{
"code": null,
"e": 25834,
"s": 25827,
"text": "Python"
},
{
"code": null,
"e": 25846,
"s": 25834,
"text": "python-list"
},
{
"code": null,
"e": 25944,
"s": 25846,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25953,
"s": 25944,
"text": "Comments"
},
{
"code": null,
"e": 25966,
"s": 25953,
"text": "Old Comments"
},
{
"code": null,
"e": 25984,
"s": 25966,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26016,
"s": 25984,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26051,
"s": 26016,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26073,
"s": 26051,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26103,
"s": 26073,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 26145,
"s": 26103,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26188,
"s": 26145,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 26225,
"s": 26188,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 26251,
"s": 26225,
"text": "Python String | replace()"
}
]
|
What are different transaction isolation levels in DBMS? | In case of transaction the term ACID has been used significantly to state some of important properties that a transaction must follow. We all know ACID stands for Atomicity, Consistency, Isolation and Durability and these properties collectively called as ACID Properties.
Database system ensures ACID property −
Atomicity − Either all or none of the transaction operation is done.
Atomicity − Either all or none of the transaction operation is done.
Consistency − A transaction transfer from one consistent (correct) state to another consistent state.
Consistency − A transaction transfer from one consistent (correct) state to another consistent state.
Isolation − A transaction is isolated from other transactions. i.e. A transaction is not affected by another transaction. Although multiple transactions execute concurrently it must appear as if the transaction are running serially (one after the other).
Isolation − A transaction is isolated from other transactions. i.e. A transaction is not affected by another transaction. Although multiple transactions execute concurrently it must appear as if the transaction are running serially (one after the other).
Durability − The results of transactions are permanent i.e. the result will never be lost with subsequent failure, durability refers to long lasting i.e. permanency.
Durability − The results of transactions are permanent i.e. the result will never be lost with subsequent failure, durability refers to long lasting i.e. permanency.
It determines the visibility of transactions of other systems. A lower level allows every user to access the same data. Therefore, it involves high risk of data privacy and security of the system. However, a higher isolation level reduces the type of concurrency over the data but requires more resources and is slower than lower isolation levels.
The isolation protocols help safeguards the data from unwanted transactions. They maintain the integrity of every data by defining how and when the changes made by one operation are visible to others.
There are four levels of isolations which are explained below −
Read Uncommitted − It is the lowest level of isolation. At this level; the dirty reads are allowed, which means one can read the uncommitted changes made by another.
Read Uncommitted − It is the lowest level of isolation. At this level; the dirty reads are allowed, which means one can read the uncommitted changes made by another.
Read committed − It allows no dirty reads, and clearly states that any uncommitted data is committed now it is read.
Read committed − It allows no dirty reads, and clearly states that any uncommitted data is committed now it is read.
Repeatable Read − This is the most restricted level of isolation. The transaction holds read locks on all the rows it references and write locks over all the rows it updates/inserts/deletes. So, there is no chance of non-repeatable reads.
Repeatable Read − This is the most restricted level of isolation. The transaction holds read locks on all the rows it references and write locks over all the rows it updates/inserts/deletes. So, there is no chance of non-repeatable reads.
Serializable − The highest level of civilization. It determines that all concurrent transactions be executed serially.
Serializable − The highest level of civilization. It determines that all concurrent transactions be executed serially.
Consider an example of isolation.
What is the isolation level of transaction E?
session begins
SET GLOBAL TRANSACTION
ISOLATION LEVEL SERIALIZABLE;
session ends
session begins
SET SESSION TRANSACTION
ISOLATION LEVEL REPEATABLE READ;
transaction A
transaction B
SET TRANSACTION
ISOLATION LEVEL READ UNCOMMITTED;
transaction C
SET TRANSACTION
ISOLATION LEVEL READ COMMITTED;
transaction D
transaction E
session ends
Check which option −
A- Serializable
B- Repeatable read
C- Read uncommitted
Repeatable Read is the right answer.
Step 1 − In the above program, the first session starts and ends without doing any transaction.
Step 1 − In the above program, the first session starts and ends without doing any transaction.
Step 2 − The second session begins at session-level with isolation level "Repeatable Read". Transaction A & B gets executed with these settings.
Step 2 − The second session begins at session-level with isolation level "Repeatable Read". Transaction A & B gets executed with these settings.
Step 3 − Once again a new transaction begins with isolation level "Read uncommitted". This setting is used only for "Transaction C" since "Set transaction" alone is mentioned. If the "SET transaction" is used without global or session keywords, then these particular settings will work only for a single transaction.
Step 3 − Once again a new transaction begins with isolation level "Read uncommitted". This setting is used only for "Transaction C" since "Set transaction" alone is mentioned. If the "SET transaction" is used without global or session keywords, then these particular settings will work only for a single transaction.
Step 4 − Once again "Set Transaction" with isolation level Read committed works only for Transaction D. (Refer step 3 for reason)
Step 4 − Once again "Set Transaction" with isolation level Read committed works only for Transaction D. (Refer step 3 for reason)
Step 5 − "Transaction E" gets continued at the "Repeatable Read" since the transaction started at step 2 has not ended still. Transaction isolation level set at Step 3 and Step 4 vanishes once a single transaction is executed. So, automatically "Transaction E" will refer to the prior transaction settings.
Step 5 − "Transaction E" gets continued at the "Repeatable Read" since the transaction started at step 2 has not ended still. Transaction isolation level set at Step 3 and Step 4 vanishes once a single transaction is executed. So, automatically "Transaction E" will refer to the prior transaction settings. | [
{
"code": null,
"e": 1335,
"s": 1062,
"text": "In case of transaction the term ACID has been used significantly to state some of important properties that a transaction must follow. We all know ACID stands for Atomicity, Consistency, Isolation and Durability and these properties collectively called as ACID Properties."
},
{
"code": null,
"e": 1375,
"s": 1335,
"text": "Database system ensures ACID property −"
},
{
"code": null,
"e": 1444,
"s": 1375,
"text": "Atomicity − Either all or none of the transaction operation is done."
},
{
"code": null,
"e": 1513,
"s": 1444,
"text": "Atomicity − Either all or none of the transaction operation is done."
},
{
"code": null,
"e": 1615,
"s": 1513,
"text": "Consistency − A transaction transfer from one consistent (correct) state to another consistent state."
},
{
"code": null,
"e": 1717,
"s": 1615,
"text": "Consistency − A transaction transfer from one consistent (correct) state to another consistent state."
},
{
"code": null,
"e": 1972,
"s": 1717,
"text": "Isolation − A transaction is isolated from other transactions. i.e. A transaction is not affected by another transaction. Although multiple transactions execute concurrently it must appear as if the transaction are running serially (one after the other)."
},
{
"code": null,
"e": 2227,
"s": 1972,
"text": "Isolation − A transaction is isolated from other transactions. i.e. A transaction is not affected by another transaction. Although multiple transactions execute concurrently it must appear as if the transaction are running serially (one after the other)."
},
{
"code": null,
"e": 2393,
"s": 2227,
"text": "Durability − The results of transactions are permanent i.e. the result will never be lost with subsequent failure, durability refers to long lasting i.e. permanency."
},
{
"code": null,
"e": 2559,
"s": 2393,
"text": "Durability − The results of transactions are permanent i.e. the result will never be lost with subsequent failure, durability refers to long lasting i.e. permanency."
},
{
"code": null,
"e": 2907,
"s": 2559,
"text": "It determines the visibility of transactions of other systems. A lower level allows every user to access the same data. Therefore, it involves high risk of data privacy and security of the system. However, a higher isolation level reduces the type of concurrency over the data but requires more resources and is slower than lower isolation levels."
},
{
"code": null,
"e": 3108,
"s": 2907,
"text": "The isolation protocols help safeguards the data from unwanted transactions. They maintain the integrity of every data by defining how and when the changes made by one operation are visible to others."
},
{
"code": null,
"e": 3172,
"s": 3108,
"text": "There are four levels of isolations which are explained below −"
},
{
"code": null,
"e": 3338,
"s": 3172,
"text": "Read Uncommitted − It is the lowest level of isolation. At this level; the dirty reads are allowed, which means one can read the uncommitted changes made by another."
},
{
"code": null,
"e": 3504,
"s": 3338,
"text": "Read Uncommitted − It is the lowest level of isolation. At this level; the dirty reads are allowed, which means one can read the uncommitted changes made by another."
},
{
"code": null,
"e": 3621,
"s": 3504,
"text": "Read committed − It allows no dirty reads, and clearly states that any uncommitted data is committed now it is read."
},
{
"code": null,
"e": 3738,
"s": 3621,
"text": "Read committed − It allows no dirty reads, and clearly states that any uncommitted data is committed now it is read."
},
{
"code": null,
"e": 3977,
"s": 3738,
"text": "Repeatable Read − This is the most restricted level of isolation. The transaction holds read locks on all the rows it references and write locks over all the rows it updates/inserts/deletes. So, there is no chance of non-repeatable reads."
},
{
"code": null,
"e": 4216,
"s": 3977,
"text": "Repeatable Read − This is the most restricted level of isolation. The transaction holds read locks on all the rows it references and write locks over all the rows it updates/inserts/deletes. So, there is no chance of non-repeatable reads."
},
{
"code": null,
"e": 4335,
"s": 4216,
"text": "Serializable − The highest level of civilization. It determines that all concurrent transactions be executed serially."
},
{
"code": null,
"e": 4454,
"s": 4335,
"text": "Serializable − The highest level of civilization. It determines that all concurrent transactions be executed serially."
},
{
"code": null,
"e": 4488,
"s": 4454,
"text": "Consider an example of isolation."
},
{
"code": null,
"e": 4534,
"s": 4488,
"text": "What is the isolation level of transaction E?"
},
{
"code": null,
"e": 4549,
"s": 4534,
"text": "session begins"
},
{
"code": null,
"e": 4572,
"s": 4549,
"text": "SET GLOBAL TRANSACTION"
},
{
"code": null,
"e": 4602,
"s": 4572,
"text": "ISOLATION LEVEL SERIALIZABLE;"
},
{
"code": null,
"e": 4630,
"s": 4602,
"text": "session ends\nsession begins"
},
{
"code": null,
"e": 4654,
"s": 4630,
"text": "SET SESSION TRANSACTION"
},
{
"code": null,
"e": 4687,
"s": 4654,
"text": "ISOLATION LEVEL REPEATABLE READ;"
},
{
"code": null,
"e": 4715,
"s": 4687,
"text": "transaction A\ntransaction B"
},
{
"code": null,
"e": 4731,
"s": 4715,
"text": "SET TRANSACTION"
},
{
"code": null,
"e": 4765,
"s": 4731,
"text": "ISOLATION LEVEL READ UNCOMMITTED;"
},
{
"code": null,
"e": 4779,
"s": 4765,
"text": "transaction C"
},
{
"code": null,
"e": 4795,
"s": 4779,
"text": "SET TRANSACTION"
},
{
"code": null,
"e": 4827,
"s": 4795,
"text": "ISOLATION LEVEL READ COMMITTED;"
},
{
"code": null,
"e": 4868,
"s": 4827,
"text": "transaction D\ntransaction E\nsession ends"
},
{
"code": null,
"e": 4889,
"s": 4868,
"text": "Check which option −"
},
{
"code": null,
"e": 4944,
"s": 4889,
"text": "A- Serializable\nB- Repeatable read\nC- Read uncommitted"
},
{
"code": null,
"e": 4981,
"s": 4944,
"text": "Repeatable Read is the right answer."
},
{
"code": null,
"e": 5077,
"s": 4981,
"text": "Step 1 − In the above program, the first session starts and ends without doing any transaction."
},
{
"code": null,
"e": 5173,
"s": 5077,
"text": "Step 1 − In the above program, the first session starts and ends without doing any transaction."
},
{
"code": null,
"e": 5318,
"s": 5173,
"text": "Step 2 − The second session begins at session-level with isolation level \"Repeatable Read\". Transaction A & B gets executed with these settings."
},
{
"code": null,
"e": 5463,
"s": 5318,
"text": "Step 2 − The second session begins at session-level with isolation level \"Repeatable Read\". Transaction A & B gets executed with these settings."
},
{
"code": null,
"e": 5780,
"s": 5463,
"text": "Step 3 − Once again a new transaction begins with isolation level \"Read uncommitted\". This setting is used only for \"Transaction C\" since \"Set transaction\" alone is mentioned. If the \"SET transaction\" is used without global or session keywords, then these particular settings will work only for a single transaction."
},
{
"code": null,
"e": 6097,
"s": 5780,
"text": "Step 3 − Once again a new transaction begins with isolation level \"Read uncommitted\". This setting is used only for \"Transaction C\" since \"Set transaction\" alone is mentioned. If the \"SET transaction\" is used without global or session keywords, then these particular settings will work only for a single transaction."
},
{
"code": null,
"e": 6227,
"s": 6097,
"text": "Step 4 − Once again \"Set Transaction\" with isolation level Read committed works only for Transaction D. (Refer step 3 for reason)"
},
{
"code": null,
"e": 6357,
"s": 6227,
"text": "Step 4 − Once again \"Set Transaction\" with isolation level Read committed works only for Transaction D. (Refer step 3 for reason)"
},
{
"code": null,
"e": 6664,
"s": 6357,
"text": "Step 5 − \"Transaction E\" gets continued at the \"Repeatable Read\" since the transaction started at step 2 has not ended still. Transaction isolation level set at Step 3 and Step 4 vanishes once a single transaction is executed. So, automatically \"Transaction E\" will refer to the prior transaction settings."
},
{
"code": null,
"e": 6971,
"s": 6664,
"text": "Step 5 − \"Transaction E\" gets continued at the \"Repeatable Read\" since the transaction started at step 2 has not ended still. Transaction isolation level set at Step 3 and Step 4 vanishes once a single transaction is executed. So, automatically \"Transaction E\" will refer to the prior transaction settings."
}
]
|
Find the day number in the current year for the given date - GeeksforGeeks | 08 Jun, 2021
Given a string str which represents a date formatted as YYYY-MM-DD, the task is to find the day number for the current year. For example, 1st January is the 1st day of the year, 2nd January is the 2nd day of the year, 1st February is the 32nd day of the year and so on.Examples:
Input: str = “2019-01-09” Output: 9Input: str = “2003-03-01” Output: 60
Approach:
Extract the year, month and the day from the given date and store them in variables year, month and day.
Create an array days[] where days[i] will store the number of days in the ith month.
Update count = days[0] + days[1] + ... + days[month – 1] to get the count of all the past days of previous months.
If the given year is a leap year then increment this count by 1 in order to count 29th February.
Finally, add day to the count which is number of the day in the current month and print the final count.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; int days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; // Function to return the day number// of the year for the given dateint dayOfYear(string date){ // Extract the year, month and the // day from the date string int year = stoi(date.substr(0, 4)); int month = stoi(date.substr(5, 2)); int day = stoi(date.substr(8)); // If current year is a leap year and the date // given is after the 28th of February then // it must include the 29th February if (month > 2 && year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) { ++day; } // Add the days in the previous months while (month-- > 0) { day = day + days[month - 1]; } return day;} // Driver codeint main(){ string date = "2019-01-09"; cout << dayOfYear(date); return 0;}
// Java implementation of the approachclass GFG{ static int days [] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; // Function to return the day number // of the year for the given date static int dayOfYear(String date) { // Extract the year, month and the // day from the date string int year = Integer.parseInt(date.substring(0, 4)); int month = Integer.parseInt(date.substring(5, 7)); int day = Integer.parseInt(date.substring(8)); // If current year is a leap year and the date // given is after the 28th of February then // it must include the 29th February if (month > 2 && year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) { ++day; } // Add the days in the previous months while (--month > 0) { day = day + days[month - 1]; } return day; } // Driver code public static void main (String[] args) { String date = "2019-01-09"; System.out.println(dayOfYear(date)); }} // This code is contributed by ihritik
# Python3 implementation of the approachdays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; # Function to return the day number# of the year for the given datedef dayOfYear(date): # Extract the year, month and the # day from the date string year = (int)(date[0:4]); month = (int)(date[5:7]); day = (int)(date[8:]); # If current year is a leap year and the date # given is after the 28th of February then # it must include the 29th February if (month > 2 and year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)): day += 1; # Add the days in the previous months month -= 1; while (month > 0): day = day + days[month - 1]; month -= 1; return day; # Driver codeif __name__ == '__main__': date = "2019-01-09"; print(dayOfYear(date)); # This code is contributed by Rajput-Ji
// C# implementation of the approachusing System; class GFG{ static int [] days = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; // Function to return the day number // of the year for the given date static int dayOfYear(string date) { // Extract the year, month and the // day from the date string int year = Int32.Parse(date.Substring(0, 4)); int month = Int32.Parse(date.Substring(5, 2)); int day = Int32.Parse(date.Substring(8)); // If current year is a leap year and the date // given is after the 28th of February then // it must include the 29th February if (month > 2 && year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) { ++day; } // Add the days in the previous months while (--month > 0) { day = day + days[month - 1]; } return day; } // Driver code public static void Main () { String date = "2019-01-09"; Console.WriteLine(dayOfYear(date)); }} // This code is contributed by ihritik
<script> // Javascript implementation of the approach var days= [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ]; // Function to return the day number// of the year for the given datefunction dayOfYear( date){ // Extract the year, month and the // day from the date string var year = parseInt(date.substring(0, 4)); var month = parseInt(date.substring(5, 6)); var day = parseInt(date.substring(8)); // If current year is a leap year and the date // given is after the 28th of February then // it must include the 29th February if (month > 2 && year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) { ++day; } // Add the days in the previous months while (month-- > 0) { day = day + days[month - 1]; } return day;} // Driver codevar date = "2019-01-09";document.write( dayOfYear(date)); // This code is contributed by rutvik_56.</script>
9
ihritik
Rajput-Ji
rutvik_56
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Algorithm to solve Rubik's Cube
Program to convert a given number to words
Program to multiply two matrices
Modular multiplicative inverse
Program to print prime numbers from 1 to N.
Count ways to reach the n'th stair
Check if a number is Palindrome
Singular Value Decomposition (SVD)
Fizz Buzz Implementation
Find first and last digits of a number | [
{
"code": null,
"e": 24612,
"s": 24584,
"text": "\n08 Jun, 2021"
},
{
"code": null,
"e": 24893,
"s": 24612,
"text": "Given a string str which represents a date formatted as YYYY-MM-DD, the task is to find the day number for the current year. For example, 1st January is the 1st day of the year, 2nd January is the 2nd day of the year, 1st February is the 32nd day of the year and so on.Examples: "
},
{
"code": null,
"e": 24967,
"s": 24893,
"text": "Input: str = “2019-01-09” Output: 9Input: str = “2003-03-01” Output: 60 "
},
{
"code": null,
"e": 24981,
"s": 24969,
"text": "Approach: "
},
{
"code": null,
"e": 25086,
"s": 24981,
"text": "Extract the year, month and the day from the given date and store them in variables year, month and day."
},
{
"code": null,
"e": 25171,
"s": 25086,
"text": "Create an array days[] where days[i] will store the number of days in the ith month."
},
{
"code": null,
"e": 25286,
"s": 25171,
"text": "Update count = days[0] + days[1] + ... + days[month – 1] to get the count of all the past days of previous months."
},
{
"code": null,
"e": 25383,
"s": 25286,
"text": "If the given year is a leap year then increment this count by 1 in order to count 29th February."
},
{
"code": null,
"e": 25488,
"s": 25383,
"text": "Finally, add day to the count which is number of the day in the current month and print the final count."
},
{
"code": null,
"e": 25541,
"s": 25488,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25545,
"s": 25541,
"text": "C++"
},
{
"code": null,
"e": 25550,
"s": 25545,
"text": "Java"
},
{
"code": null,
"e": 25558,
"s": 25550,
"text": "Python3"
},
{
"code": null,
"e": 25561,
"s": 25558,
"text": "C#"
},
{
"code": null,
"e": 25572,
"s": 25561,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; int days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; // Function to return the day number// of the year for the given dateint dayOfYear(string date){ // Extract the year, month and the // day from the date string int year = stoi(date.substr(0, 4)); int month = stoi(date.substr(5, 2)); int day = stoi(date.substr(8)); // If current year is a leap year and the date // given is after the 28th of February then // it must include the 29th February if (month > 2 && year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) { ++day; } // Add the days in the previous months while (month-- > 0) { day = day + days[month - 1]; } return day;} // Driver codeint main(){ string date = \"2019-01-09\"; cout << dayOfYear(date); return 0;}",
"e": 26479,
"s": 25572,
"text": null
},
{
"code": "// Java implementation of the approachclass GFG{ static int days [] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; // Function to return the day number // of the year for the given date static int dayOfYear(String date) { // Extract the year, month and the // day from the date string int year = Integer.parseInt(date.substring(0, 4)); int month = Integer.parseInt(date.substring(5, 7)); int day = Integer.parseInt(date.substring(8)); // If current year is a leap year and the date // given is after the 28th of February then // it must include the 29th February if (month > 2 && year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) { ++day; } // Add the days in the previous months while (--month > 0) { day = day + days[month - 1]; } return day; } // Driver code public static void main (String[] args) { String date = \"2019-01-09\"; System.out.println(dayOfYear(date)); }} // This code is contributed by ihritik",
"e": 27658,
"s": 26479,
"text": null
},
{
"code": "# Python3 implementation of the approachdays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; # Function to return the day number# of the year for the given datedef dayOfYear(date): # Extract the year, month and the # day from the date string year = (int)(date[0:4]); month = (int)(date[5:7]); day = (int)(date[8:]); # If current year is a leap year and the date # given is after the 28th of February then # it must include the 29th February if (month > 2 and year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)): day += 1; # Add the days in the previous months month -= 1; while (month > 0): day = day + days[month - 1]; month -= 1; return day; # Driver codeif __name__ == '__main__': date = \"2019-01-09\"; print(dayOfYear(date)); # This code is contributed by Rajput-Ji",
"e": 28521,
"s": 27658,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ static int [] days = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; // Function to return the day number // of the year for the given date static int dayOfYear(string date) { // Extract the year, month and the // day from the date string int year = Int32.Parse(date.Substring(0, 4)); int month = Int32.Parse(date.Substring(5, 2)); int day = Int32.Parse(date.Substring(8)); // If current year is a leap year and the date // given is after the 28th of February then // it must include the 29th February if (month > 2 && year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) { ++day; } // Add the days in the previous months while (--month > 0) { day = day + days[month - 1]; } return day; } // Driver code public static void Main () { String date = \"2019-01-09\"; Console.WriteLine(dayOfYear(date)); }} // This code is contributed by ihritik",
"e": 29696,
"s": 28521,
"text": null
},
{
"code": "<script> // Javascript implementation of the approach var days= [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ]; // Function to return the day number// of the year for the given datefunction dayOfYear( date){ // Extract the year, month and the // day from the date string var year = parseInt(date.substring(0, 4)); var month = parseInt(date.substring(5, 6)); var day = parseInt(date.substring(8)); // If current year is a leap year and the date // given is after the 28th of February then // it must include the 29th February if (month > 2 && year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) { ++day; } // Add the days in the previous months while (month-- > 0) { day = day + days[month - 1]; } return day;} // Driver codevar date = \"2019-01-09\";document.write( dayOfYear(date)); // This code is contributed by rutvik_56.</script>",
"e": 30614,
"s": 29696,
"text": null
},
{
"code": null,
"e": 30616,
"s": 30614,
"text": "9"
},
{
"code": null,
"e": 30626,
"s": 30618,
"text": "ihritik"
},
{
"code": null,
"e": 30636,
"s": 30626,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 30646,
"s": 30636,
"text": "rutvik_56"
},
{
"code": null,
"e": 30659,
"s": 30646,
"text": "Mathematical"
},
{
"code": null,
"e": 30672,
"s": 30659,
"text": "Mathematical"
},
{
"code": null,
"e": 30770,
"s": 30672,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30779,
"s": 30770,
"text": "Comments"
},
{
"code": null,
"e": 30792,
"s": 30779,
"text": "Old Comments"
},
{
"code": null,
"e": 30824,
"s": 30792,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 30867,
"s": 30824,
"text": "Program to convert a given number to words"
},
{
"code": null,
"e": 30900,
"s": 30867,
"text": "Program to multiply two matrices"
},
{
"code": null,
"e": 30931,
"s": 30900,
"text": "Modular multiplicative inverse"
},
{
"code": null,
"e": 30975,
"s": 30931,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 31010,
"s": 30975,
"text": "Count ways to reach the n'th stair"
},
{
"code": null,
"e": 31042,
"s": 31010,
"text": "Check if a number is Palindrome"
},
{
"code": null,
"e": 31077,
"s": 31042,
"text": "Singular Value Decomposition (SVD)"
},
{
"code": null,
"e": 31102,
"s": 31077,
"text": "Fizz Buzz Implementation"
}
]
|
PHP - Ajax XML Parser | Using with Ajax we can parser xml from local directory as well as servers, Below example demonstrate how to parser xml with web browser.
<html>
<head>
<script>
function showCD(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","getcourse.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
Select a Course:
<select name = "cds" onchange = "showCD(this.value)">
<option value = "">Select a course:</option>
<option value = "Android">Android </option>
<option value = "Html">HTML</option>
<option value = "Java">Java</option>
<option value = "Microsoft">MS technologies</option>
</select>
</form>
<div id = "txtHint"><b>Course info will be listed here...</b></div>
</body>
</html>
The above example will call getcourse.php using with GET method. getcourse.php file loads catalog.xml. getcourse.php is as shown below −
<?php
$q = $_GET["q"];
$xmlDoc = new DOMDocument();
$xmlDoc->load("catalog.xml");
$x = $xmlDoc->getElementsByTagName('COURSE');
for ($i = 0; $i<=$x->length-1; $i++) {
=
if ($x->item($i)->nodeType == 1) {
if ($x->item($i)->childNodes->item(0)->nodeValue == $q) {
$y = ($x->item($i)->parentNode);
}
}
}
$cd = ($y->childNodes);
for ($i = 0;$i<$cd->length;$i++) {
if ($cd->item($i)->nodeType == 1) {
echo("<b>" . $cd->item($i)->nodeName . ":</b> ");
echo($cd->item($i)->childNodes->item(0)->nodeValue);
echo("<br>");
}
}
?>
XML file having list of courses and details.This file is accessed by getcourse.php
<CATALOG>
<SUBJECT>
<COURSE>Android</COURSE>
<COUNTRY>India</COUNTRY>
<COMPANY>TutorialsPoint</COMPANY>
<PRICE>$10</PRICE>
<YEAR>2015</YEAR>
</SUBJECT>
<SUBJECT>
<COURSE>Html</COURSE>
<COUNTRY>India</COUNTRY>
<COMPANY>TutorialsPoint</COMPANY>
<PRICE>$15</PRICE>
<YEAR>2015</YEAR>
</SUBJECT>
<SUBJECT>
<COURSE>Java</COURSE>
<COUNTRY>India</COUNTRY>
<COMPANY>TutorialsPoint</COMPANY>
<PRICE>$20</PRICE>
<YEAR>2015</YEAR>
</SUBJECT>
<SUBJECT>
<COURSE>Microsoft</COURSE>
<COUNTRY>India</COUNTRY>
<COMPANY>TutorialsPoint</COMPANY>
<PRICE>$25</PRICE>
<YEAR>2015</YEAR>
</SUBJECT>
</CATALOG>
It will produce the following result −
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": 2894,
"s": 2757,
"text": "Using with Ajax we can parser xml from local directory as well as servers, Below example demonstrate how to parser xml with web browser."
},
{
"code": null,
"e": 4318,
"s": 2894,
"text": "<html>\n <head>\n \n <script>\n function showCD(str) {\n if (str == \"\") {\n document.getElementById(\"txtHint\").innerHTML = \"\";\n return;\n }\n \n if (window.XMLHttpRequest) {\n // code for IE7+, Firefox, Chrome, Opera, Safari\n xmlhttp = new XMLHttpRequest();\n }else { \n // code for IE6, IE5\n xmlhttp = new ActiveXObject(\"Microsoft.XMLHTTP\");\n }\n \n xmlhttp.onreadystatechange = function() {\n if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {\n document.getElementById(\"txtHint\").innerHTML = xmlhttp.responseText;\n }\n }\n xmlhttp.open(\"GET\",\"getcourse.php?q=\"+str,true);\n xmlhttp.send();\n }\n </script>\n \n </head>\n <body>\n \n <form>\n Select a Course:\n <select name = \"cds\" onchange = \"showCD(this.value)\">\n <option value = \"\">Select a course:</option>\n <option value = \"Android\">Android </option>\n <option value = \"Html\">HTML</option>\n <option value = \"Java\">Java</option>\n <option value = \"Microsoft\">MS technologies</option>\n </select>\n </form>\n \n <div id = \"txtHint\"><b>Course info will be listed here...</b></div>\n \n </body>\n</html>"
},
{
"code": null,
"e": 4455,
"s": 4318,
"text": "The above example will call getcourse.php using with GET method. getcourse.php file loads catalog.xml. getcourse.php is as shown below −"
},
{
"code": null,
"e": 5107,
"s": 4455,
"text": "<?php\n $q = $_GET[\"q\"];\n \n $xmlDoc = new DOMDocument();\n $xmlDoc->load(\"catalog.xml\");\n \n $x = $xmlDoc->getElementsByTagName('COURSE');\n \n for ($i = 0; $i<=$x->length-1; $i++) {\n =\n if ($x->item($i)->nodeType == 1) {\n if ($x->item($i)->childNodes->item(0)->nodeValue == $q) {\n $y = ($x->item($i)->parentNode);\n }\n }\n }\n\t\n $cd = ($y->childNodes);\n \n for ($i = 0;$i<$cd->length;$i++) {\n if ($cd->item($i)->nodeType == 1) {\n echo(\"<b>\" . $cd->item($i)->nodeName . \":</b> \");\n echo($cd->item($i)->childNodes->item(0)->nodeValue);\n echo(\"<br>\");\n }\n }\n?>"
},
{
"code": null,
"e": 5190,
"s": 5107,
"text": "XML file having list of courses and details.This file is accessed by getcourse.php"
},
{
"code": null,
"e": 5931,
"s": 5190,
"text": "<CATALOG>\n <SUBJECT>\n <COURSE>Android</COURSE>\n <COUNTRY>India</COUNTRY>\n <COMPANY>TutorialsPoint</COMPANY>\n <PRICE>$10</PRICE>\n <YEAR>2015</YEAR>\n </SUBJECT>\n \n <SUBJECT>\n <COURSE>Html</COURSE>\n <COUNTRY>India</COUNTRY>\n <COMPANY>TutorialsPoint</COMPANY>\n <PRICE>$15</PRICE>\n <YEAR>2015</YEAR>\n </SUBJECT>\n \n <SUBJECT>\n <COURSE>Java</COURSE>\n <COUNTRY>India</COUNTRY>\n <COMPANY>TutorialsPoint</COMPANY>\n <PRICE>$20</PRICE>\n <YEAR>2015</YEAR>\n </SUBJECT>\n \n <SUBJECT>\n <COURSE>Microsoft</COURSE>\n <COUNTRY>India</COUNTRY>\n <COMPANY>TutorialsPoint</COMPANY>\n <PRICE>$25</PRICE>\n <YEAR>2015</YEAR>\n </SUBJECT>\n</CATALOG>"
},
{
"code": null,
"e": 5970,
"s": 5931,
"text": "It will produce the following result −"
},
{
"code": null,
"e": 6003,
"s": 5970,
"text": "\n 45 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 6019,
"s": 6003,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 6052,
"s": 6019,
"text": "\n 34 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 6063,
"s": 6052,
"text": " Syed Raza"
},
{
"code": null,
"e": 6098,
"s": 6063,
"text": "\n 84 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 6115,
"s": 6098,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 6148,
"s": 6115,
"text": "\n 17 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6163,
"s": 6148,
"text": " Nivedita Jain"
},
{
"code": null,
"e": 6198,
"s": 6163,
"text": "\n 100 Lectures \n 34 hours \n"
},
{
"code": null,
"e": 6210,
"s": 6198,
"text": " Azaz Patel"
},
{
"code": null,
"e": 6245,
"s": 6210,
"text": "\n 43 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 6273,
"s": 6245,
"text": " Vijay Kumar Parvatha Reddy"
},
{
"code": null,
"e": 6280,
"s": 6273,
"text": " Print"
},
{
"code": null,
"e": 6291,
"s": 6280,
"text": " Add Notes"
}
]
|
Biopython - Machine Learning | Bioinformatics is an excellent area to apply machine learning algorithms. Here, we have genetic information of large number of organisms and it is not possible to manually analyze all this information. If proper machine learning algorithm is used, we can extract lot of useful information from these data. Biopython provides useful set of algorithm to do supervised machine learning.
Supervised learning is based on input variable (X) and output variable (Y). It uses an algorithm to learn the mapping function from the input to the output. It is defined below −
Y = f(X)
The main objective of this approach is to approximate the mapping function and when you have new input data (x), you can predict the output variables (Y) for that data.
Logistic regression is a supervised machine Learning algorithm. It is used to find out the difference between K classes using weighted sum of predictor variables. It computes the probability of an event occurrence and can be used for cancer detection.
Biopython provides Bio.LogisticRegression module to predict variables based on Logistic regression algorithm. Currently, Biopython implements logistic regression algorithm for two classes only (K = 2).
k-Nearest neighbors is also a supervised machine learning algorithm. It works by categorizing the data based on nearest neighbors. Biopython provides Bio.KNN module to predict variables based on k-nearest neighbors algorithm.
Naive Bayes classifiers are a collection of classification algorithms based on Bayes’ Theorem. It is not a single algorithm but a family of algorithms where all of them share a common principle, i.e. every pair of features being classified is independent of each other. Biopython provides Bio.NaiveBayes module to work with Naive Bayes algorithm.
A Markov model is a mathematical system defined as a collection of random variables, that experiences transition from one state to another according to certain probabilistic rules. Biopython provides Bio.MarkovModel and Bio.HMM.MarkovModel modules to work with Markov models.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2490,
"s": 2106,
"text": "Bioinformatics is an excellent area to apply machine learning algorithms. Here, we have genetic information of large number of organisms and it is not possible to manually analyze all this information. If proper machine learning algorithm is used, we can extract lot of useful information from these data. Biopython provides useful set of algorithm to do supervised machine learning."
},
{
"code": null,
"e": 2669,
"s": 2490,
"text": "Supervised learning is based on input variable (X) and output variable (Y). It uses an algorithm to learn the mapping function from the input to the output. It is defined below −"
},
{
"code": null,
"e": 2679,
"s": 2669,
"text": "Y = f(X)\n"
},
{
"code": null,
"e": 2848,
"s": 2679,
"text": "The main objective of this approach is to approximate the mapping function and when you have new input data (x), you can predict the output variables (Y) for that data."
},
{
"code": null,
"e": 3100,
"s": 2848,
"text": "Logistic regression is a supervised machine Learning algorithm. It is used to find out the difference between K classes using weighted sum of predictor variables. It computes the probability of an event occurrence and can be used for cancer detection."
},
{
"code": null,
"e": 3302,
"s": 3100,
"text": "Biopython provides Bio.LogisticRegression module to predict variables based on Logistic regression algorithm. Currently, Biopython implements logistic regression algorithm for two classes only (K = 2)."
},
{
"code": null,
"e": 3528,
"s": 3302,
"text": "k-Nearest neighbors is also a supervised machine learning algorithm. It works by categorizing the data based on nearest neighbors. Biopython provides Bio.KNN module to predict variables based on k-nearest neighbors algorithm."
},
{
"code": null,
"e": 3875,
"s": 3528,
"text": "Naive Bayes classifiers are a collection of classification algorithms based on Bayes’ Theorem. It is not a single algorithm but a family of algorithms where all of them share a common principle, i.e. every pair of features being classified is independent of each other. Biopython provides Bio.NaiveBayes module to work with Naive Bayes algorithm."
},
{
"code": null,
"e": 4151,
"s": 3875,
"text": "A Markov model is a mathematical system defined as a collection of random variables, that experiences transition from one state to another according to certain probabilistic rules. Biopython provides Bio.MarkovModel and Bio.HMM.MarkovModel modules to work with Markov models."
},
{
"code": null,
"e": 4158,
"s": 4151,
"text": " Print"
},
{
"code": null,
"e": 4169,
"s": 4158,
"text": " Add Notes"
}
]
|
Amsterdam Airbnb dataset: An End-to-End Project | by Rob | Towards Data Science | A Data Science portfolio project is like studying for your driving license practical exam, you are not learning to drive, you are learning how to pass the exam.
When preparing your portfolio it’s important to have projects that cover different fields, techniques and are able to tell a story.
In this article, my main goal is to show how I would do a data science portfolio project that covers visualization, data preprocessing, modeling and final considerations along with production suggestions.
I am using the Amsterdam Airbnb dataset for predicting the price of a flat given a list of predictors.
The dataset once imported into Python is analyzed using pandas_profiling a very useful tool that extends the df.info() functionality in pandas.
As described in the report, the dataset contains 14 variables, 10 are numeric and 2 categorical (we will probably need to get dummy variables for those when modeling).
Moreover, according to the report variable host_listings_count and calculated_host_listings_count are highly correlated with a Pearson score of 0.94, hence we will discard the former to avoid multicollinearity problems.
We can see that our target variable price is not a number, let’s have a look to the longest one, in order to understand if there are any formatting applied that needs to be removed before converting:
max(df[‘price’].values, key = len)>>> '$1,305.00'
First of all, we can see our target variable has 2 different characters we need to get rid of, the $ symbol and the comma identifying the thousands. let’s get rid of them by using the df.apply().
df[‘price’] = df[‘price’].apply(lambda x: x.replace(‘$’, ‘’))df[‘price’] = df[‘price’].apply(lambda x: x.replace(‘,’, ‘’))df[‘price’] = pd.to_numeric(df[‘price’])
The dataset has two columns containing pieces of information about coordinates where the flat is located, plus we have our target variable. Hence we can create a heatmap to better understand where flats are located and how the price is affected by the location
To achieve we will use gmaps , a python package to create interactive maps using Google Maps.
You can use the free version, without an API key, however, you will get maps with an ugly ‘for development purposes only’ watermark, if you want to get rid of those watermarks you can register (by adding a credit card) to Google Cloud Platform and claim free credits. More info here.
Please, be careful with API keys, especially if you want to share your project online. (i disabled my key before pushing the notebook to GitHub 🙃)
You can install gmaps on Jupyter Notebook by first enabling via terminal ipywidgets extensions:
$ jupyter nbextension enable — py — sys-prefix widgetsnbextension
and then:
$ pip install gmaps
and finally, load the extension with:
$ jupyter nbextension enable — py — sys-prefix gmaps
Creating heatmaps with gmaps is simple, we specify a Map object and then pass our dataframe with coordinates and weights.
fig = gmaps.Map(layout={‘width’: ‘1000px’, ‘height’: ‘500px’, ‘padding’: ‘10px’})fig.add_layer(gmaps.heatmap_layer(df[[‘latitude’, ‘longitude’]], weights=df[‘price’]))fig
The map shows that locations in the city center are more expensive, while the outskirts are cheaper (a pattern that probably does not only exists in Amsterdam). In addition, the city center seems to have its own pattern.
In order to capture some geographical pattern we need to apply some feature engineering, a nice approach is to find a list of point of interest (POI) and calculate the distance between each observation and the POI.
If we know that a specific location is very close to a place we consider expensive most probably the whole sorrounding area will be expensive.
To calculate the distance in KM I am using a function that retrieves the haversine distance, AKA the distance between two points on a sphere.
This kind of metric has its own pros and cons: it gives an easy way to calculate the distance between two points, but it does not take into account obstacles such as buildings, lakes, rivers, borders, and so on.
To get a list of POI, I searched on Google and the, for each of them I searched the geographical coordinates.
here are the results:
It is now possible to define a function to calculate distances of one house to each of the POI:
from math import radians, cos, sin, asin, sqrtdef haversine(lon1, lat1, lon2, lat2): “”” Calculate the great circle distance between two points on the earth (specified in decimal degrees) “”” # convert decimal degrees to radians lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2]) # haversine formula dlon = lon2 — lon1 dlat = lat2 — lat1 a = sin(dlat / 2) ** 2 + cos(lat1) * cos(lat2) * sin(dlon / 2)**2 c = 2 * asin(sqrt(a)) km = 6367 * c return km
Now we can iterate each row of the dataset, and for each of them we iterate through our POI dataframe and calculate the distance for every POI (Did I say too many times “each” or “POI”?)
Let’s now plot again our map with POIs, we can do this by iterating over each row of the poi dataframe and creating a tuple using list comprehension:
fig.add_layer(gmaps.symbol_layer([tuple(x) for x in poi.to_numpy()] , fill_color=’green’, stroke_color=’green’))fig
From the visualization, it can be possible to see that near Willemspark there are much fewer flats than compared to areas around, in addition, most of the POIs are located in ‘expensive’ areas, especially around Dam Square's district.
Let’s now start the modeling section, we will prepare our dataset by encoding the categorical variable room_type and by splitting it into train and test
df = pd.get_dummies(df)X = df.drop([‘price’], axis=1)y = df[‘price’]from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=1)
The dataset is split in 80–20 % between train and test.
The first model used will be used as a baseline, as we need a benchmark to assess the performances of other models and compare results.
It consists of a classical Linear Regression, evaluated with cross-validation using the GridSearchCV class on r2 and MAE metrics.
let’s fit it:
from sklearn.linear_model import LinearRegressionlin_reg = LinearRegression()lin_reg.fit(X_train, y_train)y_pred = lin_reg.predict(X_test)
We can now calculate our r2 and MAE errors by creating a dummy dataframe to store results for each model:
from sklearn import metricsr2 = metrics.r2_score(y_test, y_pred)mae = metrics.mean_absolute_error(y_test, y_pred)scores = pd.DataFrame({‘Baseline (regression)’ : [r2, mae]}, index=[‘R2’, ‘MAE’])scores
The mae tells us that our predictions are on average 40$ off, while the R2 tells us our data are pretty sparsed.
An interesting plot to graphically assess the results of the regression is the difference of test set and predicted value against our test set:
The closest the values are to 0 the better since the delta y_test — y_pred should be ideally 0.
The next model has been chosen according to the sklearn map, and it consists of a Support Vector Machine. However, since playing with parameters its not always easy, and it might require specific knowledge GridSearchCV will come in help:
if 'svr_gridsearch_cv.pkl' in os.listdir(): svr_grid_search = joblib.load('svr_gridsearch_cv.pkl') else: from sklearn.svm import SVRsvr = SVR()param_grid = [ {'C': [1, 10, 100, 1000], 'kernel': ['linear']}, {'C': [1, 10, 100, 1000], 'gamma': [0.01, 0.001, 0.0001], 'kernel': ['rbf']}]svr_grid_search = GridSearchCV(svr, param_grid=param_grid, n_jobs=-1, scoring=['r2', 'neg_mean_squared_error'], refit='neg_mean_squared_error', verbose=100)svr_grid_search.fit(X_train, y_train)joblib.dump(svr_grid_search.best_estimator_, 'svr_gridsearch_cv.pkl')
Be careful, this task can take more than 40 minutes, that’s why before fitting I check if the model already exists from a previous fit, and if exists, I load it.
We will then, again, predict and calculate our metrics based on the best parameters from GridSearchCV
Compared to our baseline model the mae decreased by almost 4$ on average.
Let’s also for this model plot predicted values vs the delta of the errors:
The third model we will test is based on Stochastic Gradient Descent, I will use LightGBM, a library by Microsoft which is widely used in the industry and is one of the most used libraries to win Kaggle competitions.
if 'gbm_gridsearch_cv.pkl' in os.listdir(): gbm_grid_search = joblib.load('gbm_gridsearch_cv.pkl') else: from lightgbm import LGBMRegressorgbm = LGBMRegressor()param_grid = { 'learning_rate': [0.01, 0.1, 1], 'n_estimators': [50, 100, 150], 'boosting_type': ['gbdt', 'dart'], 'num_leaves': [15, 31, 50]}gbm_grid_search = GridSearchCV(gbm, param_grid=param_grid, n_jobs=-1, scoring=['r2', 'neg_mean_squared_error'], refit='neg_mean_squared_error', verbose=100)gbm_grid_search.fit(X_train, y_train)joblib.dump(gbm_grid_search.best_estimator_, 'gbm_gridsearch_cv.pkl')
The model train pretty fast and the results aren’t bad at all:
So far the best performing model is the GBM, which increases the R2 by ~ 6% while the mae is slightly worse.
Thinking about a way to further improve our regressor, the first thing that bumped into my mind was neural networks obviously! So I decided to implement a simple one:
def build_model(): model = keras.Sequential([ tf.keras.layers.Dense(64, activation=’relu’, input_shape=(25,)), tf.keras.layers.Dropout(0.2), tf.keras.layers.Dense(128, activation=’relu’), tf.keras.layers.Dropout(0.2), tf.keras.layers.Dense(1) ])optimizer = tf.keras.optimizers.RMSprop(0.001)model.compile(loss=’mean_squared_error’, optimizer=optimizer, metrics=[‘mae’, r2_keras]) return model
However, after playing a bit and running it for 100 epochs results aren’t particularly surprising:
Results are basically an average between the GBM and the SVR, and also plotting the errors give a very similar plot to the previous ones.
Despite having already metrics on the performances of the models, in order to give a final evaluation on which model could be considered the best, it is necessary to add other evaluation metrics such as the resources needed to implement the model and the time needed to train it.
Considering the second model SVR: it performed exceptionally, achieving the best MAE, however the training time of a grid search to implement took over 40 minutes, meaning that every time something wants to be checked or changed it cost at least 40 minutes.
The third model (Gradient boosting tree), took a few seconds to fit and the results were pretty good, practically achieving the best results overall.
Considering the last model, the neural network, it took as well not so much time to train, a couple of minutes, however, the results weren’t radically better than the previous models, actually, it performed more or less in the same way, maybe because I didn’t choose the right hyperparameters, maybe because the amount of data, maybe because multiple other reasons, however, it didn't perform radically better than previous models.
In addition, it is a less explainable model, meaning that it is difficult for us to explain how a prediction was decided, while for example, for a linear regression we can have all the data such as intercept and coefficients:
coefficients = pd.concat([pd.DataFrame(X.columns, columns=['variable']), pd.DataFrame(np.transpose(lin_reg.coef_), columns ['coefficients'])], axis = 1)coefficients
Taking into account the previously mentioned considerations, and stating that very often compromises are a good approximation, we can conclude that, given our metrics, the best model was the Gradient Boosting Tree (LightGBM), it trained in a blink of an eye and results were the best among other candidates.
Moreover, opting for a machine learning model offers an advantage: a decision tree is an explainable model, which is possible to decompose it and find why and how it calculated specific results instead of another, calling the following method on the tree regressor it is possible to have a look at the tree’s diagram:
import lightgbmlightgbm.create_tree_digraph(gbm_grid_search.best_estimator_)
XAI, or Explainable AI is a very important aspect of modern Data Science, which focuses on how a particular prediction was achieved, instead of seeing model as black boxes.
Citing a paper* from the University of Bonn:
A prerequisite for obtaining a scientific outcome is domain knowledge, which is needed to gain explainability, but also to enhance scientific consistency.
[*] Ribana Roscher, Bastian Bohn, Marco F. Duarte, and Jochen Garcke, Explainable Machine Learning for Scientific Insights and Discoveries (2019).
Thanks for reading this story! I hope it was interesting for you. If yes, please consider following my profile, it means a lot for me 😃 | [
{
"code": null,
"e": 332,
"s": 171,
"text": "A Data Science portfolio project is like studying for your driving license practical exam, you are not learning to drive, you are learning how to pass the exam."
},
{
"code": null,
"e": 464,
"s": 332,
"text": "When preparing your portfolio it’s important to have projects that cover different fields, techniques and are able to tell a story."
},
{
"code": null,
"e": 669,
"s": 464,
"text": "In this article, my main goal is to show how I would do a data science portfolio project that covers visualization, data preprocessing, modeling and final considerations along with production suggestions."
},
{
"code": null,
"e": 772,
"s": 669,
"text": "I am using the Amsterdam Airbnb dataset for predicting the price of a flat given a list of predictors."
},
{
"code": null,
"e": 916,
"s": 772,
"text": "The dataset once imported into Python is analyzed using pandas_profiling a very useful tool that extends the df.info() functionality in pandas."
},
{
"code": null,
"e": 1084,
"s": 916,
"text": "As described in the report, the dataset contains 14 variables, 10 are numeric and 2 categorical (we will probably need to get dummy variables for those when modeling)."
},
{
"code": null,
"e": 1304,
"s": 1084,
"text": "Moreover, according to the report variable host_listings_count and calculated_host_listings_count are highly correlated with a Pearson score of 0.94, hence we will discard the former to avoid multicollinearity problems."
},
{
"code": null,
"e": 1504,
"s": 1304,
"text": "We can see that our target variable price is not a number, let’s have a look to the longest one, in order to understand if there are any formatting applied that needs to be removed before converting:"
},
{
"code": null,
"e": 1554,
"s": 1504,
"text": "max(df[‘price’].values, key = len)>>> '$1,305.00'"
},
{
"code": null,
"e": 1750,
"s": 1554,
"text": "First of all, we can see our target variable has 2 different characters we need to get rid of, the $ symbol and the comma identifying the thousands. let’s get rid of them by using the df.apply()."
},
{
"code": null,
"e": 1913,
"s": 1750,
"text": "df[‘price’] = df[‘price’].apply(lambda x: x.replace(‘$’, ‘’))df[‘price’] = df[‘price’].apply(lambda x: x.replace(‘,’, ‘’))df[‘price’] = pd.to_numeric(df[‘price’])"
},
{
"code": null,
"e": 2174,
"s": 1913,
"text": "The dataset has two columns containing pieces of information about coordinates where the flat is located, plus we have our target variable. Hence we can create a heatmap to better understand where flats are located and how the price is affected by the location"
},
{
"code": null,
"e": 2268,
"s": 2174,
"text": "To achieve we will use gmaps , a python package to create interactive maps using Google Maps."
},
{
"code": null,
"e": 2552,
"s": 2268,
"text": "You can use the free version, without an API key, however, you will get maps with an ugly ‘for development purposes only’ watermark, if you want to get rid of those watermarks you can register (by adding a credit card) to Google Cloud Platform and claim free credits. More info here."
},
{
"code": null,
"e": 2699,
"s": 2552,
"text": "Please, be careful with API keys, especially if you want to share your project online. (i disabled my key before pushing the notebook to GitHub 🙃)"
},
{
"code": null,
"e": 2795,
"s": 2699,
"text": "You can install gmaps on Jupyter Notebook by first enabling via terminal ipywidgets extensions:"
},
{
"code": null,
"e": 2861,
"s": 2795,
"text": "$ jupyter nbextension enable — py — sys-prefix widgetsnbextension"
},
{
"code": null,
"e": 2871,
"s": 2861,
"text": "and then:"
},
{
"code": null,
"e": 2891,
"s": 2871,
"text": "$ pip install gmaps"
},
{
"code": null,
"e": 2929,
"s": 2891,
"text": "and finally, load the extension with:"
},
{
"code": null,
"e": 2982,
"s": 2929,
"text": "$ jupyter nbextension enable — py — sys-prefix gmaps"
},
{
"code": null,
"e": 3104,
"s": 2982,
"text": "Creating heatmaps with gmaps is simple, we specify a Map object and then pass our dataframe with coordinates and weights."
},
{
"code": null,
"e": 3275,
"s": 3104,
"text": "fig = gmaps.Map(layout={‘width’: ‘1000px’, ‘height’: ‘500px’, ‘padding’: ‘10px’})fig.add_layer(gmaps.heatmap_layer(df[[‘latitude’, ‘longitude’]], weights=df[‘price’]))fig"
},
{
"code": null,
"e": 3496,
"s": 3275,
"text": "The map shows that locations in the city center are more expensive, while the outskirts are cheaper (a pattern that probably does not only exists in Amsterdam). In addition, the city center seems to have its own pattern."
},
{
"code": null,
"e": 3711,
"s": 3496,
"text": "In order to capture some geographical pattern we need to apply some feature engineering, a nice approach is to find a list of point of interest (POI) and calculate the distance between each observation and the POI."
},
{
"code": null,
"e": 3854,
"s": 3711,
"text": "If we know that a specific location is very close to a place we consider expensive most probably the whole sorrounding area will be expensive."
},
{
"code": null,
"e": 3996,
"s": 3854,
"text": "To calculate the distance in KM I am using a function that retrieves the haversine distance, AKA the distance between two points on a sphere."
},
{
"code": null,
"e": 4208,
"s": 3996,
"text": "This kind of metric has its own pros and cons: it gives an easy way to calculate the distance between two points, but it does not take into account obstacles such as buildings, lakes, rivers, borders, and so on."
},
{
"code": null,
"e": 4318,
"s": 4208,
"text": "To get a list of POI, I searched on Google and the, for each of them I searched the geographical coordinates."
},
{
"code": null,
"e": 4340,
"s": 4318,
"text": "here are the results:"
},
{
"code": null,
"e": 4436,
"s": 4340,
"text": "It is now possible to define a function to calculate distances of one house to each of the POI:"
},
{
"code": null,
"e": 4905,
"s": 4436,
"text": "from math import radians, cos, sin, asin, sqrtdef haversine(lon1, lat1, lon2, lat2): “”” Calculate the great circle distance between two points on the earth (specified in decimal degrees) “”” # convert decimal degrees to radians lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2]) # haversine formula dlon = lon2 — lon1 dlat = lat2 — lat1 a = sin(dlat / 2) ** 2 + cos(lat1) * cos(lat2) * sin(dlon / 2)**2 c = 2 * asin(sqrt(a)) km = 6367 * c return km"
},
{
"code": null,
"e": 5092,
"s": 4905,
"text": "Now we can iterate each row of the dataset, and for each of them we iterate through our POI dataframe and calculate the distance for every POI (Did I say too many times “each” or “POI”?)"
},
{
"code": null,
"e": 5242,
"s": 5092,
"text": "Let’s now plot again our map with POIs, we can do this by iterating over each row of the poi dataframe and creating a tuple using list comprehension:"
},
{
"code": null,
"e": 5358,
"s": 5242,
"text": "fig.add_layer(gmaps.symbol_layer([tuple(x) for x in poi.to_numpy()] , fill_color=’green’, stroke_color=’green’))fig"
},
{
"code": null,
"e": 5593,
"s": 5358,
"text": "From the visualization, it can be possible to see that near Willemspark there are much fewer flats than compared to areas around, in addition, most of the POIs are located in ‘expensive’ areas, especially around Dam Square's district."
},
{
"code": null,
"e": 5746,
"s": 5593,
"text": "Let’s now start the modeling section, we will prepare our dataset by encoding the categorical variable room_type and by splitting it into train and test"
},
{
"code": null,
"e": 5956,
"s": 5746,
"text": "df = pd.get_dummies(df)X = df.drop([‘price’], axis=1)y = df[‘price’]from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=1)"
},
{
"code": null,
"e": 6012,
"s": 5956,
"text": "The dataset is split in 80–20 % between train and test."
},
{
"code": null,
"e": 6148,
"s": 6012,
"text": "The first model used will be used as a baseline, as we need a benchmark to assess the performances of other models and compare results."
},
{
"code": null,
"e": 6278,
"s": 6148,
"text": "It consists of a classical Linear Regression, evaluated with cross-validation using the GridSearchCV class on r2 and MAE metrics."
},
{
"code": null,
"e": 6292,
"s": 6278,
"text": "let’s fit it:"
},
{
"code": null,
"e": 6431,
"s": 6292,
"text": "from sklearn.linear_model import LinearRegressionlin_reg = LinearRegression()lin_reg.fit(X_train, y_train)y_pred = lin_reg.predict(X_test)"
},
{
"code": null,
"e": 6537,
"s": 6431,
"text": "We can now calculate our r2 and MAE errors by creating a dummy dataframe to store results for each model:"
},
{
"code": null,
"e": 6738,
"s": 6537,
"text": "from sklearn import metricsr2 = metrics.r2_score(y_test, y_pred)mae = metrics.mean_absolute_error(y_test, y_pred)scores = pd.DataFrame({‘Baseline (regression)’ : [r2, mae]}, index=[‘R2’, ‘MAE’])scores"
},
{
"code": null,
"e": 6851,
"s": 6738,
"text": "The mae tells us that our predictions are on average 40$ off, while the R2 tells us our data are pretty sparsed."
},
{
"code": null,
"e": 6995,
"s": 6851,
"text": "An interesting plot to graphically assess the results of the regression is the difference of test set and predicted value against our test set:"
},
{
"code": null,
"e": 7091,
"s": 6995,
"text": "The closest the values are to 0 the better since the delta y_test — y_pred should be ideally 0."
},
{
"code": null,
"e": 7329,
"s": 7091,
"text": "The next model has been chosen according to the sklearn map, and it consists of a Support Vector Machine. However, since playing with parameters its not always easy, and it might require specific knowledge GridSearchCV will come in help:"
},
{
"code": null,
"e": 8006,
"s": 7329,
"text": "if 'svr_gridsearch_cv.pkl' in os.listdir(): svr_grid_search = joblib.load('svr_gridsearch_cv.pkl') else: from sklearn.svm import SVRsvr = SVR()param_grid = [ {'C': [1, 10, 100, 1000], 'kernel': ['linear']}, {'C': [1, 10, 100, 1000], 'gamma': [0.01, 0.001, 0.0001], 'kernel': ['rbf']}]svr_grid_search = GridSearchCV(svr, param_grid=param_grid, n_jobs=-1, scoring=['r2', 'neg_mean_squared_error'], refit='neg_mean_squared_error', verbose=100)svr_grid_search.fit(X_train, y_train)joblib.dump(svr_grid_search.best_estimator_, 'svr_gridsearch_cv.pkl')"
},
{
"code": null,
"e": 8168,
"s": 8006,
"text": "Be careful, this task can take more than 40 minutes, that’s why before fitting I check if the model already exists from a previous fit, and if exists, I load it."
},
{
"code": null,
"e": 8270,
"s": 8168,
"text": "We will then, again, predict and calculate our metrics based on the best parameters from GridSearchCV"
},
{
"code": null,
"e": 8344,
"s": 8270,
"text": "Compared to our baseline model the mae decreased by almost 4$ on average."
},
{
"code": null,
"e": 8420,
"s": 8344,
"text": "Let’s also for this model plot predicted values vs the delta of the errors:"
},
{
"code": null,
"e": 8637,
"s": 8420,
"text": "The third model we will test is based on Stochastic Gradient Descent, I will use LightGBM, a library by Microsoft which is widely used in the industry and is one of the most used libraries to win Kaggle competitions."
},
{
"code": null,
"e": 9334,
"s": 8637,
"text": "if 'gbm_gridsearch_cv.pkl' in os.listdir(): gbm_grid_search = joblib.load('gbm_gridsearch_cv.pkl') else: from lightgbm import LGBMRegressorgbm = LGBMRegressor()param_grid = { 'learning_rate': [0.01, 0.1, 1], 'n_estimators': [50, 100, 150], 'boosting_type': ['gbdt', 'dart'], 'num_leaves': [15, 31, 50]}gbm_grid_search = GridSearchCV(gbm, param_grid=param_grid, n_jobs=-1, scoring=['r2', 'neg_mean_squared_error'], refit='neg_mean_squared_error', verbose=100)gbm_grid_search.fit(X_train, y_train)joblib.dump(gbm_grid_search.best_estimator_, 'gbm_gridsearch_cv.pkl')"
},
{
"code": null,
"e": 9397,
"s": 9334,
"text": "The model train pretty fast and the results aren’t bad at all:"
},
{
"code": null,
"e": 9506,
"s": 9397,
"text": "So far the best performing model is the GBM, which increases the R2 by ~ 6% while the mae is slightly worse."
},
{
"code": null,
"e": 9673,
"s": 9506,
"text": "Thinking about a way to further improve our regressor, the first thing that bumped into my mind was neural networks obviously! So I decided to implement a simple one:"
},
{
"code": null,
"e": 10069,
"s": 9673,
"text": "def build_model(): model = keras.Sequential([ tf.keras.layers.Dense(64, activation=’relu’, input_shape=(25,)), tf.keras.layers.Dropout(0.2), tf.keras.layers.Dense(128, activation=’relu’), tf.keras.layers.Dropout(0.2), tf.keras.layers.Dense(1) ])optimizer = tf.keras.optimizers.RMSprop(0.001)model.compile(loss=’mean_squared_error’, optimizer=optimizer, metrics=[‘mae’, r2_keras]) return model"
},
{
"code": null,
"e": 10168,
"s": 10069,
"text": "However, after playing a bit and running it for 100 epochs results aren’t particularly surprising:"
},
{
"code": null,
"e": 10306,
"s": 10168,
"text": "Results are basically an average between the GBM and the SVR, and also plotting the errors give a very similar plot to the previous ones."
},
{
"code": null,
"e": 10586,
"s": 10306,
"text": "Despite having already metrics on the performances of the models, in order to give a final evaluation on which model could be considered the best, it is necessary to add other evaluation metrics such as the resources needed to implement the model and the time needed to train it."
},
{
"code": null,
"e": 10844,
"s": 10586,
"text": "Considering the second model SVR: it performed exceptionally, achieving the best MAE, however the training time of a grid search to implement took over 40 minutes, meaning that every time something wants to be checked or changed it cost at least 40 minutes."
},
{
"code": null,
"e": 10994,
"s": 10844,
"text": "The third model (Gradient boosting tree), took a few seconds to fit and the results were pretty good, practically achieving the best results overall."
},
{
"code": null,
"e": 11426,
"s": 10994,
"text": "Considering the last model, the neural network, it took as well not so much time to train, a couple of minutes, however, the results weren’t radically better than the previous models, actually, it performed more or less in the same way, maybe because I didn’t choose the right hyperparameters, maybe because the amount of data, maybe because multiple other reasons, however, it didn't perform radically better than previous models."
},
{
"code": null,
"e": 11652,
"s": 11426,
"text": "In addition, it is a less explainable model, meaning that it is difficult for us to explain how a prediction was decided, while for example, for a linear regression we can have all the data such as intercept and coefficients:"
},
{
"code": null,
"e": 11817,
"s": 11652,
"text": "coefficients = pd.concat([pd.DataFrame(X.columns, columns=['variable']), pd.DataFrame(np.transpose(lin_reg.coef_), columns ['coefficients'])], axis = 1)coefficients"
},
{
"code": null,
"e": 12125,
"s": 11817,
"text": "Taking into account the previously mentioned considerations, and stating that very often compromises are a good approximation, we can conclude that, given our metrics, the best model was the Gradient Boosting Tree (LightGBM), it trained in a blink of an eye and results were the best among other candidates."
},
{
"code": null,
"e": 12443,
"s": 12125,
"text": "Moreover, opting for a machine learning model offers an advantage: a decision tree is an explainable model, which is possible to decompose it and find why and how it calculated specific results instead of another, calling the following method on the tree regressor it is possible to have a look at the tree’s diagram:"
},
{
"code": null,
"e": 12520,
"s": 12443,
"text": "import lightgbmlightgbm.create_tree_digraph(gbm_grid_search.best_estimator_)"
},
{
"code": null,
"e": 12693,
"s": 12520,
"text": "XAI, or Explainable AI is a very important aspect of modern Data Science, which focuses on how a particular prediction was achieved, instead of seeing model as black boxes."
},
{
"code": null,
"e": 12738,
"s": 12693,
"text": "Citing a paper* from the University of Bonn:"
},
{
"code": null,
"e": 12893,
"s": 12738,
"text": "A prerequisite for obtaining a scientific outcome is domain knowledge, which is needed to gain explainability, but also to enhance scientific consistency."
},
{
"code": null,
"e": 13040,
"s": 12893,
"text": "[*] Ribana Roscher, Bastian Bohn, Marco F. Duarte, and Jochen Garcke, Explainable Machine Learning for Scientific Insights and Discoveries (2019)."
}
]
|
Python - Random Numbers Summation - GeeksforGeeks | 19 Feb, 2020
Sometimes, in making programs for gaming or gambling, we come across the task of creating the list all with random numbers and perform its summation. This task has to performed in general using loop and appending the random numbers one by one and then performing sum. But there is always requirement to perform this in most concise manner. Lets discuss certain ways in which this can be done.
Method #1 : Using list comprehension + randrange() + sum()The naive method to perform this particular task can be shortened using the list comprehension. randrange function is used to perform the task of generating the random numbers. The task of performing sum is done using sum().
# Python3 code to demonstrate # Random Numbers Summation# using list comprehension + randrange() + sum()import random # using list comprehension + randrange() + sum()# Random Numbers Summationres = sum([random.randrange(1, 50, 1) for i in range(7)]) # printing resultprint ("Random number summation list is : " + str(res))
Random number summation list is : 187
Method #2 : Using random.sample() + sum()This single utility function performs the exact required as asked by the problem statement, it generated N no. of random numbers in a list in the specified range and returns the required list. The task of performing sum is done using sum().
# Python3 code to demonstrate # Random Numbers Summation# using random.sample() + sum()import random # using random.sample() + sum()# Random Numbers Summationres = sum(random.sample(range(1, 50), 7)) # printing resultprint ("Random number summation list is : " + str(res))
Random number summation list is : 187
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Reading and Writing to text files in Python
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python? | [
{
"code": null,
"e": 24358,
"s": 24330,
"text": "\n19 Feb, 2020"
},
{
"code": null,
"e": 24751,
"s": 24358,
"text": "Sometimes, in making programs for gaming or gambling, we come across the task of creating the list all with random numbers and perform its summation. This task has to performed in general using loop and appending the random numbers one by one and then performing sum. But there is always requirement to perform this in most concise manner. Lets discuss certain ways in which this can be done."
},
{
"code": null,
"e": 25034,
"s": 24751,
"text": "Method #1 : Using list comprehension + randrange() + sum()The naive method to perform this particular task can be shortened using the list comprehension. randrange function is used to perform the task of generating the random numbers. The task of performing sum is done using sum()."
},
{
"code": "# Python3 code to demonstrate # Random Numbers Summation# using list comprehension + randrange() + sum()import random # using list comprehension + randrange() + sum()# Random Numbers Summationres = sum([random.randrange(1, 50, 1) for i in range(7)]) # printing resultprint (\"Random number summation list is : \" + str(res))",
"e": 25359,
"s": 25034,
"text": null
},
{
"code": null,
"e": 25398,
"s": 25359,
"text": "Random number summation list is : 187\n"
},
{
"code": null,
"e": 25682,
"s": 25400,
"text": "Method #2 : Using random.sample() + sum()This single utility function performs the exact required as asked by the problem statement, it generated N no. of random numbers in a list in the specified range and returns the required list. The task of performing sum is done using sum()."
},
{
"code": "# Python3 code to demonstrate # Random Numbers Summation# using random.sample() + sum()import random # using random.sample() + sum()# Random Numbers Summationres = sum(random.sample(range(1, 50), 7)) # printing resultprint (\"Random number summation list is : \" + str(res))",
"e": 25957,
"s": 25682,
"text": null
},
{
"code": null,
"e": 25996,
"s": 25957,
"text": "Random number summation list is : 187\n"
},
{
"code": null,
"e": 26017,
"s": 25996,
"text": "Python list-programs"
},
{
"code": null,
"e": 26024,
"s": 26017,
"text": "Python"
},
{
"code": null,
"e": 26040,
"s": 26024,
"text": "Python Programs"
},
{
"code": null,
"e": 26138,
"s": 26040,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26147,
"s": 26138,
"text": "Comments"
},
{
"code": null,
"e": 26160,
"s": 26147,
"text": "Old Comments"
},
{
"code": null,
"e": 26178,
"s": 26160,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26210,
"s": 26178,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26232,
"s": 26210,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26274,
"s": 26232,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26318,
"s": 26274,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 26340,
"s": 26318,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26379,
"s": 26340,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 26425,
"s": 26379,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 26463,
"s": 26425,
"text": "Python | Convert a list to dictionary"
}
]
|
Program to count submatrices with all ones using Python | Suppose we have m x n binary matrix, we have to find how many submatrices have all ones.
So, if the input is like
then the output will be 13 as there are 6 (1x1) matrices, 3 (2,1) matrices, 2 (1x2) matrices, 1 (3x1) matrix and 1 (4x4) matrix.
To solve this, we will follow these steps −
m := row count of matrix
m := row count of matrix
n := column count of matrix
n := column count of matrix
dp := a zero matrix of same size m x n
dp := a zero matrix of same size m x n
for i in range 0 to m - 1, dofor j in range 0 to n - 1, doif i is same as 0 and matrix[i, j], thendp[i, j] := 1otherwise when matrix[i][j] is non-zero, thendp[i, j] := dp[i-1, j] + 1
for i in range 0 to m - 1, do
for j in range 0 to n - 1, doif i is same as 0 and matrix[i, j], thendp[i, j] := 1otherwise when matrix[i][j] is non-zero, thendp[i, j] := dp[i-1, j] + 1
for j in range 0 to n - 1, do
if i is same as 0 and matrix[i, j], thendp[i, j] := 1
if i is same as 0 and matrix[i, j], then
dp[i, j] := 1
dp[i, j] := 1
otherwise when matrix[i][j] is non-zero, thendp[i, j] := dp[i-1, j] + 1
otherwise when matrix[i][j] is non-zero, then
dp[i, j] := dp[i-1, j] + 1
dp[i, j] := dp[i-1, j] + 1
total := 0
total := 0
for i in range 0 to m - 1, dofor j in range 0 to n - 1, dofor k in range j+1 to n, dototal := total + minimum of dp[i,j] to dp[i,k]
for i in range 0 to m - 1, do
for j in range 0 to n - 1, dofor k in range j+1 to n, dototal := total + minimum of dp[i,j] to dp[i,k]
for j in range 0 to n - 1, do
for k in range j+1 to n, dototal := total + minimum of dp[i,j] to dp[i,k]
for k in range j+1 to n, do
total := total + minimum of dp[i,j] to dp[i,k]
total := total + minimum of dp[i,j] to dp[i,k]
return total
return total
Let us see the following implementation to get better understanding −
Live Demo
def solve(matrix):
m = len(matrix)
n = len(matrix[0])
dp = [[0] * n for _ in range(m)]
for i in range(m):
for j in range(n):
if i == 0 and matrix[i][j]:
dp[i][j] = 1
elif matrix[i][j]:
dp[i][j] = dp[i-1][j] + 1
total = 0
for i in range(m):
for j in range(n):
for k in range(j+1, n+1):
total += min(dp[i][j:k])
return total
matrix = [[1,0,1],[0,1,1],[0,1,1]]
print(solve(matrix))
[4,6,7,8], 11
13 | [
{
"code": null,
"e": 1151,
"s": 1062,
"text": "Suppose we have m x n binary matrix, we have to find how many submatrices have all ones."
},
{
"code": null,
"e": 1176,
"s": 1151,
"text": "So, if the input is like"
},
{
"code": null,
"e": 1305,
"s": 1176,
"text": "then the output will be 13 as there are 6 (1x1) matrices, 3 (2,1) matrices, 2 (1x2) matrices, 1 (3x1) matrix and 1 (4x4) matrix."
},
{
"code": null,
"e": 1349,
"s": 1305,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1374,
"s": 1349,
"text": "m := row count of matrix"
},
{
"code": null,
"e": 1399,
"s": 1374,
"text": "m := row count of matrix"
},
{
"code": null,
"e": 1427,
"s": 1399,
"text": "n := column count of matrix"
},
{
"code": null,
"e": 1455,
"s": 1427,
"text": "n := column count of matrix"
},
{
"code": null,
"e": 1494,
"s": 1455,
"text": "dp := a zero matrix of same size m x n"
},
{
"code": null,
"e": 1533,
"s": 1494,
"text": "dp := a zero matrix of same size m x n"
},
{
"code": null,
"e": 1716,
"s": 1533,
"text": "for i in range 0 to m - 1, dofor j in range 0 to n - 1, doif i is same as 0 and matrix[i, j], thendp[i, j] := 1otherwise when matrix[i][j] is non-zero, thendp[i, j] := dp[i-1, j] + 1"
},
{
"code": null,
"e": 1746,
"s": 1716,
"text": "for i in range 0 to m - 1, do"
},
{
"code": null,
"e": 1900,
"s": 1746,
"text": "for j in range 0 to n - 1, doif i is same as 0 and matrix[i, j], thendp[i, j] := 1otherwise when matrix[i][j] is non-zero, thendp[i, j] := dp[i-1, j] + 1"
},
{
"code": null,
"e": 1930,
"s": 1900,
"text": "for j in range 0 to n - 1, do"
},
{
"code": null,
"e": 1984,
"s": 1930,
"text": "if i is same as 0 and matrix[i, j], thendp[i, j] := 1"
},
{
"code": null,
"e": 2025,
"s": 1984,
"text": "if i is same as 0 and matrix[i, j], then"
},
{
"code": null,
"e": 2039,
"s": 2025,
"text": "dp[i, j] := 1"
},
{
"code": null,
"e": 2053,
"s": 2039,
"text": "dp[i, j] := 1"
},
{
"code": null,
"e": 2125,
"s": 2053,
"text": "otherwise when matrix[i][j] is non-zero, thendp[i, j] := dp[i-1, j] + 1"
},
{
"code": null,
"e": 2171,
"s": 2125,
"text": "otherwise when matrix[i][j] is non-zero, then"
},
{
"code": null,
"e": 2198,
"s": 2171,
"text": "dp[i, j] := dp[i-1, j] + 1"
},
{
"code": null,
"e": 2225,
"s": 2198,
"text": "dp[i, j] := dp[i-1, j] + 1"
},
{
"code": null,
"e": 2236,
"s": 2225,
"text": "total := 0"
},
{
"code": null,
"e": 2247,
"s": 2236,
"text": "total := 0"
},
{
"code": null,
"e": 2379,
"s": 2247,
"text": "for i in range 0 to m - 1, dofor j in range 0 to n - 1, dofor k in range j+1 to n, dototal := total + minimum of dp[i,j] to dp[i,k]"
},
{
"code": null,
"e": 2409,
"s": 2379,
"text": "for i in range 0 to m - 1, do"
},
{
"code": null,
"e": 2512,
"s": 2409,
"text": "for j in range 0 to n - 1, dofor k in range j+1 to n, dototal := total + minimum of dp[i,j] to dp[i,k]"
},
{
"code": null,
"e": 2542,
"s": 2512,
"text": "for j in range 0 to n - 1, do"
},
{
"code": null,
"e": 2616,
"s": 2542,
"text": "for k in range j+1 to n, dototal := total + minimum of dp[i,j] to dp[i,k]"
},
{
"code": null,
"e": 2644,
"s": 2616,
"text": "for k in range j+1 to n, do"
},
{
"code": null,
"e": 2691,
"s": 2644,
"text": "total := total + minimum of dp[i,j] to dp[i,k]"
},
{
"code": null,
"e": 2738,
"s": 2691,
"text": "total := total + minimum of dp[i,j] to dp[i,k]"
},
{
"code": null,
"e": 2751,
"s": 2738,
"text": "return total"
},
{
"code": null,
"e": 2764,
"s": 2751,
"text": "return total"
},
{
"code": null,
"e": 2834,
"s": 2764,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 2845,
"s": 2834,
"text": " Live Demo"
},
{
"code": null,
"e": 3320,
"s": 2845,
"text": "def solve(matrix):\n m = len(matrix)\n n = len(matrix[0])\n dp = [[0] * n for _ in range(m)]\n for i in range(m):\n for j in range(n):\n if i == 0 and matrix[i][j]:\n dp[i][j] = 1\n elif matrix[i][j]:\n dp[i][j] = dp[i-1][j] + 1\n total = 0\n for i in range(m):\n for j in range(n):\n for k in range(j+1, n+1):\n total += min(dp[i][j:k])\n return total\nmatrix = [[1,0,1],[0,1,1],[0,1,1]]\nprint(solve(matrix))"
},
{
"code": null,
"e": 3334,
"s": 3320,
"text": "[4,6,7,8], 11"
},
{
"code": null,
"e": 3337,
"s": 3334,
"text": "13"
}
]
|
How to calculate Heikin Ashi candles in Python for trading | by Gianluca Malato | Towards Data Science | Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details.
Quantitative traders know that they need to extract as much information as possible from price charts. Price action is a very useful technique to spot trading opportunities, but it’s sometimes difficult to read because candlestick charts might be messy or noisy. So, traders need a tool to smooth price action and remove noise. Heikin Ashi candles can help us. Let’s see how.
Heikin Ashi candles (sometimes called Heiken Ashi) are a particular kind of candlestick chart that tries to remove noise from price action. Particularly, in this kind of chart, there are no gaps.
Let’s see a chart of S&P 500 with plain candlesticks.
As you can see, there are a lot of daily gaps and the shadows of the candles are sometimes wide and make it difficult to decide what to do.
Heikin Ashi candles are calculated this way:
Open: (Open (previous candle) + Close (previous candle))/2
Close: (Open + Low + Close + High)/4
High: the same of the actual candle
Low: the same of the actual candle
As you can see, the calculation of today’s HA candle uses data from both today's and yesterday’s candles. This way, HA candles smooth price action.
The result, applied to the same chart is:
As you can see, there are no gaps and the chart is easier to read.
Using HA charts is very simple. First of all, we can see that before an important reversal we can detect some spinning top patterns, that are candles with very small real body and large shadows of almost the same size. This is an important way to detect a trend reversal.
Then, we can see that when the trend is strong, the opposite shadow is almost absent (i.e. in a strong bullish trend, lower shadows are invisible and in a strong bearish trend, upper shadows are invisible). This gives us a clear overview of the strength of a trend. Finally, a color change is very often used as a confirmation that the trend has changed direction and may be used as an operative signal.
These are all useful items for building a trading strategy and we don’t need to be able to catch several types of patterns like in candlestick charts, but we only need to spot spinning tops and color changes.
The drawback of Heikin Ashi candles is that, like any other kind of moving average, they catch the trend reversal with some delay. So, their signals are always a confirmation of something that has already happened. Thus, they are useful only then you have to work with long-term strategies because the delay in the signal will always make you enter and exit late. However, HA candles are a very useful tool, especially when you work with scalping and need to smooth very noisy price action. Just like any other indicator, it’s useful to use it with another signal, for example with moving averages.
Let’s now see how to calculate Heikin Ashi candles in Python.
For this example, we’re going to analyze S&P 500 data from December 15, 2020 to April 15, 2021. You can find the whole code here on GitHub.
First, let’s install some useful libraries:
!pip install yfinance!pip install mpl_finance
Then, let’s import them and apply some graphical enhancements:
import pandas as pdimport yfinancefrom mpl_finance import candlestick_ohlcimport matplotlib.pyplot as pltplt.rcParams['figure.figsize'] = [12, 7]plt.rc('font', size=14)
Now we can download S&P 500 data and replace the date with a sequential index
name = 'SPY'ticker = yfinance.Ticker(name)df = ticker.history(interval="1d",start="2020-12-15",end="2021-04-15")df['Date'] = range(df.shape[0])df = df.loc[:,['Date', 'Open', 'High', 'Low', 'Close']]
Let’s create a simple function to draw the chart of a data frame:
def plot_chart(df): fig, ax = plt.subplots() candlestick_ohlc(ax,df.values,width=0.6, \ colorup='green', colordown='red', alpha=0.8) fig.tight_layout()fig.show()
Now, let’s see the original candlestick chart:
plot_chart(df)
As you can see, it’s full of gaps and long tails.
Now, let’s calculate Heikin Ashi candles according to the original formula. Since we need to check the previous candle, we have to skip the first row.
We’ll store the result in a new data frame called df_ha. We copy the original data of the candles in order to keep the same highs and lows. Then, we remove the first line.
df_ha = df.copy()for i in range(df_ha.shape[0]): if i > 0: df_ha.loc[df_ha.index[i],'Open'] = (df['Open'][i-1] + df['Close'][i-1])/2 df_ha.loc[df_ha.index[i],'Close'] = (df['Open'][i] + df['Close'][i] + df['Low'][i] + df['High'][i])/4df_ha = df_ha.iloc[1:,:]
We can now plot the result:
plot_chart(df_ha)
As we can see, gaps disappeared and the spinning top HA candles are able to predict a trend inversion quite well.
Heikin Ashi candles are a very useful tool for any kind of trader and it has to be present in every investor’s toolbox. Just don't forget that smoothing price action has the price of a delayed signal.
Gianluca Malato is an Italian Data Scientist and a fiction author. He is the founder of YourDataTeacher.com, an online school of data science, machine learning and data analysis. | [
{
"code": null,
"e": 472,
"s": 172,
"text": "Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details."
},
{
"code": null,
"e": 848,
"s": 472,
"text": "Quantitative traders know that they need to extract as much information as possible from price charts. Price action is a very useful technique to spot trading opportunities, but it’s sometimes difficult to read because candlestick charts might be messy or noisy. So, traders need a tool to smooth price action and remove noise. Heikin Ashi candles can help us. Let’s see how."
},
{
"code": null,
"e": 1044,
"s": 848,
"text": "Heikin Ashi candles (sometimes called Heiken Ashi) are a particular kind of candlestick chart that tries to remove noise from price action. Particularly, in this kind of chart, there are no gaps."
},
{
"code": null,
"e": 1098,
"s": 1044,
"text": "Let’s see a chart of S&P 500 with plain candlesticks."
},
{
"code": null,
"e": 1238,
"s": 1098,
"text": "As you can see, there are a lot of daily gaps and the shadows of the candles are sometimes wide and make it difficult to decide what to do."
},
{
"code": null,
"e": 1283,
"s": 1238,
"text": "Heikin Ashi candles are calculated this way:"
},
{
"code": null,
"e": 1342,
"s": 1283,
"text": "Open: (Open (previous candle) + Close (previous candle))/2"
},
{
"code": null,
"e": 1379,
"s": 1342,
"text": "Close: (Open + Low + Close + High)/4"
},
{
"code": null,
"e": 1415,
"s": 1379,
"text": "High: the same of the actual candle"
},
{
"code": null,
"e": 1450,
"s": 1415,
"text": "Low: the same of the actual candle"
},
{
"code": null,
"e": 1598,
"s": 1450,
"text": "As you can see, the calculation of today’s HA candle uses data from both today's and yesterday’s candles. This way, HA candles smooth price action."
},
{
"code": null,
"e": 1640,
"s": 1598,
"text": "The result, applied to the same chart is:"
},
{
"code": null,
"e": 1707,
"s": 1640,
"text": "As you can see, there are no gaps and the chart is easier to read."
},
{
"code": null,
"e": 1979,
"s": 1707,
"text": "Using HA charts is very simple. First of all, we can see that before an important reversal we can detect some spinning top patterns, that are candles with very small real body and large shadows of almost the same size. This is an important way to detect a trend reversal."
},
{
"code": null,
"e": 2383,
"s": 1979,
"text": "Then, we can see that when the trend is strong, the opposite shadow is almost absent (i.e. in a strong bullish trend, lower shadows are invisible and in a strong bearish trend, upper shadows are invisible). This gives us a clear overview of the strength of a trend. Finally, a color change is very often used as a confirmation that the trend has changed direction and may be used as an operative signal."
},
{
"code": null,
"e": 2592,
"s": 2383,
"text": "These are all useful items for building a trading strategy and we don’t need to be able to catch several types of patterns like in candlestick charts, but we only need to spot spinning tops and color changes."
},
{
"code": null,
"e": 3191,
"s": 2592,
"text": "The drawback of Heikin Ashi candles is that, like any other kind of moving average, they catch the trend reversal with some delay. So, their signals are always a confirmation of something that has already happened. Thus, they are useful only then you have to work with long-term strategies because the delay in the signal will always make you enter and exit late. However, HA candles are a very useful tool, especially when you work with scalping and need to smooth very noisy price action. Just like any other indicator, it’s useful to use it with another signal, for example with moving averages."
},
{
"code": null,
"e": 3253,
"s": 3191,
"text": "Let’s now see how to calculate Heikin Ashi candles in Python."
},
{
"code": null,
"e": 3393,
"s": 3253,
"text": "For this example, we’re going to analyze S&P 500 data from December 15, 2020 to April 15, 2021. You can find the whole code here on GitHub."
},
{
"code": null,
"e": 3437,
"s": 3393,
"text": "First, let’s install some useful libraries:"
},
{
"code": null,
"e": 3483,
"s": 3437,
"text": "!pip install yfinance!pip install mpl_finance"
},
{
"code": null,
"e": 3546,
"s": 3483,
"text": "Then, let’s import them and apply some graphical enhancements:"
},
{
"code": null,
"e": 3715,
"s": 3546,
"text": "import pandas as pdimport yfinancefrom mpl_finance import candlestick_ohlcimport matplotlib.pyplot as pltplt.rcParams['figure.figsize'] = [12, 7]plt.rc('font', size=14)"
},
{
"code": null,
"e": 3793,
"s": 3715,
"text": "Now we can download S&P 500 data and replace the date with a sequential index"
},
{
"code": null,
"e": 3992,
"s": 3793,
"text": "name = 'SPY'ticker = yfinance.Ticker(name)df = ticker.history(interval=\"1d\",start=\"2020-12-15\",end=\"2021-04-15\")df['Date'] = range(df.shape[0])df = df.loc[:,['Date', 'Open', 'High', 'Low', 'Close']]"
},
{
"code": null,
"e": 4058,
"s": 3992,
"text": "Let’s create a simple function to draw the chart of a data frame:"
},
{
"code": null,
"e": 4241,
"s": 4058,
"text": "def plot_chart(df): fig, ax = plt.subplots() candlestick_ohlc(ax,df.values,width=0.6, \\ colorup='green', colordown='red', alpha=0.8) fig.tight_layout()fig.show()"
},
{
"code": null,
"e": 4288,
"s": 4241,
"text": "Now, let’s see the original candlestick chart:"
},
{
"code": null,
"e": 4303,
"s": 4288,
"text": "plot_chart(df)"
},
{
"code": null,
"e": 4353,
"s": 4303,
"text": "As you can see, it’s full of gaps and long tails."
},
{
"code": null,
"e": 4504,
"s": 4353,
"text": "Now, let’s calculate Heikin Ashi candles according to the original formula. Since we need to check the previous candle, we have to skip the first row."
},
{
"code": null,
"e": 4676,
"s": 4504,
"text": "We’ll store the result in a new data frame called df_ha. We copy the original data of the candles in order to keep the same highs and lows. Then, we remove the first line."
},
{
"code": null,
"e": 4943,
"s": 4676,
"text": "df_ha = df.copy()for i in range(df_ha.shape[0]): if i > 0: df_ha.loc[df_ha.index[i],'Open'] = (df['Open'][i-1] + df['Close'][i-1])/2 df_ha.loc[df_ha.index[i],'Close'] = (df['Open'][i] + df['Close'][i] + df['Low'][i] + df['High'][i])/4df_ha = df_ha.iloc[1:,:]"
},
{
"code": null,
"e": 4971,
"s": 4943,
"text": "We can now plot the result:"
},
{
"code": null,
"e": 4989,
"s": 4971,
"text": "plot_chart(df_ha)"
},
{
"code": null,
"e": 5103,
"s": 4989,
"text": "As we can see, gaps disappeared and the spinning top HA candles are able to predict a trend inversion quite well."
},
{
"code": null,
"e": 5304,
"s": 5103,
"text": "Heikin Ashi candles are a very useful tool for any kind of trader and it has to be present in every investor’s toolbox. Just don't forget that smoothing price action has the price of a delayed signal."
}
]
|
DAX Date & Time - SECOND function | Returns the seconds of a time value, as a number from 0 to 59.
SECOND (<datetime>)
datetime
A datetime value representing time. E.g. 18:15:15 or 5:45:15 P.M.
An integer number from 0 to 59.
The parameter to the SECOND function is the time that contains the second you want to find.
You can specify the time as one of the following −
Output of a date/time function.
An expression that returns a datetime value.
A value in one of the accepted time formats.
An accepted text representation of a time.
DAX SECOND function uses the locale and date/time settings of the client computer to understand the text value in order to perform the conversion. Most locales use the colon (:) as the time separator and any input text using colons as time separators will parse correctly. Review your locale settings to understand your results.
= SECOND ("18:15:45") returns 45.
= SECOND ("2:15:05") returns 5.
= SECOND (NOW ()) returns 57 if NOW () returns 12/16/2016 10:07:57 AM.
53 Lectures
5.5 hours
Abhay Gadiya
24 Lectures
2 hours
Randy Minder
26 Lectures
4.5 hours
Randy Minder
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2064,
"s": 2001,
"text": "Returns the seconds of a time value, as a number from 0 to 59."
},
{
"code": null,
"e": 2086,
"s": 2064,
"text": "SECOND (<datetime>) \n"
},
{
"code": null,
"e": 2095,
"s": 2086,
"text": "datetime"
},
{
"code": null,
"e": 2161,
"s": 2095,
"text": "A datetime value representing time. E.g. 18:15:15 or 5:45:15 P.M."
},
{
"code": null,
"e": 2193,
"s": 2161,
"text": "An integer number from 0 to 59."
},
{
"code": null,
"e": 2285,
"s": 2193,
"text": "The parameter to the SECOND function is the time that contains the second you want to find."
},
{
"code": null,
"e": 2336,
"s": 2285,
"text": "You can specify the time as one of the following −"
},
{
"code": null,
"e": 2368,
"s": 2336,
"text": "Output of a date/time function."
},
{
"code": null,
"e": 2413,
"s": 2368,
"text": "An expression that returns a datetime value."
},
{
"code": null,
"e": 2458,
"s": 2413,
"text": "A value in one of the accepted time formats."
},
{
"code": null,
"e": 2501,
"s": 2458,
"text": "An accepted text representation of a time."
},
{
"code": null,
"e": 2830,
"s": 2501,
"text": "DAX SECOND function uses the locale and date/time settings of the client computer to understand the text value in order to perform the conversion. Most locales use the colon (:) as the time separator and any input text using colons as time separators will parse correctly. Review your locale settings to understand your results."
},
{
"code": null,
"e": 2970,
"s": 2830,
"text": "= SECOND (\"18:15:45\") returns 45. \n= SECOND (\"2:15:05\") returns 5. \n= SECOND (NOW ()) returns 57 if NOW () returns 12/16/2016 10:07:57 AM. "
},
{
"code": null,
"e": 3005,
"s": 2970,
"text": "\n 53 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3019,
"s": 3005,
"text": " Abhay Gadiya"
},
{
"code": null,
"e": 3052,
"s": 3019,
"text": "\n 24 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3066,
"s": 3052,
"text": " Randy Minder"
},
{
"code": null,
"e": 3101,
"s": 3066,
"text": "\n 26 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3115,
"s": 3101,
"text": " Randy Minder"
},
{
"code": null,
"e": 3122,
"s": 3115,
"text": " Print"
},
{
"code": null,
"e": 3133,
"s": 3122,
"text": " Add Notes"
}
]
|
How to return a string from a JavaScript function? | To return a string from a JavaScript function, use the return statement in JavaScript.
You need to run the following code to learn how to return a string using return statement −
<html>
<head>
<script>
function concatenate(name, subject) {
var val;
val = name + subject;
return val;
}
function DisplayFunction() {
var result;
result = concatenate('Amit', ' Java');
document.write (result );
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type = "button" onclick = "DisplayFunction()" value = "Result">
</form>
</body>
</html> | [
{
"code": null,
"e": 1149,
"s": 1062,
"text": "To return a string from a JavaScript function, use the return statement in JavaScript."
},
{
"code": null,
"e": 1241,
"s": 1149,
"text": "You need to run the following code to learn how to return a string using return statement −"
},
{
"code": null,
"e": 1800,
"s": 1241,
"text": "<html>\n <head>\n <script>\n function concatenate(name, subject) {\n var val;\n val = name + subject;\n return val;\n }\n function DisplayFunction() {\n var result;\n result = concatenate('Amit', ' Java');\n document.write (result );\n }\n </script>\n </head>\n \n <body>\n <p>Click the following button to call the function</p>\n <form>\n <input type = \"button\" onclick = \"DisplayFunction()\" value = \"Result\">\n </form>\n </body>\n</html>"
}
]
|
Multi-threaded Chat Application in Java | Set 2 (Client Side Programming) | 17 Jun, 2017
Prerequisites : Introducing threads in socket programming, Multi-threaded chat Application | Set 1
This article gives the implementation of client program for the multi-threaded chat application. Till now all examples in socket programming assume that client first sends some information and then server or other clients responds to that information.In real world, this might not be the case. It is not required to send someone a message in order to be able to receive one. A client should readily receive a message whenever it is delivered to it i.e sending and receiving must be implemented as separate activities rather than sequential.There is a very simple solution which uses threads to achieve this functionality. In the client side implementation we will be creating two threads:
SendMessage : This thread will be used for sending the message to other clients. The working is very simple, it takes input the message to send and the recipient to deliver to. Note that this implementation assumes the message to be of the format message # recipient, where recipient is the name of the recipient. It then writes the message on its output stream which is connected to the handler for this client. The handler breaks the message and recipient part and deliver to particular recipient. Lets look at how this thread can be implemented.Thread sendMessage = new Thread(new Runnable() { @Override public void run() { while (true) { // read the message to deliver. String msg = sc.nextLine(); try { // write on the output stream dos.writeUTF(msg); } catch (IOException e) { e.printStackTrace(); } } } });readMessage : A similar approach is taken for creating a thread for receiving the messages. When any client tries to write on this clients input stream, we use readUTF() method to read that message. The following snippet of how this thread is implemented is shown below-Thread readMessage = new Thread(new Runnable() { @Override public void run() { while (true) { try { // read the message sent to this client String msg = dis.readUTF(); System.out.println(msg); } catch (IOException e) { e.printStackTrace(); } } } });
SendMessage : This thread will be used for sending the message to other clients. The working is very simple, it takes input the message to send and the recipient to deliver to. Note that this implementation assumes the message to be of the format message # recipient, where recipient is the name of the recipient. It then writes the message on its output stream which is connected to the handler for this client. The handler breaks the message and recipient part and deliver to particular recipient. Lets look at how this thread can be implemented.Thread sendMessage = new Thread(new Runnable() { @Override public void run() { while (true) { // read the message to deliver. String msg = sc.nextLine(); try { // write on the output stream dos.writeUTF(msg); } catch (IOException e) { e.printStackTrace(); } } } });
Thread sendMessage = new Thread(new Runnable() { @Override public void run() { while (true) { // read the message to deliver. String msg = sc.nextLine(); try { // write on the output stream dos.writeUTF(msg); } catch (IOException e) { e.printStackTrace(); } } } });
readMessage : A similar approach is taken for creating a thread for receiving the messages. When any client tries to write on this clients input stream, we use readUTF() method to read that message. The following snippet of how this thread is implemented is shown below-Thread readMessage = new Thread(new Runnable() { @Override public void run() { while (true) { try { // read the message sent to this client String msg = dis.readUTF(); System.out.println(msg); } catch (IOException e) { e.printStackTrace(); } } } });
Thread readMessage = new Thread(new Runnable() { @Override public void run() { while (true) { try { // read the message sent to this client String msg = dis.readUTF(); System.out.println(msg); } catch (IOException e) { e.printStackTrace(); } } } });
The remaining steps of client side programming are similar to previous examples. A brief explanation is as follows –
Establish a Socket ConnectionCommunicationCommunication occurs with the help of the readMessage and sendMessage threads. Separate threads for reading and writing ensures simultaneous sending and receiving of messages.
Establish a Socket Connection
CommunicationCommunication occurs with the help of the readMessage and sendMessage threads. Separate threads for reading and writing ensures simultaneous sending and receiving of messages.
// Java implementation for multithreaded chat client// Save file as Client.java import java.io.*;import java.net.*;import java.util.Scanner; public class Client { final static int ServerPort = 1234; public static void main(String args[]) throws UnknownHostException, IOException { Scanner scn = new Scanner(System.in); // getting localhost ip InetAddress ip = InetAddress.getByName("localhost"); // establish the connection Socket s = new Socket(ip, ServerPort); // obtaining input and out streams DataInputStream dis = new DataInputStream(s.getInputStream()); DataOutputStream dos = new DataOutputStream(s.getOutputStream()); // sendMessage thread Thread sendMessage = new Thread(new Runnable() { @Override public void run() { while (true) { // read the message to deliver. String msg = scn.nextLine(); try { // write on the output stream dos.writeUTF(msg); } catch (IOException e) { e.printStackTrace(); } } } }); // readMessage thread Thread readMessage = new Thread(new Runnable() { @Override public void run() { while (true) { try { // read the message sent to this client String msg = dis.readUTF(); System.out.println(msg); } catch (IOException e) { e.printStackTrace(); } } } }); sendMessage.start(); readMessage.start(); }}
Output :From client 0 :
hello#client 1
client 1 : heya
how are you#client 1
client 1 : fine..how about you
logout
From client 1 :
client 0 : hello
heya#client 0
client 0 : how are you
fine..how about you#client 0
logout
Important points :
To send a message from any client, type the message, followed by a “#” and then the name of the recipient client. Please note that this implementation gives names as “client 0”, “client 1′′....”client n” and so carefully names must be appended int the end. After that press Enter key.
Once a message is sent, the handler for this client will receive the message and it will be delivered to the specified client.
If any client sends a message to this client, the readMessage thread will automatically print the message on the console.
Once a client is done with chatting, he can send a “logout” message without any recipient name so that server would know that this client has logged off the system. It is recommended to send a logout message before closing the terminal for the client to avoid any errors.
How to run the above program ?
Similar to previous examples, first run the server and then run multiple instances of the client. From each of the client, try sending message to each other. Please make sure you send message to only a valid client, i.e. to the client available on active list.
Suggested Improvements
This was only the explanation part as to how threads and socket programming can be used to create powerful programs. There are some suggested improvements to above implementations for the interested readers-
Create a graphical user interface for clients for sending and receiving messages. A tool such as Netbeans can be used to quickly design an interface
Currently the names are hard-coded as client 0, client 1. This can be improved to use user given nicknames.
This implementation can be further enhanced to provide client the list of current active users so that he can know who all of his friends are online. A simple method can be implemented for this purpose which when invoked prints the names in active list.
This article is contributed by Rishabh Mahrsee. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Java-Multithreading
Java-Networking
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n17 Jun, 2017"
},
{
"code": null,
"e": 153,
"s": 54,
"text": "Prerequisites : Introducing threads in socket programming, Multi-threaded chat Application | Set 1"
},
{
"code": null,
"e": 842,
"s": 153,
"text": "This article gives the implementation of client program for the multi-threaded chat application. Till now all examples in socket programming assume that client first sends some information and then server or other clients responds to that information.In real world, this might not be the case. It is not required to send someone a message in order to be able to receive one. A client should readily receive a message whenever it is delivered to it i.e sending and receiving must be implemented as separate activities rather than sequential.There is a very simple solution which uses threads to achieve this functionality. In the client side implementation we will be creating two threads:"
},
{
"code": null,
"e": 2640,
"s": 842,
"text": "SendMessage : This thread will be used for sending the message to other clients. The working is very simple, it takes input the message to send and the recipient to deliver to. Note that this implementation assumes the message to be of the format message # recipient, where recipient is the name of the recipient. It then writes the message on its output stream which is connected to the handler for this client. The handler breaks the message and recipient part and deliver to particular recipient. Lets look at how this thread can be implemented.Thread sendMessage = new Thread(new Runnable() { @Override public void run() { while (true) { // read the message to deliver. String msg = sc.nextLine(); try { // write on the output stream dos.writeUTF(msg); } catch (IOException e) { e.printStackTrace(); } } } });readMessage : A similar approach is taken for creating a thread for receiving the messages. When any client tries to write on this clients input stream, we use readUTF() method to read that message. The following snippet of how this thread is implemented is shown below-Thread readMessage = new Thread(new Runnable() { @Override public void run() { while (true) { try { // read the message sent to this client String msg = dis.readUTF(); System.out.println(msg); } catch (IOException e) { e.printStackTrace(); } } } });"
},
{
"code": null,
"e": 3692,
"s": 2640,
"text": "SendMessage : This thread will be used for sending the message to other clients. The working is very simple, it takes input the message to send and the recipient to deliver to. Note that this implementation assumes the message to be of the format message # recipient, where recipient is the name of the recipient. It then writes the message on its output stream which is connected to the handler for this client. The handler breaks the message and recipient part and deliver to particular recipient. Lets look at how this thread can be implemented.Thread sendMessage = new Thread(new Runnable() { @Override public void run() { while (true) { // read the message to deliver. String msg = sc.nextLine(); try { // write on the output stream dos.writeUTF(msg); } catch (IOException e) { e.printStackTrace(); } } } });"
},
{
"code": "Thread sendMessage = new Thread(new Runnable() { @Override public void run() { while (true) { // read the message to deliver. String msg = sc.nextLine(); try { // write on the output stream dos.writeUTF(msg); } catch (IOException e) { e.printStackTrace(); } } } });",
"e": 4196,
"s": 3692,
"text": null
},
{
"code": null,
"e": 4943,
"s": 4196,
"text": "readMessage : A similar approach is taken for creating a thread for receiving the messages. When any client tries to write on this clients input stream, we use readUTF() method to read that message. The following snippet of how this thread is implemented is shown below-Thread readMessage = new Thread(new Runnable() { @Override public void run() { while (true) { try { // read the message sent to this client String msg = dis.readUTF(); System.out.println(msg); } catch (IOException e) { e.printStackTrace(); } } } });"
},
{
"code": "Thread readMessage = new Thread(new Runnable() { @Override public void run() { while (true) { try { // read the message sent to this client String msg = dis.readUTF(); System.out.println(msg); } catch (IOException e) { e.printStackTrace(); } } } });",
"e": 5420,
"s": 4943,
"text": null
},
{
"code": null,
"e": 5537,
"s": 5420,
"text": "The remaining steps of client side programming are similar to previous examples. A brief explanation is as follows –"
},
{
"code": null,
"e": 5755,
"s": 5537,
"text": "Establish a Socket ConnectionCommunicationCommunication occurs with the help of the readMessage and sendMessage threads. Separate threads for reading and writing ensures simultaneous sending and receiving of messages."
},
{
"code": null,
"e": 5785,
"s": 5755,
"text": "Establish a Socket Connection"
},
{
"code": null,
"e": 5974,
"s": 5785,
"text": "CommunicationCommunication occurs with the help of the readMessage and sendMessage threads. Separate threads for reading and writing ensures simultaneous sending and receiving of messages."
},
{
"code": "// Java implementation for multithreaded chat client// Save file as Client.java import java.io.*;import java.net.*;import java.util.Scanner; public class Client { final static int ServerPort = 1234; public static void main(String args[]) throws UnknownHostException, IOException { Scanner scn = new Scanner(System.in); // getting localhost ip InetAddress ip = InetAddress.getByName(\"localhost\"); // establish the connection Socket s = new Socket(ip, ServerPort); // obtaining input and out streams DataInputStream dis = new DataInputStream(s.getInputStream()); DataOutputStream dos = new DataOutputStream(s.getOutputStream()); // sendMessage thread Thread sendMessage = new Thread(new Runnable() { @Override public void run() { while (true) { // read the message to deliver. String msg = scn.nextLine(); try { // write on the output stream dos.writeUTF(msg); } catch (IOException e) { e.printStackTrace(); } } } }); // readMessage thread Thread readMessage = new Thread(new Runnable() { @Override public void run() { while (true) { try { // read the message sent to this client String msg = dis.readUTF(); System.out.println(msg); } catch (IOException e) { e.printStackTrace(); } } } }); sendMessage.start(); readMessage.start(); }}",
"e": 7865,
"s": 5974,
"text": null
},
{
"code": null,
"e": 7889,
"s": 7865,
"text": "Output :From client 0 :"
},
{
"code": null,
"e": 7980,
"s": 7889,
"text": "hello#client 1\nclient 1 : heya\nhow are you#client 1\nclient 1 : fine..how about you\nlogout\n"
},
{
"code": null,
"e": 7996,
"s": 7980,
"text": "From client 1 :"
},
{
"code": null,
"e": 8087,
"s": 7996,
"text": "client 0 : hello\nheya#client 0\nclient 0 : how are you\nfine..how about you#client 0\nlogout\n"
},
{
"code": null,
"e": 8106,
"s": 8087,
"text": "Important points :"
},
{
"code": null,
"e": 8391,
"s": 8106,
"text": "To send a message from any client, type the message, followed by a “#” and then the name of the recipient client. Please note that this implementation gives names as “client 0”, “client 1′′....”client n” and so carefully names must be appended int the end. After that press Enter key."
},
{
"code": null,
"e": 8518,
"s": 8391,
"text": "Once a message is sent, the handler for this client will receive the message and it will be delivered to the specified client."
},
{
"code": null,
"e": 8640,
"s": 8518,
"text": "If any client sends a message to this client, the readMessage thread will automatically print the message on the console."
},
{
"code": null,
"e": 8912,
"s": 8640,
"text": "Once a client is done with chatting, he can send a “logout” message without any recipient name so that server would know that this client has logged off the system. It is recommended to send a logout message before closing the terminal for the client to avoid any errors."
},
{
"code": null,
"e": 8943,
"s": 8912,
"text": "How to run the above program ?"
},
{
"code": null,
"e": 9204,
"s": 8943,
"text": "Similar to previous examples, first run the server and then run multiple instances of the client. From each of the client, try sending message to each other. Please make sure you send message to only a valid client, i.e. to the client available on active list."
},
{
"code": null,
"e": 9227,
"s": 9204,
"text": "Suggested Improvements"
},
{
"code": null,
"e": 9435,
"s": 9227,
"text": "This was only the explanation part as to how threads and socket programming can be used to create powerful programs. There are some suggested improvements to above implementations for the interested readers-"
},
{
"code": null,
"e": 9584,
"s": 9435,
"text": "Create a graphical user interface for clients for sending and receiving messages. A tool such as Netbeans can be used to quickly design an interface"
},
{
"code": null,
"e": 9692,
"s": 9584,
"text": "Currently the names are hard-coded as client 0, client 1. This can be improved to use user given nicknames."
},
{
"code": null,
"e": 9946,
"s": 9692,
"text": "This implementation can be further enhanced to provide client the list of current active users so that he can know who all of his friends are online. A simple method can be implemented for this purpose which when invoked prints the names in active list."
},
{
"code": null,
"e": 10249,
"s": 9946,
"text": "This article is contributed by Rishabh Mahrsee. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 10374,
"s": 10249,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 10394,
"s": 10374,
"text": "Java-Multithreading"
},
{
"code": null,
"e": 10410,
"s": 10394,
"text": "Java-Networking"
},
{
"code": null,
"e": 10415,
"s": 10410,
"text": "Java"
},
{
"code": null,
"e": 10420,
"s": 10415,
"text": "Java"
}
]
|
List sublist() Method in Java with Examples | 19 Jun, 2019
This method gives a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive.
Syntax:
List subList(int fromIndex,
int toIndex)
Parameters: This function has two parameter fromIndex and toIndex, which are the starting and ending ranges respectively to create a sublist form the given list.
Returns: This method returns the view of list between the given ranges.
Below programs show the implementation of this method.
Program 1:
// Java code to show the implementation of// lastIndexOf method in list interfaceimport java.util.*;public class GfG { // Driver code public static void main(String[] args) { // Initializing a list of type Linkedlist List<Integer> l = new LinkedList<>(); l.add(1); l.add(3); l.add(5); l.add(7); l.add(3); System.out.println(l); System.out.println(l.lastIndexOf(3)); }}
[1, 3, 5, 7, 3]
4
[1, 3, 5, 7, 3]
4
Program 2: Below is the code to show implementation of list.subList() using Linkedlist.
// Java code to show the implementation of// subList method in list interfaceimport java.util.*;public class GfG { // Driver code public static void main(String[] args) { // Initializing a list of type Linkedlist List<Integer> l = new LinkedList<>(); l.add(10); l.add(30); l.add(50); l.add(70); l.add(30); List<Integer> sub = new LinkedList<>(); System.out.println(l); sub = l.subList(1, 3); System.out.println(sub); }}
[10, 30, 50, 70, 30]
[30, 50]
Reference:Oracle Docs
Akanksha_Rai
Java - util package
Java-Collections
Java-Functions
java-list
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Jun, 2019"
},
{
"code": null,
"e": 149,
"s": 28,
"text": "This method gives a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive."
},
{
"code": null,
"e": 157,
"s": 149,
"text": "Syntax:"
},
{
"code": null,
"e": 212,
"s": 157,
"text": "List subList(int fromIndex,\n int toIndex)"
},
{
"code": null,
"e": 374,
"s": 212,
"text": "Parameters: This function has two parameter fromIndex and toIndex, which are the starting and ending ranges respectively to create a sublist form the given list."
},
{
"code": null,
"e": 446,
"s": 374,
"text": "Returns: This method returns the view of list between the given ranges."
},
{
"code": null,
"e": 501,
"s": 446,
"text": "Below programs show the implementation of this method."
},
{
"code": null,
"e": 512,
"s": 501,
"text": "Program 1:"
},
{
"code": "// Java code to show the implementation of// lastIndexOf method in list interfaceimport java.util.*;public class GfG { // Driver code public static void main(String[] args) { // Initializing a list of type Linkedlist List<Integer> l = new LinkedList<>(); l.add(1); l.add(3); l.add(5); l.add(7); l.add(3); System.out.println(l); System.out.println(l.lastIndexOf(3)); }}",
"e": 960,
"s": 512,
"text": null
},
{
"code": null,
"e": 979,
"s": 960,
"text": "[1, 3, 5, 7, 3]\n4\n"
},
{
"code": null,
"e": 998,
"s": 979,
"text": "[1, 3, 5, 7, 3]\n4\n"
},
{
"code": null,
"e": 1086,
"s": 998,
"text": "Program 2: Below is the code to show implementation of list.subList() using Linkedlist."
},
{
"code": "// Java code to show the implementation of// subList method in list interfaceimport java.util.*;public class GfG { // Driver code public static void main(String[] args) { // Initializing a list of type Linkedlist List<Integer> l = new LinkedList<>(); l.add(10); l.add(30); l.add(50); l.add(70); l.add(30); List<Integer> sub = new LinkedList<>(); System.out.println(l); sub = l.subList(1, 3); System.out.println(sub); }}",
"e": 1599,
"s": 1086,
"text": null
},
{
"code": null,
"e": 1630,
"s": 1599,
"text": "[10, 30, 50, 70, 30]\n[30, 50]\n"
},
{
"code": null,
"e": 1652,
"s": 1630,
"text": "Reference:Oracle Docs"
},
{
"code": null,
"e": 1665,
"s": 1652,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 1685,
"s": 1665,
"text": "Java - util package"
},
{
"code": null,
"e": 1702,
"s": 1685,
"text": "Java-Collections"
},
{
"code": null,
"e": 1717,
"s": 1702,
"text": "Java-Functions"
},
{
"code": null,
"e": 1727,
"s": 1717,
"text": "java-list"
},
{
"code": null,
"e": 1732,
"s": 1727,
"text": "Java"
},
{
"code": null,
"e": 1737,
"s": 1732,
"text": "Java"
},
{
"code": null,
"e": 1754,
"s": 1737,
"text": "Java-Collections"
}
]
|
Python | Pandas Series.str.len() | 28 Sep, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas str.len() method is used to determine length of each string in a Pandas series. This method is only for series of strings.Since this is a string method, .str has to be prefixed everytime before calling this method. Otherwise it will give an error.
Syntax: Series.str.len()
Return type: Series of integer values. NULL values might be present too depending upon caller series.
To download the CSV used in code, click here.In the following examples, the data frame used contains data of some NBA players. The image of data frame before any operations is attached below.
Example #1: Calculating length of string series (dtype=str)
In this example, the string length of Name column is calculated using str.len() method. The dtype of the Series is already string. So there is no need of data type conversion. Before doing any operations, null rows are removed to avoid errors.
# importing pandas module import pandas as pd # reading csv file from url data = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv") # dropping null value columns to avoid errorsdata.dropna(inplace = True) # creating new column for len# passing values through str.len()data["Name Length"]= data["Name"].str.len() # displaydata
Output:As shown in the output image, the length of each string in name column is returned.Note:
This method doesn’t count length of integer or float series. It will give an error since it’s not a string series. The series need to be converted first ( Shown in next Example)
There is no parameter to handle null values. A null value would return null in the output string too.
Example #2:In this example, the length of salary column is calculated using the str.len() method. Since the series is imported as float64 dtype, it’s first converted to string using .astype() method.
# importing pandas module import pandas as pd # reading csv file from url data = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv") # dropping null value columns to avoid errorsdata.dropna(inplace = True) # converting to string dtypedata["Salary"]= data["Salary"].astype(str) # passing valuesdata["Salary Length"]= data["Salary"].str.len() # converting back to float dtypedata["Salary"]= data["Salary"].astype(float) # displaydata
Output:As shown in the output, length of int or float series can only be computed by converting it to string dtype.
Python pandas-series
Python pandas-series-methods
Python-pandas
Python-pandas-series-str
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
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n28 Sep, 2018"
},
{
"code": null,
"e": 267,
"s": 53,
"text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier."
},
{
"code": null,
"e": 522,
"s": 267,
"text": "Pandas str.len() method is used to determine length of each string in a Pandas series. This method is only for series of strings.Since this is a string method, .str has to be prefixed everytime before calling this method. Otherwise it will give an error."
},
{
"code": null,
"e": 547,
"s": 522,
"text": "Syntax: Series.str.len()"
},
{
"code": null,
"e": 649,
"s": 547,
"text": "Return type: Series of integer values. NULL values might be present too depending upon caller series."
},
{
"code": null,
"e": 841,
"s": 649,
"text": "To download the CSV used in code, click here.In the following examples, the data frame used contains data of some NBA players. The image of data frame before any operations is attached below."
},
{
"code": null,
"e": 901,
"s": 841,
"text": "Example #1: Calculating length of string series (dtype=str)"
},
{
"code": null,
"e": 1145,
"s": 901,
"text": "In this example, the string length of Name column is calculated using str.len() method. The dtype of the Series is already string. So there is no need of data type conversion. Before doing any operations, null rows are removed to avoid errors."
},
{
"code": "# importing pandas module import pandas as pd # reading csv file from url data = pd.read_csv(\"https://media.geeksforgeeks.org/wp-content/uploads/nba.csv\") # dropping null value columns to avoid errorsdata.dropna(inplace = True) # creating new column for len# passing values through str.len()data[\"Name Length\"]= data[\"Name\"].str.len() # displaydata",
"e": 1499,
"s": 1145,
"text": null
},
{
"code": null,
"e": 1595,
"s": 1499,
"text": "Output:As shown in the output image, the length of each string in name column is returned.Note:"
},
{
"code": null,
"e": 1773,
"s": 1595,
"text": "This method doesn’t count length of integer or float series. It will give an error since it’s not a string series. The series need to be converted first ( Shown in next Example)"
},
{
"code": null,
"e": 1875,
"s": 1773,
"text": "There is no parameter to handle null values. A null value would return null in the output string too."
},
{
"code": null,
"e": 2076,
"s": 1875,
"text": " Example #2:In this example, the length of salary column is calculated using the str.len() method. Since the series is imported as float64 dtype, it’s first converted to string using .astype() method."
},
{
"code": "# importing pandas module import pandas as pd # reading csv file from url data = pd.read_csv(\"https://media.geeksforgeeks.org/wp-content/uploads/nba.csv\") # dropping null value columns to avoid errorsdata.dropna(inplace = True) # converting to string dtypedata[\"Salary\"]= data[\"Salary\"].astype(str) # passing valuesdata[\"Salary Length\"]= data[\"Salary\"].str.len() # converting back to float dtypedata[\"Salary\"]= data[\"Salary\"].astype(float) # displaydata",
"e": 2537,
"s": 2076,
"text": null
},
{
"code": null,
"e": 2653,
"s": 2537,
"text": "Output:As shown in the output, length of int or float series can only be computed by converting it to string dtype."
},
{
"code": null,
"e": 2674,
"s": 2653,
"text": "Python pandas-series"
},
{
"code": null,
"e": 2703,
"s": 2674,
"text": "Python pandas-series-methods"
},
{
"code": null,
"e": 2717,
"s": 2703,
"text": "Python-pandas"
},
{
"code": null,
"e": 2742,
"s": 2717,
"text": "Python-pandas-series-str"
},
{
"code": null,
"e": 2749,
"s": 2742,
"text": "Python"
},
{
"code": null,
"e": 2847,
"s": 2749,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2879,
"s": 2847,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2906,
"s": 2879,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2927,
"s": 2906,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2950,
"s": 2927,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 3006,
"s": 2950,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 3037,
"s": 3006,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 3079,
"s": 3037,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 3121,
"s": 3079,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 3160,
"s": 3121,
"text": "Python | Get unique values from a list"
}
]
|
How to Use xlim() and ylim() in R? | 28 Nov, 2021
In this article, we will be looking at the different ways to use the xlim() and the ylim() functions in the R programming language.
The xlim() function with the provided parameters as the range of the x-axis in vectors is used to set the x-axis without dropping any data of the given plot or an object accordingly.
Syntax:
xlim(...)
Parameters:
...: if numeric, will create a continuous scale, if factor or character, will create a discrete scale.
Example:
In this example, we will be using the xlim() function to change the x-axis of the given bar plot in the R programming language.
R
# Datapoint for the barplotgfg<-c(1,4,6,5,7,5,4) # Creating bar plot and setting # the x-axis limitsbarplot(gfg,xlim=c(0,10))
Output:
The xlim() function with the provided parameters as the range of the y-axis in vectors is used to set the y-axis without dropping any data of the given plot or an object accordingly.
Syntax:
xlim(...)
Parameters:
...: if numeric, will create a continuous scale, if factor or character, will create a discrete scale.
Example:
In this example, we will be using the ylim() function to change the y-axis of the given bar plot (with the same data as in the previous example)in the R programming language.
R
# Datapoint for the barplotgfg<-c(1,4,6,5,7,5,4) # Creating bar plot and setting # the y-axis limitsbarplot(gfg,ylim=c(0,20))
Output:
Here, we will be using both xlim() and the ylim() function together to set the axis limits accordingly of both the x-axis and y-axis together in the same plot to get a clear idea of the outcomes, refer to the below example.
Example:
In this example, we will be using the xlim() and the ylim() function both together in the same barplot with the same data as the previous example and set the axis limits accordingly in the R programming language.
R
# Datapoint for the barplotgfg<-c(1,4,6,5,7,5,4) # Creating bar plot and setting the# x-axis and y-axis limitsbarplot(gfg,xlim=c(0,10),ylim=c(0,20))
Output:
Picked
R-Charts
R-Graphs
R-plots
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Nov, 2021"
},
{
"code": null,
"e": 160,
"s": 28,
"text": "In this article, we will be looking at the different ways to use the xlim() and the ylim() functions in the R programming language."
},
{
"code": null,
"e": 343,
"s": 160,
"text": "The xlim() function with the provided parameters as the range of the x-axis in vectors is used to set the x-axis without dropping any data of the given plot or an object accordingly."
},
{
"code": null,
"e": 351,
"s": 343,
"text": "Syntax:"
},
{
"code": null,
"e": 361,
"s": 351,
"text": "xlim(...)"
},
{
"code": null,
"e": 373,
"s": 361,
"text": "Parameters:"
},
{
"code": null,
"e": 476,
"s": 373,
"text": "...: if numeric, will create a continuous scale, if factor or character, will create a discrete scale."
},
{
"code": null,
"e": 485,
"s": 476,
"text": "Example:"
},
{
"code": null,
"e": 613,
"s": 485,
"text": "In this example, we will be using the xlim() function to change the x-axis of the given bar plot in the R programming language."
},
{
"code": null,
"e": 615,
"s": 613,
"text": "R"
},
{
"code": "# Datapoint for the barplotgfg<-c(1,4,6,5,7,5,4) # Creating bar plot and setting # the x-axis limitsbarplot(gfg,xlim=c(0,10))",
"e": 744,
"s": 615,
"text": null
},
{
"code": null,
"e": 752,
"s": 744,
"text": "Output:"
},
{
"code": null,
"e": 935,
"s": 752,
"text": "The xlim() function with the provided parameters as the range of the y-axis in vectors is used to set the y-axis without dropping any data of the given plot or an object accordingly."
},
{
"code": null,
"e": 943,
"s": 935,
"text": "Syntax:"
},
{
"code": null,
"e": 953,
"s": 943,
"text": "xlim(...)"
},
{
"code": null,
"e": 965,
"s": 953,
"text": "Parameters:"
},
{
"code": null,
"e": 1068,
"s": 965,
"text": "...: if numeric, will create a continuous scale, if factor or character, will create a discrete scale."
},
{
"code": null,
"e": 1077,
"s": 1068,
"text": "Example:"
},
{
"code": null,
"e": 1252,
"s": 1077,
"text": "In this example, we will be using the ylim() function to change the y-axis of the given bar plot (with the same data as in the previous example)in the R programming language."
},
{
"code": null,
"e": 1254,
"s": 1252,
"text": "R"
},
{
"code": "# Datapoint for the barplotgfg<-c(1,4,6,5,7,5,4) # Creating bar plot and setting # the y-axis limitsbarplot(gfg,ylim=c(0,20))",
"e": 1381,
"s": 1254,
"text": null
},
{
"code": null,
"e": 1389,
"s": 1381,
"text": "Output:"
},
{
"code": null,
"e": 1613,
"s": 1389,
"text": "Here, we will be using both xlim() and the ylim() function together to set the axis limits accordingly of both the x-axis and y-axis together in the same plot to get a clear idea of the outcomes, refer to the below example."
},
{
"code": null,
"e": 1622,
"s": 1613,
"text": "Example:"
},
{
"code": null,
"e": 1835,
"s": 1622,
"text": "In this example, we will be using the xlim() and the ylim() function both together in the same barplot with the same data as the previous example and set the axis limits accordingly in the R programming language."
},
{
"code": null,
"e": 1837,
"s": 1835,
"text": "R"
},
{
"code": "# Datapoint for the barplotgfg<-c(1,4,6,5,7,5,4) # Creating bar plot and setting the# x-axis and y-axis limitsbarplot(gfg,xlim=c(0,10),ylim=c(0,20))",
"e": 1987,
"s": 1837,
"text": null
},
{
"code": null,
"e": 1995,
"s": 1987,
"text": "Output:"
},
{
"code": null,
"e": 2002,
"s": 1995,
"text": "Picked"
},
{
"code": null,
"e": 2011,
"s": 2002,
"text": "R-Charts"
},
{
"code": null,
"e": 2020,
"s": 2011,
"text": "R-Graphs"
},
{
"code": null,
"e": 2028,
"s": 2020,
"text": "R-plots"
},
{
"code": null,
"e": 2039,
"s": 2028,
"text": "R Language"
}
]
|
D3.js line() method | 19 Aug, 2020
The d3.line() method is used to constructs a new line generator with the default settings. The line generator is then used to make a line.
Syntax:
d3.line();
Parameters: This method takes no parameters.
Return Value: This method returns a line Generator.
Example 1: Making a simple line using this method.
<!DOCTYPE html><html><meta charset="utf-8"><head> <title>Line in D3.js</title></head><script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.2/d3.min.js"></script> <style>path { fill: none; stroke: green;}</style> <body> <h1 style="text-align: center; color: green;">GeeksforGeeks</h1> <center> <svg width="500" height="500"> <path></path> </svg></center> <script> // Making a line Generator var Gen = d3.line(); var points = [ [0, 100], [500, 100] ]; var pathOfLine = Gen(points); d3.select('path') .attr('d', pathOfLine); </script></body></html>
Output:
Example 2: Making a Multiconnected line.
<!DOCTYPE html><html><meta charset="utf-8"><head> <title>Line in D3.js</title></head><script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.2/d3.min.js"></script> <style>path { fill: none; stroke: green;}</style> <body> <h1 style="text-align: center; color: green;">GeeksforGeeks</h1> <center> <svg width="500" height="500"> <path></path> </svg></center> <script> // Making a line Generator var Gen = d3.line(); var points = [ [0, 100], [500, 100], [200, 200], [500, 200] ]; var pathOfLine = Gen(points); d3.select('path') .attr('d', pathOfLine); </script></body></html>
Output:
D3.js
HTML
JavaScript
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Aug, 2020"
},
{
"code": null,
"e": 167,
"s": 28,
"text": "The d3.line() method is used to constructs a new line generator with the default settings. The line generator is then used to make a line."
},
{
"code": null,
"e": 175,
"s": 167,
"text": "Syntax:"
},
{
"code": null,
"e": 186,
"s": 175,
"text": "d3.line();"
},
{
"code": null,
"e": 231,
"s": 186,
"text": "Parameters: This method takes no parameters."
},
{
"code": null,
"e": 283,
"s": 231,
"text": "Return Value: This method returns a line Generator."
},
{
"code": null,
"e": 334,
"s": 283,
"text": "Example 1: Making a simple line using this method."
},
{
"code": "<!DOCTYPE html><html><meta charset=\"utf-8\"><head> <title>Line in D3.js</title></head><script src=\"https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.2/d3.min.js\"></script> <style>path { fill: none; stroke: green;}</style> <body> <h1 style=\"text-align: center; color: green;\">GeeksforGeeks</h1> <center> <svg width=\"500\" height=\"500\"> <path></path> </svg></center> <script> // Making a line Generator var Gen = d3.line(); var points = [ [0, 100], [500, 100] ]; var pathOfLine = Gen(points); d3.select('path') .attr('d', pathOfLine); </script></body></html>",
"e": 1006,
"s": 334,
"text": null
},
{
"code": null,
"e": 1014,
"s": 1006,
"text": "Output:"
},
{
"code": null,
"e": 1055,
"s": 1014,
"text": "Example 2: Making a Multiconnected line."
},
{
"code": "<!DOCTYPE html><html><meta charset=\"utf-8\"><head> <title>Line in D3.js</title></head><script src=\"https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.2/d3.min.js\"></script> <style>path { fill: none; stroke: green;}</style> <body> <h1 style=\"text-align: center; color: green;\">GeeksforGeeks</h1> <center> <svg width=\"500\" height=\"500\"> <path></path> </svg></center> <script> // Making a line Generator var Gen = d3.line(); var points = [ [0, 100], [500, 100], [200, 200], [500, 200] ]; var pathOfLine = Gen(points); d3.select('path') .attr('d', pathOfLine); </script></body></html>",
"e": 1773,
"s": 1055,
"text": null
},
{
"code": null,
"e": 1781,
"s": 1773,
"text": "Output:"
},
{
"code": null,
"e": 1787,
"s": 1781,
"text": "D3.js"
},
{
"code": null,
"e": 1792,
"s": 1787,
"text": "HTML"
},
{
"code": null,
"e": 1803,
"s": 1792,
"text": "JavaScript"
},
{
"code": null,
"e": 1820,
"s": 1803,
"text": "Web Technologies"
},
{
"code": null,
"e": 1825,
"s": 1820,
"text": "HTML"
}
]
|
Matplotlib.pyplot.axes() in Python | 17 May, 2020
Pyplot is another module of matplotlib that enables users to integrate MATLAB within Python environment, and thus providing MATLAB like interface and making Python visually interactive.
pyplot.axes is a function of the matplotlib library that adds axes to the current graph and makes it as current axes. Its output depends on the arguments used.
Syntax: matplotlib.pyplot.axes(*args, **kwargs)
Parameters:*args: It may include either None(nothing) or 4 tuples of float type
none: It gives a new full window axes
4 tuples: It takes 4 tuples as list i.e [left bottom width height] and gives a window of these dimensions as axes.
**kwargs: There are several keyword arguments(kwargs) used as parameters to pyplot.axes(), most common include facecolor, gid, in_layout, label, position, xlim, ylim, etc.
Example 1:
# importing matplot library along # with necessary modulesimport matplotlib.pyplot as plt # providing values to x and y x = [8, 5, 11, 13, 16, 23]y = [14, 8, 21, 7, 12, 15] # to plot x and yplt.plot(x, y) # to generate the full window axesplt.axes()
Output:
Example 2:
# importing matplot library along # with necessary modulesimport matplotlib.pyplot as plt # providing values to x and y x = [8, 5, 11, 13, 16, 23]y = [14, 8, 21, 7, 12, 15] # to plot x and y#plt.plot(x, y)# to generate window of custom # dimensions [left, bottom, width,# height] along with the facecolor plt.axes([0, 2.0, 2.0, 2.0], facecolor = 'black')
Output:
afshan_mairaj
Matplotlib Pyplot-class
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Create a directory in Python | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 May, 2020"
},
{
"code": null,
"e": 214,
"s": 28,
"text": "Pyplot is another module of matplotlib that enables users to integrate MATLAB within Python environment, and thus providing MATLAB like interface and making Python visually interactive."
},
{
"code": null,
"e": 374,
"s": 214,
"text": "pyplot.axes is a function of the matplotlib library that adds axes to the current graph and makes it as current axes. Its output depends on the arguments used."
},
{
"code": null,
"e": 422,
"s": 374,
"text": "Syntax: matplotlib.pyplot.axes(*args, **kwargs)"
},
{
"code": null,
"e": 502,
"s": 422,
"text": "Parameters:*args: It may include either None(nothing) or 4 tuples of float type"
},
{
"code": null,
"e": 540,
"s": 502,
"text": "none: It gives a new full window axes"
},
{
"code": null,
"e": 655,
"s": 540,
"text": "4 tuples: It takes 4 tuples as list i.e [left bottom width height] and gives a window of these dimensions as axes."
},
{
"code": null,
"e": 827,
"s": 655,
"text": "**kwargs: There are several keyword arguments(kwargs) used as parameters to pyplot.axes(), most common include facecolor, gid, in_layout, label, position, xlim, ylim, etc."
},
{
"code": null,
"e": 838,
"s": 827,
"text": "Example 1:"
},
{
"code": "# importing matplot library along # with necessary modulesimport matplotlib.pyplot as plt # providing values to x and y x = [8, 5, 11, 13, 16, 23]y = [14, 8, 21, 7, 12, 15] # to plot x and yplt.plot(x, y) # to generate the full window axesplt.axes()",
"e": 1093,
"s": 838,
"text": null
},
{
"code": null,
"e": 1101,
"s": 1093,
"text": "Output:"
},
{
"code": null,
"e": 1112,
"s": 1101,
"text": "Example 2:"
},
{
"code": "# importing matplot library along # with necessary modulesimport matplotlib.pyplot as plt # providing values to x and y x = [8, 5, 11, 13, 16, 23]y = [14, 8, 21, 7, 12, 15] # to plot x and y#plt.plot(x, y)# to generate window of custom # dimensions [left, bottom, width,# height] along with the facecolor plt.axes([0, 2.0, 2.0, 2.0], facecolor = 'black') ",
"e": 1472,
"s": 1112,
"text": null
},
{
"code": null,
"e": 1480,
"s": 1472,
"text": "Output:"
},
{
"code": null,
"e": 1494,
"s": 1480,
"text": "afshan_mairaj"
},
{
"code": null,
"e": 1518,
"s": 1494,
"text": "Matplotlib Pyplot-class"
},
{
"code": null,
"e": 1536,
"s": 1518,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 1543,
"s": 1536,
"text": "Python"
},
{
"code": null,
"e": 1641,
"s": 1543,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1673,
"s": 1641,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1700,
"s": 1673,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1731,
"s": 1700,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 1754,
"s": 1731,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1775,
"s": 1754,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1831,
"s": 1775,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 1873,
"s": 1831,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 1915,
"s": 1873,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 1954,
"s": 1915,
"text": "Python | Get unique values from a list"
}
]
|
Ruby | Array zip() function | 06 Dec, 2019
Array#zip() : zip() is a Array class method which Converts any arguments to arrays, then merges elements of self with corresponding elements from each argument.
Syntax: Array.zip()
Parameter: Array
Return: merges elements of self with corresponding elements from each argument.
Example #1 :
# Ruby code for zip() method # declaring arraya = [18, 22, 33, nil, 5, 6] # declaring arrayb = [1, 4, 1, 1, 88, 9] # declaring arrayc = [18, 22, 50, 6] # zip method exampleputs "zip() method form : #{a.zip(b)}\n\n" puts "zip() method form : #{b.zip(c)}\n\n" puts "zip() method form : #{c.zip(c)}\n\n"
Output :
zip() method form : [[18, 1], [22, 4], [33, 1], [nil, 1], [5, 88], [6, 9]]
zip() method form : [[1, 18], [4, 22], [1, 50], [1, 6], [88, nil], [9, nil]]
zip() method form : [[18, 18], [22, 22], [50, 50], [6, 6]]
Example #2 :
# Ruby code for zip() method # declaring arraya = ["abc", "nil", "dog"] # declaring arrayc = ["cat", nil] # declaring arrayb = ["cow", nil, "dog"] # zip method exampleputs "zip() method form : #{a.zip(b)}\n\n" puts "zip() method form : #{b.zip(c)}\n\n" puts "zip() method form : #{c.zip(c)}\n\n"
Output :
zip() method form : [["abc", "cow"], ["nil", nil], ["dog", "dog"]]
zip() method form : [["cow", "cat"], [nil, nil], ["dog", nil]]
zip() method form : [["cat", "cat"], [nil, nil]]
Ruby Array-class
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Make a Custom Array of Hashes in Ruby?
Ruby | Enumerator each_with_index function
Ruby | unless Statement and unless Modifier
Ruby on Rails Introduction
Ruby | String concat Method
Ruby | Array class find_index() operation
Ruby For Beginners
Ruby | Array shift() function
Ruby | Types of Variables | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 Dec, 2019"
},
{
"code": null,
"e": 189,
"s": 28,
"text": "Array#zip() : zip() is a Array class method which Converts any arguments to arrays, then merges elements of self with corresponding elements from each argument."
},
{
"code": null,
"e": 209,
"s": 189,
"text": "Syntax: Array.zip()"
},
{
"code": null,
"e": 226,
"s": 209,
"text": "Parameter: Array"
},
{
"code": null,
"e": 306,
"s": 226,
"text": "Return: merges elements of self with corresponding elements from each argument."
},
{
"code": null,
"e": 319,
"s": 306,
"text": "Example #1 :"
},
{
"code": "# Ruby code for zip() method # declaring arraya = [18, 22, 33, nil, 5, 6] # declaring arrayb = [1, 4, 1, 1, 88, 9] # declaring arrayc = [18, 22, 50, 6] # zip method exampleputs \"zip() method form : #{a.zip(b)}\\n\\n\" puts \"zip() method form : #{b.zip(c)}\\n\\n\" puts \"zip() method form : #{c.zip(c)}\\n\\n\"",
"e": 628,
"s": 319,
"text": null
},
{
"code": null,
"e": 637,
"s": 628,
"text": "Output :"
},
{
"code": null,
"e": 852,
"s": 637,
"text": "zip() method form : [[18, 1], [22, 4], [33, 1], [nil, 1], [5, 88], [6, 9]]\n\nzip() method form : [[1, 18], [4, 22], [1, 50], [1, 6], [88, nil], [9, nil]]\n\nzip() method form : [[18, 18], [22, 22], [50, 50], [6, 6]]\n\n"
},
{
"code": null,
"e": 865,
"s": 852,
"text": "Example #2 :"
},
{
"code": "# Ruby code for zip() method # declaring arraya = [\"abc\", \"nil\", \"dog\"] # declaring arrayc = [\"cat\", nil] # declaring arrayb = [\"cow\", nil, \"dog\"] # zip method exampleputs \"zip() method form : #{a.zip(b)}\\n\\n\" puts \"zip() method form : #{b.zip(c)}\\n\\n\" puts \"zip() method form : #{c.zip(c)}\\n\\n\"",
"e": 1169,
"s": 865,
"text": null
},
{
"code": null,
"e": 1178,
"s": 1169,
"text": "Output :"
},
{
"code": null,
"e": 1361,
"s": 1178,
"text": "zip() method form : [[\"abc\", \"cow\"], [\"nil\", nil], [\"dog\", \"dog\"]]\n\nzip() method form : [[\"cow\", \"cat\"], [nil, nil], [\"dog\", nil]]\n\nzip() method form : [[\"cat\", \"cat\"], [nil, nil]]\n\n"
},
{
"code": null,
"e": 1378,
"s": 1361,
"text": "Ruby Array-class"
},
{
"code": null,
"e": 1391,
"s": 1378,
"text": "Ruby-Methods"
},
{
"code": null,
"e": 1396,
"s": 1391,
"text": "Ruby"
},
{
"code": null,
"e": 1494,
"s": 1396,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1540,
"s": 1494,
"text": "How to Make a Custom Array of Hashes in Ruby?"
},
{
"code": null,
"e": 1583,
"s": 1540,
"text": "Ruby | Enumerator each_with_index function"
},
{
"code": null,
"e": 1627,
"s": 1583,
"text": "Ruby | unless Statement and unless Modifier"
},
{
"code": null,
"e": 1654,
"s": 1627,
"text": "Ruby on Rails Introduction"
},
{
"code": null,
"e": 1682,
"s": 1654,
"text": "Ruby | String concat Method"
},
{
"code": null,
"e": 1724,
"s": 1682,
"text": "Ruby | Array class find_index() operation"
},
{
"code": null,
"e": 1743,
"s": 1724,
"text": "Ruby For Beginners"
},
{
"code": null,
"e": 1773,
"s": 1743,
"text": "Ruby | Array shift() function"
}
]
|
Koch Curve or Koch Snowflake | 03 Oct, 2018
What is Koch Curve?
The Koch snowflake (also known as the Koch curve, Koch star, or Koch island) is a mathematical curve and one of the earliest fractal curves to have been described. It is based on the Koch curve, which appeared in a 1904 paper titled “On a continuous curve without tangents, constructible from elementary geometry” by the Swedish mathematician Helge von Koch.
The progression for the area of the snowflake converges to 8/5 times the area of the original triangle, while the progression for the snowflake’s perimeter diverges to infinity. Consequently, the snowflake has a finite area bounded by an infinitely long line.
Step1:
Draw an equilateral triangle. You can draw it with a compass or protractor, or just eyeball it if you don’t want to spend too much time drawing the snowflake.
It’s best if the length of the sides are divisible by 3, because of the nature of this fractal. This will become clear in the next few steps.
Step2:
Divide each side in three equal parts. This is why it is handy to have the sides divisible by three.
Step3:
Draw an equilateral triangle on each middle part. Measure the length of the middle third to know the length of the sides of these new triangles.
Step4:
Divide each outer side into thirds. You can see the 2nd generation of triangles covers a bit of the first. These three line segments shouldn’t be parted in three.
Step5:
Draw an equilateral triangle on each middle part.
Note how you draw each next generation of parts that are one 3rd of the mast one.
The Koch curve can be expressed by the following rewrite system (Lindenmayer system):
Alphabet : FConstants : +, ?Axiom : FProduction rules: F ? F+F–F+F
Here, F means “draw forward”, – means “turn right 60°”, and + means “turn left 60°”.To create the Koch snowflake, one would use F++F++F (an equilateral triangle) as the axiom.
# Python program to print partial Koch Curve.# importing the libraries : turtle standard # graphics library for pythonfrom turtle import * #function to create koch snowflake or koch curvedef snowflake(lengthSide, levels): if levels == 0: forward(lengthSide) return lengthSide /= 3.0 snowflake(lengthSide, levels-1) left(60) snowflake(lengthSide, levels-1) right(120) snowflake(lengthSide, levels-1) left(60) snowflake(lengthSide, levels-1) # main functionif __name__ == "__main__": # defining the speed of the turtle speed(0) length = 300.0 # Pull the pen up – no drawing when moving. penup() # Move the turtle backward by distance, # opposite to the direction the turtle # is headed. # Do not change the turtle’s heading. backward(length/2.0) # Pull the pen down – drawing when moving. pendown() snowflake(length, 4) # To control the closing windows of the turtle mainloop()
Output:
To create a full snowflake with Koch curve, we need to repeat the same pattern three times. So lets try that out.
# Python program to print complete Koch Curve.from turtle import * # function to create koch snowflake or koch curvedef snowflake(lengthSide, levels): if levels == 0: forward(lengthSide) return lengthSide /= 3.0 snowflake(lengthSide, levels-1) left(60) snowflake(lengthSide, levels-1) right(120) snowflake(lengthSide, levels-1) left(60) snowflake(lengthSide, levels-1) # main functionif __name__ == "__main__": # defining the speed of the turtle speed(0) length = 300.0 # Pull the pen up – no drawing when moving. # Move the turtle backward by distance, opposite # to the direction the turtle is headed. # Do not change the turtle’s heading. penup() backward(length/2.0) # Pull the pen down – drawing when moving. pendown() for i in range(3): snowflake(length, 4) right(120) # To control the closing windows of the turtle mainloop()
Output:
Video Playerhttps://media.geeksforgeeks.org/wp-content/uploads/output_2.mp400:0000:0000:20Use Up/Down Arrow keys to increase or decrease volume.
This article is contributed by Subhajit Saha. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
computer-graphics
Fractal
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Iterate over a list in Python
Python Classes and Objects
Convert integer to string in Python | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n03 Oct, 2018"
},
{
"code": null,
"e": 48,
"s": 28,
"text": "What is Koch Curve?"
},
{
"code": null,
"e": 407,
"s": 48,
"text": "The Koch snowflake (also known as the Koch curve, Koch star, or Koch island) is a mathematical curve and one of the earliest fractal curves to have been described. It is based on the Koch curve, which appeared in a 1904 paper titled “On a continuous curve without tangents, constructible from elementary geometry” by the Swedish mathematician Helge von Koch."
},
{
"code": null,
"e": 667,
"s": 407,
"text": "The progression for the area of the snowflake converges to 8/5 times the area of the original triangle, while the progression for the snowflake’s perimeter diverges to infinity. Consequently, the snowflake has a finite area bounded by an infinitely long line."
},
{
"code": null,
"e": 674,
"s": 667,
"text": "Step1:"
},
{
"code": null,
"e": 833,
"s": 674,
"text": "Draw an equilateral triangle. You can draw it with a compass or protractor, or just eyeball it if you don’t want to spend too much time drawing the snowflake."
},
{
"code": null,
"e": 975,
"s": 833,
"text": "It’s best if the length of the sides are divisible by 3, because of the nature of this fractal. This will become clear in the next few steps."
},
{
"code": null,
"e": 982,
"s": 975,
"text": "Step2:"
},
{
"code": null,
"e": 1083,
"s": 982,
"text": "Divide each side in three equal parts. This is why it is handy to have the sides divisible by three."
},
{
"code": null,
"e": 1090,
"s": 1083,
"text": "Step3:"
},
{
"code": null,
"e": 1235,
"s": 1090,
"text": "Draw an equilateral triangle on each middle part. Measure the length of the middle third to know the length of the sides of these new triangles."
},
{
"code": null,
"e": 1242,
"s": 1235,
"text": "Step4:"
},
{
"code": null,
"e": 1405,
"s": 1242,
"text": "Divide each outer side into thirds. You can see the 2nd generation of triangles covers a bit of the first. These three line segments shouldn’t be parted in three."
},
{
"code": null,
"e": 1412,
"s": 1405,
"text": "Step5:"
},
{
"code": null,
"e": 1462,
"s": 1412,
"text": "Draw an equilateral triangle on each middle part."
},
{
"code": null,
"e": 1544,
"s": 1462,
"text": "Note how you draw each next generation of parts that are one 3rd of the mast one."
},
{
"code": null,
"e": 1630,
"s": 1544,
"text": "The Koch curve can be expressed by the following rewrite system (Lindenmayer system):"
},
{
"code": null,
"e": 1697,
"s": 1630,
"text": "Alphabet : FConstants : +, ?Axiom : FProduction rules: F ? F+F–F+F"
},
{
"code": null,
"e": 1873,
"s": 1697,
"text": "Here, F means “draw forward”, – means “turn right 60°”, and + means “turn left 60°”.To create the Koch snowflake, one would use F++F++F (an equilateral triangle) as the axiom."
},
{
"code": "# Python program to print partial Koch Curve.# importing the libraries : turtle standard # graphics library for pythonfrom turtle import * #function to create koch snowflake or koch curvedef snowflake(lengthSide, levels): if levels == 0: forward(lengthSide) return lengthSide /= 3.0 snowflake(lengthSide, levels-1) left(60) snowflake(lengthSide, levels-1) right(120) snowflake(lengthSide, levels-1) left(60) snowflake(lengthSide, levels-1) # main functionif __name__ == \"__main__\": # defining the speed of the turtle speed(0) length = 300.0 # Pull the pen up – no drawing when moving. penup() # Move the turtle backward by distance, # opposite to the direction the turtle # is headed. # Do not change the turtle’s heading. backward(length/2.0) # Pull the pen down – drawing when moving. pendown() snowflake(length, 4) # To control the closing windows of the turtle mainloop() ",
"e": 2927,
"s": 1873,
"text": null
},
{
"code": null,
"e": 2935,
"s": 2927,
"text": "Output:"
},
{
"code": null,
"e": 3049,
"s": 2935,
"text": "To create a full snowflake with Koch curve, we need to repeat the same pattern three times. So lets try that out."
},
{
"code": "# Python program to print complete Koch Curve.from turtle import * # function to create koch snowflake or koch curvedef snowflake(lengthSide, levels): if levels == 0: forward(lengthSide) return lengthSide /= 3.0 snowflake(lengthSide, levels-1) left(60) snowflake(lengthSide, levels-1) right(120) snowflake(lengthSide, levels-1) left(60) snowflake(lengthSide, levels-1) # main functionif __name__ == \"__main__\": # defining the speed of the turtle speed(0) length = 300.0 # Pull the pen up – no drawing when moving. # Move the turtle backward by distance, opposite # to the direction the turtle is headed. # Do not change the turtle’s heading. penup() backward(length/2.0) # Pull the pen down – drawing when moving. pendown() for i in range(3): snowflake(length, 4) right(120) # To control the closing windows of the turtle mainloop() ",
"e": 4074,
"s": 3049,
"text": null
},
{
"code": null,
"e": 4082,
"s": 4074,
"text": "Output:"
},
{
"code": null,
"e": 4228,
"s": 4082,
"text": "Video Playerhttps://media.geeksforgeeks.org/wp-content/uploads/output_2.mp400:0000:0000:20Use Up/Down Arrow keys to increase or decrease volume.\n"
},
{
"code": null,
"e": 4529,
"s": 4228,
"text": "This article is contributed by Subhajit Saha. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 4654,
"s": 4529,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 4672,
"s": 4654,
"text": "computer-graphics"
},
{
"code": null,
"e": 4680,
"s": 4672,
"text": "Fractal"
},
{
"code": null,
"e": 4687,
"s": 4680,
"text": "Python"
},
{
"code": null,
"e": 4785,
"s": 4687,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4803,
"s": 4785,
"text": "Python Dictionary"
},
{
"code": null,
"e": 4845,
"s": 4803,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 4867,
"s": 4845,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 4902,
"s": 4867,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 4928,
"s": 4902,
"text": "Python String | replace()"
},
{
"code": null,
"e": 4960,
"s": 4928,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 4989,
"s": 4960,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 5019,
"s": 4989,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 5046,
"s": 5019,
"text": "Python Classes and Objects"
}
]
|
Python – Model Deployment Using TensorFlow Serving | 27 Jan, 2022
The most important part of the machine learning pipeline is the model deployment. Model Deployment means Deployment is the method by which you integrate a machine learning model into an existing production environment to allow it to use for practical purposes in real-time.
There are many ways to deploy a model. One way is to integrate a model with Django/Flask application with a script that takes input, load the model, and generates results. So, we can easily pass image data to the model and display results after the model generates the output. Below is the limitation of the above method:
Depending upon the size of the model, it will take some time to process input and generate results.
The model cannot be used in other applications. (Consider, we do not write any REST/gRPC API).
I/O processing is slow in Flask as compared to Node.
Training the model is also resource-intensive and time-consuming (Since it requires a lot of I/O and computation.
The other way is to deploy a model using TensorFlow serving. Since it also provides API (in form of REST and gRPC), so it is portable and can be used in different devices by using its API. It is easy to deploy and works well even for larger models.
Advantages of TensorFlow Serving:
Part of TensorFlow Extended (TFX) ecosystem.
Works well for large models (up to 2 GB).
Provides consistent API structures for the RESTful and gRPC client requests.
Can manage model versioning.
Used internally at Google
RESTful API:
TensorFlow Serving supports two types of client request format in the form of RESTful API.
Classify and Regress API
Predict API (For Prediction task)
Here, we will use predict API, the URL format for this will be:
POST http://{host}:{port}/v1/models/${MODEL_NAME}[/versions/${VERSION}|/labels/${LABEL}]:predict
and the request body contains a JSON object in the form of :
{
// (Optional) Serving signature to use.
// default : 'serving-default'
"signature_name": <string>,
// Instance : for row format (list, array etc.), inputs: for columns format.
// can have any one of them
"instances": <value>|<(nested)list>|<list-of-objects>
"inputs": <value>|<(nested)list>|<object>
}
gRPC API:
To use gRPC API, we install a package call tensorflow-serving-api using pip. More details about gRPC API endpoint are provided in code.
Implementation:
We will demonstrate the ability of TensorFlow Serving. First, we import (or install) the necessary modules, then we will train the model on CIFAR 10 dataset to 100 epochs. For production uses we can save this file as train.py
Code:
python3
# General import!pip install -Uq grpcio==1.26.0import numpy as npimport matplotlib.pyplot as pltimport osimport subprocessimport requestsimport json # TensorFlow Importsfrom tensorflow import kerasfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten,Dense, Dropoutfrom tensorflow.keras.models import Sequential,save_modelfrom tensorflow.keras.optimizers import SGDfrom tensorflow.keras.utils import to_categoricalfrom tensorflow.keras.datasets import cifar10 class_names =["airplane","automobile","bird","cat","deer","dog", "frog","horse", "ship","truck"]# load and preprocessdatasetdef load_and_preprocess(): (x_train, y_train), (x_test,y_test) = cifar_10.load_data() y_train = to_categorical(y_train) y_test = to_categorical(y_test) x_train = x_train.astype('float32') x_test = x_test.astype('float32') x_train = x_train/255 x_test = x_test/255 return (x_train, y_train), (x_test,y_test) # define model architecturedef get_model(): model = Sequential([ Conv2D(32, (3, 3), activation='relu', padding='same', input_shape=(32, 32, 3)), Conv2D(32, (3, 3), activation='relu', padding='same'), MaxPooling2D((2, 2)), Dropout(0.2), Conv2D(64, (3, 3), activation='relu', padding='same'), Conv2D(64, (3, 3), activation='relu', padding='same'), MaxPooling2D((2, 2)), Dropout(0.2), Flatten(), Dense(64, activation='relu'), Dense(10, activation='softmax') ]) model.compile( optimizer=SGD(learning_rate= 0.01 , momentum=0.1), loss='categorical_crossentropy', metrics=['accuracy'] ) model.summary() return model# train modelmodel = get_model()model.fit( x_train, y_train, epochs=100, validation_data=(x_test, y_test),
Model: "sequential_1"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
conv2d_4 (Conv2D) (None, 32, 32, 32) 896
_________________________________________________________________
conv2d_5 (Conv2D) (None, 32, 32, 32) 9248
_________________________________________________________________
max_pooling2d_2 (MaxPooling2 (None, 16, 16, 32) 0
_________________________________________________________________
dropout_2 (Dropout) (None, 16, 16, 32) 0
_________________________________________________________________
conv2d_6 (Conv2D) (None, 16, 16, 64) 18496
_________________________________________________________________
conv2d_7 (Conv2D) (None, 16, 16, 64) 36928
_________________________________________________________________
max_pooling2d_3 (MaxPooling2 (None, 8, 8, 64) 0
_________________________________________________________________
dropout_3 (Dropout) (None, 8, 8, 64) 0
_________________________________________________________________
flatten_1 (Flatten) (None, 4096) 0
_________________________________________________________________
dense_2 (Dense) (None, 64) 262208
_________________________________________________________________
dense_3 (Dense) (None, 10) 650
=================================================================
Total params: 328,426
Trainable params: 328,426
Non-trainable params: 0
_________________________________________________________________
Epoch 1/100
1563/1563 [==============================] - 7s
5ms/step - loss: 2.0344 - accuracy: 0.2537 - val_loss: 1.7737 - val_accuracy: 0.3691
Epoch 2/100
1563/1563 [==============================] - 7s
4ms/step - loss: 1.6704 - accuracy: 0.4036 - val_loss: 1.5645 - val_accuracy: 0.4289
Epoch 3/100
1563/1563 [==============================] - 7s
4ms/step - loss: 1.4688 - accuracy: 0.4723 - val_loss: 1.3854 - val_accuracy: 0.4999
Epoch 4/100
1563/1563 [==============================] - 7s
4ms/step - loss: 1.3209 - accuracy: 0.5288 - val_loss: 1.2357 - val_accuracy: 0.5540
Epoch 5/100
1563/1563 [==============================] - 7s
4ms/step - loss: 1.2046 - accuracy: 0.5699 - val_loss: 1.1413 - val_accuracy: 0.5935
Epoch 6/100
1563/1563 [==============================] - 7s
4ms/step - loss: 1.1088 - accuracy: 0.6082 - val_loss: 1.2331 - val_accuracy: 0.5572
Epoch 7/100
1563/1563 [==============================] - 7s
4ms/step - loss: 1.0248 - accuracy: 0.6373 - val_loss: 1.0139 - val_accuracy: 0.6389
Epoch 8/100
1563/1563 [==============================] - 7s
4ms/step - loss: 0.9613 - accuracy: 0.6605 - val_loss: 0.9723 - val_accuracy: 0.6577
.
.
.
.
.
Epoch 90/100
1563/1563 [==============================] - 7s
4ms/step - loss: 0.0775 - accuracy: 0.9734 - val_loss: 1.3356 - val_accuracy: 0.7473
Epoch 91/100
1563/1563 [==============================] - 7s
4ms/step - loss: 0.0739 - accuracy: 0.9740 - val_loss: 1.2990 - val_accuracy: 0.7681
Epoch 92/100
1563/1563 [==============================] - 7s
4ms/step - loss: 0.0743 - accuracy: 0.9739 - val_loss: 1.2629 - val_accuracy: 0.7655
Epoch 93/100
1563/1563 [==============================] - 7s
4ms/step - loss: 0.0740 - accuracy: 0.9743 - val_loss: 1.3276 - val_accuracy: 0.7635
Epoch 94/100
1563/1563 [==============================] - 7s
4ms/step - loss: 0.0724 - accuracy: 0.9746 - val_loss: 1.3179 - val_accuracy: 0.7656
Epoch 95/100
1563/1563 [==============================] - 7s
4ms/step - loss: 0.0737 - accuracy: 0.9740 - val_loss: 1.3039 - val_accuracy: 0.7677
Epoch 96/100
1563/1563 [==============================] - 7s
4ms/step - loss: 0.0736 - accuracy: 0.9734 - val_loss: 1.3243 - val_accuracy: 0.7653
Epoch 97/100
1563/1563 [==============================] - 7s
4ms/step - loss: 0.0704 - accuracy: 0.9756 - val_loss: 1.3264 - val_accuracy: 0.7660
Epoch 98/100
1563/1563 [==============================] - 7s
4ms/step - loss: 0.0693 - accuracy: 0.9757 - val_loss: 1.3284 - val_accuracy: 0.7658
Epoch 99/100
1563/1563 [==============================] - 7s
4ms/step - loss: 0.0668 - accuracy: 0.9764 - val_loss: 1.3649 - val_accuracy: 0.7636
Epoch 100/100
1563/1563 [==============================] - 7s
5ms/step - loss: 0.0710 - accuracy: 0.9749 - val_loss: 1.3206 - val_accuracy: 0.7682
<tensorflow.python.keras.callbacks.History at 0x7f36a042e7f0>
Then we save the model in the temp folder using TensorFlow save_model() and export it to Tar Gz for downloading.
Code:
python3
import tempfile MODEL_DIR = tempfile.gettempdir()version = 1export_path = os.path.join(MODEL_DIR, str(version))print('export_path = {}\n'.format(export_path)) save_model( model, export_path, overwrite=True, include_optimizer=True) print('\nSaved model:')!ls -l {export_path} # The command display input and output kayers with signature and data type# These details are required when we make gRPC API call!saved_model_cli show --dir {export_path} --all # Create a compressed model from the savedmodel .!tar -cz -f model.tar.gz --owner=0 --group=0 -C /tmp/1/ .
Now, We will host the model using TensorFlow Serving, we will demonstrate the hosting using two methods.
First, we will take advantage of colab environment and install TensorFlow Serving in that environment
Then, we will use the docker environment to host the model and use both gRPC and REST API to call the model and get predictions. Now, we will implement the first method.
Code:
python3
# Install TensorFlow Serving using Aptitude [For Debian]!echo "deb http://storage.googleapis.com/tensorflow-serving-apt""stable tensorflow-model-server tensorflow-model-server-universal" | tee /etc/apt/sources.list.d/tensorflow-serving.list && \!curl https://storage.googleapis.com/tensorflow-serving-apt/tensorflow-serving.release.pub.gpg | apt-key add -!apt update# Install TensorFlow Server!apt-get install tensorflow-model-server # Run TensorFlow Serving on a new thread os.environ["MODEL_DIR"] = MODEL_DIR %%bash --bgnohup tensorflow_model_server \ --rest_api_port=8501 \ --model_name=cifar_10 \ --model_base_path="${MODEL_DIR}" >server.log 2>&1
Starting job # 0 in a separate thread.
Now, we define the function to make REST API requests to the server. This will take random images from test dataset and send it to model (in the JSON format). The model then returns prediction in the JSON format.
Now, we will run our model on Docker Environment. It supports both CPU and GPU architecture and it is also recommended by developers at TensorFlow. For serving model, it provides a REST (def PORT: 8501) and gRPC[Remote Procedure Call] (def PORT: 8500) endpoint to communicate with models. We will host our model on docker using the following commands.
Code:
python3
# To TensorFlow Image from Docker Hub!docker pull tensorflow/serving# Run our model!docker run -p 8500:8500 -p 8501:8501 \ --mount type=bind,source=`pwd`/cifar_10/,target=/models/cifar_10 \ -e MODEL_NAME=cifar_10 -t tensorflow/serving
Now, we need to write a script to communicate with our model using REST and gRPC endpoints. Below is the script for REST endpoint. Save this code and run it in terminal using python. Download some images from CIFAR-10 dataset and test the results
Code:
python3
import jsonimport requestsimport sysfrom PIL import Imageimport numpy as np def get_rest_url(model_name, host='127.0.0.1', port='8501', task='predict', version=None): """ This function takes hostname, port, task (b/w predict and classify) and version to generate the URL path for REST API""" # Our REST URL should be http://127.0.0.1:8501/v1/models/cifar_10/predict url = "http://{host}:{port}/v1/models/{model_name}".format(host=host, port=port, model_name=model_name) if version: url += 'versions/{version}'.format(version=version) url += ':{task}'.format(task=task) return url def get_model_prediction(model_input, model_name='cifar_10', signature_name='serving_default'): """ This function sends request to the URL and get prediction in the form of response""" url = get_rest_url(model_name) image = Image.open(model_input) # convert image to array im = np.asarray(image) # add the 4th dimension im = np.expand_dims(im, axis=0) im= im/255 print("Image shape: ",im.shape) data = json.dumps({"signature_name": "serving_default", "instances": im.tolist()}) headers = {"content-type": "application/json"} # Send the post request and get response rv = requests.post(url, data=data, headers=headers) return rv.json()['predictions'] if __name__ == '__main__': class_names =["airplane","automobile","bird","cat","deer" ,"dog","frog","horse", "ship","truck"] print("\nGenerate REST url ...") url = get_rest_url(model_name='cifar_10') print(url) while True: print("\nEnter the image path [:q for Quit]") if sys.version_info[0] >= 3: path = str(input()) if path == ':q': break model_prediction = get_model_prediction(path) print("The model predicted ...") print(class_names[np.argmax(model_prediction)])
And the code below gRPC request. Here, it is important to get the right signature name (by default it is ‘serving default’) and the name of the input and output layers.
Code:
python3
import sysimport grpcfrom grpc.beta import implementationsimport tensorflow as tffrom PIL import Imageimport numpy as np# import prediction service functions from TF-Serving APIfrom tensorflow_serving.apis import predict_pb2from tensorflow_serving.apis import prediction_service_pb2, get_model_metadata_pb2from tensorflow_serving.apis import prediction_service_pb2_grpc def get_stub(host='127.0.0.1', port='8500'): channel = grpc.insecure_channel('127.0.0.1:8500') stub = prediction_service_pb2_grpc.PredictionServiceStub(channel) return stub def get_model_prediction(model_input, stub, model_name='cifar_10', signature_name='serving_default'): """ input => (image path, url, model_name, signature) output the results in the form of tf.array""" image = Image.open(model_input) im = np.asarray(image, dtype=np.float64) im = (im/255) im = np.expand_dims(im, axis=0) print("Image shape: ",im.shape) # We will be using Prediction Task so it uses predictRequest function from predict_pb2 request = predict_pb2.PredictRequest() request.model_spec.name = model_name request.model_spec.signature_name = signature_name #pass Image input to input layer (Here it is named 'conv2d_4_input') request.inputs['conv2d_4_input'].CopyFrom(tf.make_tensor_proto(im, dtype = tf.float32)) response = stub.Predict.future(request, 5.0) # get results from final layer(dense_3) return response.result().outputs["dense_3"].float_val def get_model_version(model_name, stub): request = get_model_metadata_pb2.GetModelMetadataRequest() request.model_spec.name = 'cifar_10' request.metadata_field.append("signature_def") response = stub.GetModelMetadata(request, 10) # signature of loaded model is available here: response.metadata['signature_def'] return response.model_spec.version.value if __name__ == '__main__': class_names =["airplane","automobile","bird","cat","deer","dog","frog","horse", "ship","truck"] print("\nCreate RPC connection ...") stub = get_stub() while True: print("\nEnter the image path [:q for Quit]") if sys.version_info[0] <= 3: path = raw_input() if sys.version_info[0] < 3 else input() if path == ':q': break model_input = str(path) model_prediction = get_model_prediction(model_input, stub) print(" Predictiom from Model ...") print(class_names[np.argmax(model_prediction)])
References:
TensorFlow Serving Docs
anikakapoor
sumitgumber28
simmytarika5
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Linear Regression
Reinforcement learning
Supervised and Unsupervised learning
Decision Tree Introduction with example
Search Algorithms in AI
Read JSON file using Python
Python map() function
Adding new column to existing DataFrame in Pandas
Python Dictionary
How to get column names in Pandas dataframe | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Jan, 2022"
},
{
"code": null,
"e": 302,
"s": 28,
"text": "The most important part of the machine learning pipeline is the model deployment. Model Deployment means Deployment is the method by which you integrate a machine learning model into an existing production environment to allow it to use for practical purposes in real-time."
},
{
"code": null,
"e": 624,
"s": 302,
"text": "There are many ways to deploy a model. One way is to integrate a model with Django/Flask application with a script that takes input, load the model, and generates results. So, we can easily pass image data to the model and display results after the model generates the output. Below is the limitation of the above method:"
},
{
"code": null,
"e": 724,
"s": 624,
"text": "Depending upon the size of the model, it will take some time to process input and generate results."
},
{
"code": null,
"e": 819,
"s": 724,
"text": "The model cannot be used in other applications. (Consider, we do not write any REST/gRPC API)."
},
{
"code": null,
"e": 872,
"s": 819,
"text": "I/O processing is slow in Flask as compared to Node."
},
{
"code": null,
"e": 986,
"s": 872,
"text": "Training the model is also resource-intensive and time-consuming (Since it requires a lot of I/O and computation."
},
{
"code": null,
"e": 1235,
"s": 986,
"text": "The other way is to deploy a model using TensorFlow serving. Since it also provides API (in form of REST and gRPC), so it is portable and can be used in different devices by using its API. It is easy to deploy and works well even for larger models."
},
{
"code": null,
"e": 1269,
"s": 1235,
"text": "Advantages of TensorFlow Serving:"
},
{
"code": null,
"e": 1314,
"s": 1269,
"text": "Part of TensorFlow Extended (TFX) ecosystem."
},
{
"code": null,
"e": 1356,
"s": 1314,
"text": "Works well for large models (up to 2 GB)."
},
{
"code": null,
"e": 1433,
"s": 1356,
"text": "Provides consistent API structures for the RESTful and gRPC client requests."
},
{
"code": null,
"e": 1462,
"s": 1433,
"text": "Can manage model versioning."
},
{
"code": null,
"e": 1488,
"s": 1462,
"text": "Used internally at Google"
},
{
"code": null,
"e": 1501,
"s": 1488,
"text": "RESTful API:"
},
{
"code": null,
"e": 1592,
"s": 1501,
"text": "TensorFlow Serving supports two types of client request format in the form of RESTful API."
},
{
"code": null,
"e": 1617,
"s": 1592,
"text": "Classify and Regress API"
},
{
"code": null,
"e": 1651,
"s": 1617,
"text": "Predict API (For Prediction task)"
},
{
"code": null,
"e": 1715,
"s": 1651,
"text": "Here, we will use predict API, the URL format for this will be:"
},
{
"code": null,
"e": 1812,
"s": 1715,
"text": "POST http://{host}:{port}/v1/models/${MODEL_NAME}[/versions/${VERSION}|/labels/${LABEL}]:predict"
},
{
"code": null,
"e": 1873,
"s": 1812,
"text": "and the request body contains a JSON object in the form of :"
},
{
"code": null,
"e": 2190,
"s": 1873,
"text": "{\n // (Optional) Serving signature to use.\n // default : 'serving-default'\n \"signature_name\": <string>,\n\n // Instance : for row format (list, array etc.), inputs: for columns format.\n // can have any one of them\n \"instances\": <value>|<(nested)list>|<list-of-objects>\n \"inputs\": <value>|<(nested)list>|<object>\n}"
},
{
"code": null,
"e": 2200,
"s": 2190,
"text": "gRPC API:"
},
{
"code": null,
"e": 2338,
"s": 2200,
"text": " To use gRPC API, we install a package call tensorflow-serving-api using pip. More details about gRPC API endpoint are provided in code."
},
{
"code": null,
"e": 2354,
"s": 2338,
"text": "Implementation:"
},
{
"code": null,
"e": 2580,
"s": 2354,
"text": "We will demonstrate the ability of TensorFlow Serving. First, we import (or install) the necessary modules, then we will train the model on CIFAR 10 dataset to 100 epochs. For production uses we can save this file as train.py"
},
{
"code": null,
"e": 2587,
"s": 2580,
"text": "Code: "
},
{
"code": null,
"e": 2595,
"s": 2587,
"text": "python3"
},
{
"code": "# General import!pip install -Uq grpcio==1.26.0import numpy as npimport matplotlib.pyplot as pltimport osimport subprocessimport requestsimport json # TensorFlow Importsfrom tensorflow import kerasfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten,Dense, Dropoutfrom tensorflow.keras.models import Sequential,save_modelfrom tensorflow.keras.optimizers import SGDfrom tensorflow.keras.utils import to_categoricalfrom tensorflow.keras.datasets import cifar10 class_names =[\"airplane\",\"automobile\",\"bird\",\"cat\",\"deer\",\"dog\", \"frog\",\"horse\", \"ship\",\"truck\"]# load and preprocessdatasetdef load_and_preprocess(): (x_train, y_train), (x_test,y_test) = cifar_10.load_data() y_train = to_categorical(y_train) y_test = to_categorical(y_test) x_train = x_train.astype('float32') x_test = x_test.astype('float32') x_train = x_train/255 x_test = x_test/255 return (x_train, y_train), (x_test,y_test) # define model architecturedef get_model(): model = Sequential([ Conv2D(32, (3, 3), activation='relu', padding='same', input_shape=(32, 32, 3)), Conv2D(32, (3, 3), activation='relu', padding='same'), MaxPooling2D((2, 2)), Dropout(0.2), Conv2D(64, (3, 3), activation='relu', padding='same'), Conv2D(64, (3, 3), activation='relu', padding='same'), MaxPooling2D((2, 2)), Dropout(0.2), Flatten(), Dense(64, activation='relu'), Dense(10, activation='softmax') ]) model.compile( optimizer=SGD(learning_rate= 0.01 , momentum=0.1), loss='categorical_crossentropy', metrics=['accuracy'] ) model.summary() return model# train modelmodel = get_model()model.fit( x_train, y_train, epochs=100, validation_data=(x_test, y_test),",
"e": 4339,
"s": 2595,
"text": null
},
{
"code": null,
"e": 9008,
"s": 4339,
"text": "Model: \"sequential_1\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\nconv2d_4 (Conv2D) (None, 32, 32, 32) 896 \n_________________________________________________________________\nconv2d_5 (Conv2D) (None, 32, 32, 32) 9248 \n_________________________________________________________________\nmax_pooling2d_2 (MaxPooling2 (None, 16, 16, 32) 0 \n_________________________________________________________________\ndropout_2 (Dropout) (None, 16, 16, 32) 0 \n_________________________________________________________________\nconv2d_6 (Conv2D) (None, 16, 16, 64) 18496 \n_________________________________________________________________\nconv2d_7 (Conv2D) (None, 16, 16, 64) 36928 \n_________________________________________________________________\nmax_pooling2d_3 (MaxPooling2 (None, 8, 8, 64) 0 \n_________________________________________________________________\ndropout_3 (Dropout) (None, 8, 8, 64) 0 \n_________________________________________________________________\nflatten_1 (Flatten) (None, 4096) 0 \n_________________________________________________________________\ndense_2 (Dense) (None, 64) 262208 \n_________________________________________________________________\ndense_3 (Dense) (None, 10) 650 \n=================================================================\nTotal params: 328,426\nTrainable params: 328,426\nNon-trainable params: 0\n_________________________________________________________________\nEpoch 1/100\n1563/1563 [==============================] - 7s \n5ms/step - loss: 2.0344 - accuracy: 0.2537 - val_loss: 1.7737 - val_accuracy: 0.3691\nEpoch 2/100\n1563/1563 [==============================] - 7s \n4ms/step - loss: 1.6704 - accuracy: 0.4036 - val_loss: 1.5645 - val_accuracy: 0.4289\nEpoch 3/100\n1563/1563 [==============================] - 7s \n4ms/step - loss: 1.4688 - accuracy: 0.4723 - val_loss: 1.3854 - val_accuracy: 0.4999\nEpoch 4/100\n1563/1563 [==============================] - 7s \n4ms/step - loss: 1.3209 - accuracy: 0.5288 - val_loss: 1.2357 - val_accuracy: 0.5540\nEpoch 5/100\n1563/1563 [==============================] - 7s \n4ms/step - loss: 1.2046 - accuracy: 0.5699 - val_loss: 1.1413 - val_accuracy: 0.5935\nEpoch 6/100\n1563/1563 [==============================] - 7s \n4ms/step - loss: 1.1088 - accuracy: 0.6082 - val_loss: 1.2331 - val_accuracy: 0.5572\nEpoch 7/100\n1563/1563 [==============================] - 7s \n4ms/step - loss: 1.0248 - accuracy: 0.6373 - val_loss: 1.0139 - val_accuracy: 0.6389\nEpoch 8/100\n1563/1563 [==============================] - 7s \n4ms/step - loss: 0.9613 - accuracy: 0.6605 - val_loss: 0.9723 - val_accuracy: 0.6577\n.\n.\n.\n.\n.\n\nEpoch 90/100\n1563/1563 [==============================] - 7s \n4ms/step - loss: 0.0775 - accuracy: 0.9734 - val_loss: 1.3356 - val_accuracy: 0.7473\nEpoch 91/100\n1563/1563 [==============================] - 7s \n4ms/step - loss: 0.0739 - accuracy: 0.9740 - val_loss: 1.2990 - val_accuracy: 0.7681\nEpoch 92/100\n1563/1563 [==============================] - 7s \n4ms/step - loss: 0.0743 - accuracy: 0.9739 - val_loss: 1.2629 - val_accuracy: 0.7655\nEpoch 93/100\n1563/1563 [==============================] - 7s \n4ms/step - loss: 0.0740 - accuracy: 0.9743 - val_loss: 1.3276 - val_accuracy: 0.7635\nEpoch 94/100\n1563/1563 [==============================] - 7s \n4ms/step - loss: 0.0724 - accuracy: 0.9746 - val_loss: 1.3179 - val_accuracy: 0.7656\nEpoch 95/100\n1563/1563 [==============================] - 7s \n4ms/step - loss: 0.0737 - accuracy: 0.9740 - val_loss: 1.3039 - val_accuracy: 0.7677\nEpoch 96/100\n1563/1563 [==============================] - 7s \n4ms/step - loss: 0.0736 - accuracy: 0.9734 - val_loss: 1.3243 - val_accuracy: 0.7653\nEpoch 97/100\n1563/1563 [==============================] - 7s \n4ms/step - loss: 0.0704 - accuracy: 0.9756 - val_loss: 1.3264 - val_accuracy: 0.7660\nEpoch 98/100\n1563/1563 [==============================] - 7s \n4ms/step - loss: 0.0693 - accuracy: 0.9757 - val_loss: 1.3284 - val_accuracy: 0.7658\nEpoch 99/100\n1563/1563 [==============================] - 7s \n4ms/step - loss: 0.0668 - accuracy: 0.9764 - val_loss: 1.3649 - val_accuracy: 0.7636\nEpoch 100/100\n1563/1563 [==============================] - 7s \n5ms/step - loss: 0.0710 - accuracy: 0.9749 - val_loss: 1.3206 - val_accuracy: 0.7682\n<tensorflow.python.keras.callbacks.History at 0x7f36a042e7f0>"
},
{
"code": null,
"e": 9121,
"s": 9008,
"text": "Then we save the model in the temp folder using TensorFlow save_model() and export it to Tar Gz for downloading."
},
{
"code": null,
"e": 9128,
"s": 9121,
"text": "Code: "
},
{
"code": null,
"e": 9136,
"s": 9128,
"text": "python3"
},
{
"code": "import tempfile MODEL_DIR = tempfile.gettempdir()version = 1export_path = os.path.join(MODEL_DIR, str(version))print('export_path = {}\\n'.format(export_path)) save_model( model, export_path, overwrite=True, include_optimizer=True) print('\\nSaved model:')!ls -l {export_path} # The command display input and output kayers with signature and data type# These details are required when we make gRPC API call!saved_model_cli show --dir {export_path} --all # Create a compressed model from the savedmodel .!tar -cz -f model.tar.gz --owner=0 --group=0 -C /tmp/1/ .",
"e": 9708,
"s": 9136,
"text": null
},
{
"code": null,
"e": 9815,
"s": 9708,
"text": "Now, We will host the model using TensorFlow Serving, we will demonstrate the hosting using two methods. "
},
{
"code": null,
"e": 9917,
"s": 9815,
"text": "First, we will take advantage of colab environment and install TensorFlow Serving in that environment"
},
{
"code": null,
"e": 10087,
"s": 9917,
"text": "Then, we will use the docker environment to host the model and use both gRPC and REST API to call the model and get predictions. Now, we will implement the first method."
},
{
"code": null,
"e": 10094,
"s": 10087,
"text": "Code: "
},
{
"code": null,
"e": 10102,
"s": 10094,
"text": "python3"
},
{
"code": "# Install TensorFlow Serving using Aptitude [For Debian]!echo \"deb http://storage.googleapis.com/tensorflow-serving-apt\"\"stable tensorflow-model-server tensorflow-model-server-universal\" | tee /etc/apt/sources.list.d/tensorflow-serving.list && \\!curl https://storage.googleapis.com/tensorflow-serving-apt/tensorflow-serving.release.pub.gpg | apt-key add -!apt update# Install TensorFlow Server!apt-get install tensorflow-model-server # Run TensorFlow Serving on a new thread os.environ[\"MODEL_DIR\"] = MODEL_DIR %%bash --bgnohup tensorflow_model_server \\ --rest_api_port=8501 \\ --model_name=cifar_10 \\ --model_base_path=\"${MODEL_DIR}\" >server.log 2>&1",
"e": 10762,
"s": 10102,
"text": null
},
{
"code": null,
"e": 10801,
"s": 10762,
"text": "Starting job # 0 in a separate thread."
},
{
"code": null,
"e": 11014,
"s": 10801,
"text": "Now, we define the function to make REST API requests to the server. This will take random images from test dataset and send it to model (in the JSON format). The model then returns prediction in the JSON format."
},
{
"code": null,
"e": 11366,
"s": 11014,
"text": "Now, we will run our model on Docker Environment. It supports both CPU and GPU architecture and it is also recommended by developers at TensorFlow. For serving model, it provides a REST (def PORT: 8501) and gRPC[Remote Procedure Call] (def PORT: 8500) endpoint to communicate with models. We will host our model on docker using the following commands."
},
{
"code": null,
"e": 11373,
"s": 11366,
"text": "Code: "
},
{
"code": null,
"e": 11381,
"s": 11373,
"text": "python3"
},
{
"code": "# To TensorFlow Image from Docker Hub!docker pull tensorflow/serving# Run our model!docker run -p 8500:8500 -p 8501:8501 \\ --mount type=bind,source=`pwd`/cifar_10/,target=/models/cifar_10 \\ -e MODEL_NAME=cifar_10 -t tensorflow/serving",
"e": 11618,
"s": 11381,
"text": null
},
{
"code": null,
"e": 11866,
"s": 11618,
"text": "Now, we need to write a script to communicate with our model using REST and gRPC endpoints. Below is the script for REST endpoint. Save this code and run it in terminal using python. Download some images from CIFAR-10 dataset and test the results"
},
{
"code": null,
"e": 11873,
"s": 11866,
"text": "Code: "
},
{
"code": null,
"e": 11881,
"s": 11873,
"text": "python3"
},
{
"code": "import jsonimport requestsimport sysfrom PIL import Imageimport numpy as np def get_rest_url(model_name, host='127.0.0.1', port='8501', task='predict', version=None): \"\"\" This function takes hostname, port, task (b/w predict and classify) and version to generate the URL path for REST API\"\"\" # Our REST URL should be http://127.0.0.1:8501/v1/models/cifar_10/predict url = \"http://{host}:{port}/v1/models/{model_name}\".format(host=host, port=port, model_name=model_name) if version: url += 'versions/{version}'.format(version=version) url += ':{task}'.format(task=task) return url def get_model_prediction(model_input, model_name='cifar_10', signature_name='serving_default'): \"\"\" This function sends request to the URL and get prediction in the form of response\"\"\" url = get_rest_url(model_name) image = Image.open(model_input) # convert image to array im = np.asarray(image) # add the 4th dimension im = np.expand_dims(im, axis=0) im= im/255 print(\"Image shape: \",im.shape) data = json.dumps({\"signature_name\": \"serving_default\", \"instances\": im.tolist()}) headers = {\"content-type\": \"application/json\"} # Send the post request and get response rv = requests.post(url, data=data, headers=headers) return rv.json()['predictions'] if __name__ == '__main__': class_names =[\"airplane\",\"automobile\",\"bird\",\"cat\",\"deer\" ,\"dog\",\"frog\",\"horse\", \"ship\",\"truck\"] print(\"\\nGenerate REST url ...\") url = get_rest_url(model_name='cifar_10') print(url) while True: print(\"\\nEnter the image path [:q for Quit]\") if sys.version_info[0] >= 3: path = str(input()) if path == ':q': break model_prediction = get_model_prediction(path) print(\"The model predicted ...\") print(class_names[np.argmax(model_prediction)])",
"e": 13810,
"s": 11881,
"text": null
},
{
"code": null,
"e": 13979,
"s": 13810,
"text": "And the code below gRPC request. Here, it is important to get the right signature name (by default it is ‘serving default’) and the name of the input and output layers."
},
{
"code": null,
"e": 13986,
"s": 13979,
"text": "Code: "
},
{
"code": null,
"e": 13994,
"s": 13986,
"text": "python3"
},
{
"code": "import sysimport grpcfrom grpc.beta import implementationsimport tensorflow as tffrom PIL import Imageimport numpy as np# import prediction service functions from TF-Serving APIfrom tensorflow_serving.apis import predict_pb2from tensorflow_serving.apis import prediction_service_pb2, get_model_metadata_pb2from tensorflow_serving.apis import prediction_service_pb2_grpc def get_stub(host='127.0.0.1', port='8500'): channel = grpc.insecure_channel('127.0.0.1:8500') stub = prediction_service_pb2_grpc.PredictionServiceStub(channel) return stub def get_model_prediction(model_input, stub, model_name='cifar_10', signature_name='serving_default'): \"\"\" input => (image path, url, model_name, signature) output the results in the form of tf.array\"\"\" image = Image.open(model_input) im = np.asarray(image, dtype=np.float64) im = (im/255) im = np.expand_dims(im, axis=0) print(\"Image shape: \",im.shape) # We will be using Prediction Task so it uses predictRequest function from predict_pb2 request = predict_pb2.PredictRequest() request.model_spec.name = model_name request.model_spec.signature_name = signature_name #pass Image input to input layer (Here it is named 'conv2d_4_input') request.inputs['conv2d_4_input'].CopyFrom(tf.make_tensor_proto(im, dtype = tf.float32)) response = stub.Predict.future(request, 5.0) # get results from final layer(dense_3) return response.result().outputs[\"dense_3\"].float_val def get_model_version(model_name, stub): request = get_model_metadata_pb2.GetModelMetadataRequest() request.model_spec.name = 'cifar_10' request.metadata_field.append(\"signature_def\") response = stub.GetModelMetadata(request, 10) # signature of loaded model is available here: response.metadata['signature_def'] return response.model_spec.version.value if __name__ == '__main__': class_names =[\"airplane\",\"automobile\",\"bird\",\"cat\",\"deer\",\"dog\",\"frog\",\"horse\", \"ship\",\"truck\"] print(\"\\nCreate RPC connection ...\") stub = get_stub() while True: print(\"\\nEnter the image path [:q for Quit]\") if sys.version_info[0] <= 3: path = raw_input() if sys.version_info[0] < 3 else input() if path == ':q': break model_input = str(path) model_prediction = get_model_prediction(model_input, stub) print(\" Predictiom from Model ...\") print(class_names[np.argmax(model_prediction)])",
"e": 16454,
"s": 13994,
"text": null
},
{
"code": null,
"e": 16466,
"s": 16454,
"text": "References:"
},
{
"code": null,
"e": 16490,
"s": 16466,
"text": "TensorFlow Serving Docs"
},
{
"code": null,
"e": 16502,
"s": 16490,
"text": "anikakapoor"
},
{
"code": null,
"e": 16516,
"s": 16502,
"text": "sumitgumber28"
},
{
"code": null,
"e": 16529,
"s": 16516,
"text": "simmytarika5"
},
{
"code": null,
"e": 16546,
"s": 16529,
"text": "Machine Learning"
},
{
"code": null,
"e": 16553,
"s": 16546,
"text": "Python"
},
{
"code": null,
"e": 16570,
"s": 16553,
"text": "Machine Learning"
},
{
"code": null,
"e": 16668,
"s": 16570,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 16691,
"s": 16668,
"text": "ML | Linear Regression"
},
{
"code": null,
"e": 16714,
"s": 16691,
"text": "Reinforcement learning"
},
{
"code": null,
"e": 16751,
"s": 16714,
"text": "Supervised and Unsupervised learning"
},
{
"code": null,
"e": 16791,
"s": 16751,
"text": "Decision Tree Introduction with example"
},
{
"code": null,
"e": 16815,
"s": 16791,
"text": "Search Algorithms in AI"
},
{
"code": null,
"e": 16843,
"s": 16815,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 16865,
"s": 16843,
"text": "Python map() function"
},
{
"code": null,
"e": 16915,
"s": 16865,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 16933,
"s": 16915,
"text": "Python Dictionary"
}
]
|
Using std::vector::reserve whenever possible | 09 Jun, 2022
In C++ vectors are dynamic arrays. Unlike arrays, they don’t have a fixed size. They can grow or shrink as required. Vectors are assigned memory in blocks of contiguous locations. When the memory allocated for the vector falls short of storing new elements, a new memory block is allocated to vector and all elements are copied from the old location to the new location. This reallocation of elements helps vectors to grow when required. However, it is a costly operation and time complexity is involved in this step is linear. std::vector class provides a useful function reserve which helps user specify the minimum size of the vector.It indicates that the vector is created such that it can store at least the number of the specified elements without having to reallocate memory.
std::vector::reserve
void reserve(size_type n)
Return Type: none
Arguments: n which denotes the no of elements to be stored in vector
Requests that vector is large enough to store n elements in the least.
If the current vector capacity is less than n, then reallocation will
take place. In other cases, reallocation will not happen. Function does
not modify existing elements in the vector
Each vector object has two parameters–size and capacity. The size denotes the number of elements currently stored in the vector while capacity is the maximum number of elements that the vector can store without reallocation. Evidently capacity >= size. When the vector runs out of space to store new elements i.e when size is becoming greater than capacity, the runtime library will request fresh memory from the heap and once memory is allocated, it will copy all elements in the vector from their old addresses to the newly allocated memory address. A call to the function reserve modifies the capacity parameter of the vector and so the vector requests sufficient memory to store the specified number of elements. Here is a program to demonstrate the performance improvement that can be obtained by using reserve function. In this program, we fill two vectors with a large number of elements and count the time taken to perform this step. For the first vector, we don’t specify the capacity, while for the second vector we specify the capacity using reserve().
Time Complexity – Linear O(N)
CPP
// CPP program to demonstrate use of// std::vector::reserve#include <chrono>#include <iostream>#include <vector> using std::vector;using std::cout;using namespace std::chrono; int main(){ // No of characters int N = (int)1e6; vector<int> v1, v2; // Reserve space in v2 v2.reserve(N); // Start filling up elements in v1 // To measure execution time in C++, refer below // https://www.geeksforgeeks.org/measure-execution-time-function-cpp/ auto start = high_resolution_clock::now(); for (int i = 0; i < N; ++i) v1.push_back(i); auto stop = high_resolution_clock::now(); auto duration = duration_cast<microseconds>(stop - start); cout << "Method I took " << duration.count() << " microseconds\n"; // Start filling up elements in v2 start = high_resolution_clock::now(); for (int i = 0; i < N; ++i) v2.push_back(i); stop = high_resolution_clock::now(); duration = duration_cast<microseconds>(stop - start); cout << "Method II took " << duration.count() << " microseconds \n"; return 0;}
Output: (Machine Dependent)
Method I took 18699 microseconds
Method II took 16276 microseconds
Note: It is guaranteed that reserving space beforehand will take less time than trying to insert the elements without specifying the size of the vector. Further, it adds semantic utility to the code and we get to know at least how large the vector is going to be.
AdityaKumawat1
surinderdawra388
utkarshgupta110092
cpp-vector
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting a vector in C++
Polymorphism in C++
Pair in C++ Standard Template Library (STL)
Friend class and function in C++
std::string class in C++
Queue in C++ Standard Template Library (STL)
std::find in C++
Unordered Sets in C++ Standard Template Library
List in C++ Standard Template Library (STL)
vector insert() function in C++ STL | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n09 Jun, 2022"
},
{
"code": null,
"e": 835,
"s": 52,
"text": "In C++ vectors are dynamic arrays. Unlike arrays, they don’t have a fixed size. They can grow or shrink as required. Vectors are assigned memory in blocks of contiguous locations. When the memory allocated for the vector falls short of storing new elements, a new memory block is allocated to vector and all elements are copied from the old location to the new location. This reallocation of elements helps vectors to grow when required. However, it is a costly operation and time complexity is involved in this step is linear. std::vector class provides a useful function reserve which helps user specify the minimum size of the vector.It indicates that the vector is created such that it can store at least the number of the specified elements without having to reallocate memory."
},
{
"code": null,
"e": 856,
"s": 835,
"text": "std::vector::reserve"
},
{
"code": null,
"e": 1228,
"s": 856,
"text": "void reserve(size_type n)\nReturn Type: none\nArguments: n which denotes the no of elements to be stored in vector\n\nRequests that vector is large enough to store n elements in the least. \nIf the current vector capacity is less than n, then reallocation will \ntake place. In other cases, reallocation will not happen. Function does\nnot modify existing elements in the vector"
},
{
"code": null,
"e": 2294,
"s": 1228,
"text": " Each vector object has two parameters–size and capacity. The size denotes the number of elements currently stored in the vector while capacity is the maximum number of elements that the vector can store without reallocation. Evidently capacity >= size. When the vector runs out of space to store new elements i.e when size is becoming greater than capacity, the runtime library will request fresh memory from the heap and once memory is allocated, it will copy all elements in the vector from their old addresses to the newly allocated memory address. A call to the function reserve modifies the capacity parameter of the vector and so the vector requests sufficient memory to store the specified number of elements. Here is a program to demonstrate the performance improvement that can be obtained by using reserve function. In this program, we fill two vectors with a large number of elements and count the time taken to perform this step. For the first vector, we don’t specify the capacity, while for the second vector we specify the capacity using reserve(). "
},
{
"code": null,
"e": 2324,
"s": 2294,
"text": "Time Complexity – Linear O(N)"
},
{
"code": null,
"e": 2328,
"s": 2324,
"text": "CPP"
},
{
"code": "// CPP program to demonstrate use of// std::vector::reserve#include <chrono>#include <iostream>#include <vector> using std::vector;using std::cout;using namespace std::chrono; int main(){ // No of characters int N = (int)1e6; vector<int> v1, v2; // Reserve space in v2 v2.reserve(N); // Start filling up elements in v1 // To measure execution time in C++, refer below // https://www.geeksforgeeks.org/measure-execution-time-function-cpp/ auto start = high_resolution_clock::now(); for (int i = 0; i < N; ++i) v1.push_back(i); auto stop = high_resolution_clock::now(); auto duration = duration_cast<microseconds>(stop - start); cout << \"Method I took \" << duration.count() << \" microseconds\\n\"; // Start filling up elements in v2 start = high_resolution_clock::now(); for (int i = 0; i < N; ++i) v2.push_back(i); stop = high_resolution_clock::now(); duration = duration_cast<microseconds>(stop - start); cout << \"Method II took \" << duration.count() << \" microseconds \\n\"; return 0;}",
"e": 3401,
"s": 2328,
"text": null
},
{
"code": null,
"e": 3429,
"s": 3401,
"text": "Output: (Machine Dependent)"
},
{
"code": null,
"e": 3497,
"s": 3429,
"text": "Method I took 18699 microseconds\nMethod II took 16276 microseconds "
},
{
"code": null,
"e": 3761,
"s": 3497,
"text": "Note: It is guaranteed that reserving space beforehand will take less time than trying to insert the elements without specifying the size of the vector. Further, it adds semantic utility to the code and we get to know at least how large the vector is going to be."
},
{
"code": null,
"e": 3776,
"s": 3761,
"text": "AdityaKumawat1"
},
{
"code": null,
"e": 3793,
"s": 3776,
"text": "surinderdawra388"
},
{
"code": null,
"e": 3812,
"s": 3793,
"text": "utkarshgupta110092"
},
{
"code": null,
"e": 3823,
"s": 3812,
"text": "cpp-vector"
},
{
"code": null,
"e": 3827,
"s": 3823,
"text": "STL"
},
{
"code": null,
"e": 3831,
"s": 3827,
"text": "C++"
},
{
"code": null,
"e": 3835,
"s": 3831,
"text": "STL"
},
{
"code": null,
"e": 3839,
"s": 3835,
"text": "CPP"
},
{
"code": null,
"e": 3937,
"s": 3839,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3961,
"s": 3937,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 3981,
"s": 3961,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 4025,
"s": 3981,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 4058,
"s": 4025,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 4083,
"s": 4058,
"text": "std::string class in C++"
},
{
"code": null,
"e": 4128,
"s": 4083,
"text": "Queue in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 4145,
"s": 4128,
"text": "std::find in C++"
},
{
"code": null,
"e": 4193,
"s": 4145,
"text": "Unordered Sets in C++ Standard Template Library"
},
{
"code": null,
"e": 4237,
"s": 4193,
"text": "List in C++ Standard Template Library (STL)"
}
]
|
Flattening a Linked List | 17 Jun, 2022
Given a linked list where every node represents a linked list and contains two pointers of its type:
Pointer to next node in the main list (we call it ‘right’ pointer in the code below) Pointer to a linked list where this node is headed (we call it the ‘down’ pointer in the code below).
Pointer to next node in the main list (we call it ‘right’ pointer in the code below)
Pointer to a linked list where this node is headed (we call it the ‘down’ pointer in the code below).
All linked lists are sorted. See the following example
5 -> 10 -> 19 -> 28
| | | |
V V V V
7 20 22 35
| | |
V V V
8 50 40
| |
V V
30 45
Write a function flatten() to flatten the lists into a single linked list. The flattened linked list should also be sorted. For example, for the above input list, output list should be 5->7->8->10->19->20->22->28->30->35->40->45->50.
The idea is to use the Merge() process of merge sort for linked lists. We use merge() to merge lists one by one. We recursively merge() the current list with the already flattened list. The down pointer is used to link nodes of the flattened list.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for flattening a Linked List#include <bits/stdc++.h>using namespace std; // Link list nodeclass Node{ public: int data; Node *right, *down;}; Node* head = NULL; // An utility function to merge two sorted// linked listsNode* merge(Node* a, Node* b){ // If first linked list is empty then second // is the answer if (a == NULL) return b; // If second linked list is empty then first // is the result if (b == NULL) return a; // Compare the data members of the two linked // lists and put the larger one in the result Node* result; if (a->data < b->data) { result = a; result->down = merge(a->down, b); } else { result = b; result->down = merge(a, b->down); } result->right = NULL; return result;} Node* flatten(Node* root){ // Base Cases if (root == NULL || root->right == NULL) return root; // Recur for list on right root->right = flatten(root->right); // Now merge root = merge(root, root->right); // Return the root // it will be in turn merged with its left return root;} // Utility function to insert a node at// beginning of the linked listNode* push(Node* head_ref, int data){ // Allocate the Node & Put in the data Node* new_node = new Node(); new_node->data = data; new_node->right = NULL; // Make next of new Node as head new_node->down = head_ref; // Move the head to point to new Node head_ref = new_node; return head_ref;} void printList(){ Node* temp = head; while (temp != NULL) { cout << temp->data << " "; temp = temp->down; } cout << endl;} // Driver codeint main(){ /* Let us create the following linked list 5 -> 10 -> 19 -> 28 | | | | V V V V 7 20 22 35 | | | V V V 8 50 40 | | V V 30 45 */ head = push(head, 30); head = push(head, 8); head = push(head, 7); head = push(head, 5); head->right = push(head->right, 20); head->right = push(head->right, 10); head->right->right = push(head->right->right, 50); head->right->right = push(head->right->right, 22); head->right->right = push(head->right->right, 19); head->right->right->right = push(head->right->right->right, 45); head->right->right->right = push(head->right->right->right, 40); head->right->right->right = push(head->right->right->right, 35); head->right->right->right = push(head->right->right->right, 20); // Flatten the list head = flatten(head); printList(); return 0;} // This code is contributed by rajsanghavi9.
// Java program for flattening a Linked Listclass LinkedList{ Node head; // head of list /* Linked list Node*/ class Node { int data; Node right, down; Node(int data) { this.data = data; right = null; down = null; } } // An utility function to merge two sorted linked lists Node merge(Node a, Node b) { // if first linked list is empty then second // is the answer if (a == null) return b; // if second linked list is empty then first // is the result if (b == null) return a; // compare the data members of the two linked lists // and put the larger one in the result Node result; if (a.data < b.data) { result = a; result.down = merge(a.down, b); } else { result = b; result.down = merge(a, b.down); } result.right = null; return result; } Node flatten(Node root) { // Base Cases if (root == null || root.right == null) return root; // recur for list on right root.right = flatten(root.right); // now merge root = merge(root, root.right); // return the root // it will be in turn merged with its left return root; } /* Utility function to insert a node at beginning of the linked list */ Node push(Node head_ref, int data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(data); /* 3. Make next of new Node as head */ new_node.down = head_ref; /* 4. Move the head to point to new Node */ head_ref = new_node; /*5. return to link it back */ return head_ref; } void printList() { Node temp = head; while (temp != null) { System.out.print(temp.data + " "); temp = temp.down; } System.out.println(); } /* Driver program to test above functions */ public static void main(String args[]) { LinkedList L = new LinkedList(); /* Let us create the following linked list 5 -> 10 -> 19 -> 28 | | | | V V V V 7 20 22 35 | | | V V V 8 50 40 | | V V 30 45 */ L.head = L.push(L.head, 30); L.head = L.push(L.head, 8); L.head = L.push(L.head, 7); L.head = L.push(L.head, 5); L.head.right = L.push(L.head.right, 20); L.head.right = L.push(L.head.right, 10); L.head.right.right = L.push(L.head.right.right, 50); L.head.right.right = L.push(L.head.right.right, 22); L.head.right.right = L.push(L.head.right.right, 19); L.head.right.right.right = L.push(L.head.right.right.right, 45); L.head.right.right.right = L.push(L.head.right.right.right, 40); L.head.right.right.right = L.push(L.head.right.right.right, 35); L.head.right.right.right = L.push(L.head.right.right.right, 20); // flatten the list L.head = L.flatten(L.head); L.printList(); }} /* This code is contributed by Rajat Mishra */
# Python program for flattening a Linked List class Node(): def __init__(self,data): self.data = data self.right = None self.down = None class LinkedList(): def __init__(self): # head of list self.head = None # Utility function to insert a node at beginning of the # linked list def push(self,head_ref,data): # 1 & 2: Allocate the Node & # Put in the data new_node = Node(data) # Make next of new Node as head new_node.down = head_ref # 4. Move the head to point to new Node head_ref = new_node # 5. return to link it back return head_ref def printList(self): temp = self.head while(temp != None): print(temp.data,end=" ") temp = temp.down print() # An utility function to merge two sorted linked lists def merge(self, a, b): # if first linked list is empty then second # is the answer if(a == None): return b # if second linked list is empty then first # is the result if(b == None): return a # compare the data members of the two linked lists # and put the larger one in the result result = None if (a.data < b.data): result = a result.down = self.merge(a.down,b) else: result = b result.down = self.merge(a,b.down) result.right = None return result def flatten(self, root): # Base Case if(root == None or root.right == None): return root # recur for list on right root.right = self.flatten(root.right) # now merge root = self.merge(root, root.right) # return the root # it will be in turn merged with its left return root # Driver program to test above functionsL = LinkedList() '''Let us create the following linked list 5 -> 10 -> 19 -> 28 | | | | V V V V 7 20 22 35 | | | V V V 8 50 40 | | V V 30 45'''L.head = L.push(L.head, 30);L.head = L.push(L.head, 8);L.head = L.push(L.head, 7);L.head = L.push(L.head, 5); L.head.right = L.push(L.head.right, 20);L.head.right = L.push(L.head.right, 10); L.head.right.right = L.push(L.head.right.right, 50);L.head.right.right = L.push(L.head.right.right, 22);L.head.right.right = L.push(L.head.right.right, 19); L.head.right.right.right = L.push(L.head.right.right.right, 45);L.head.right.right.right = L.push(L.head.right.right.right, 40);L.head.right.right.right = L.push(L.head.right.right.right, 35);L.head.right.right.right = L.push(L.head.right.right.right, 20); # flatten the listL.head = L.flatten(L.head); L.printList()# This code is contributed by maheshwaripiyush9
// C# program for flattening a Linked Listusing System;public class List { Node head; // head of list /* Linked list Node */ public class Node { public int data; public Node right, down; public Node(int data) { this.data = data; right = null; down = null; } } // An utility function to merge two sorted linked lists Node merge(Node a, Node b) { // if first linked list is empty then second // is the answer if (a == null) return b; // if second linked list is empty then first // is the result if (b == null) return a; // compare the data members of the two linked lists // and put the larger one in the result Node result; if (a.data < b.data) { result = a; result.down = merge(a.down, b); } else { result = b; result.down = merge(a, b.down); } result.right = null; return result; } Node flatten(Node root) { // Base Cases if (root == null || root.right == null) return root; // recur for list on right root.right = flatten(root.right); // now merge root = merge(root, root.right); // return the root // it will be in turn merged with its left return root; } /* * Utility function to insert a node at beginning of the linked list */ Node Push(Node head_ref, int data) { /* * 1 & 2: Allocate the Node & Put in the data */ Node new_node = new Node(data); /* 3. Make next of new Node as head */ new_node.down = head_ref; /* 4. Move the head to point to new Node */ head_ref = new_node; /* 5. return to link it back */ return head_ref; } void printList() { Node temp = head; while (temp != null) { Console.Write(temp.data + " "); temp = temp.down; } Console.WriteLine(); } /* Driver program to test above functions */ public static void Main(String []args) { List L = new List(); /* * Let us create the following linked list 5 -> 10 -> 19 -> 28 | | | | V V V V 7 * 20 22 35 | | | V V V 8 50 40 | | V V 30 45 */ L.head = L.Push(L.head, 30); L.head = L.Push(L.head, 8); L.head = L.Push(L.head, 7); L.head = L.Push(L.head, 5); L.head.right = L.Push(L.head.right, 20); L.head.right = L.Push(L.head.right, 10); L.head.right.right = L.Push(L.head.right.right, 50); L.head.right.right = L.Push(L.head.right.right, 22); L.head.right.right = L.Push(L.head.right.right, 19); L.head.right.right.right = L.Push(L.head.right.right.right, 45); L.head.right.right.right = L.Push(L.head.right.right.right, 40); L.head.right.right.right = L.Push(L.head.right.right.right, 35); L.head.right.right.right = L.Push(L.head.right.right.right, 20); // flatten the list L.head = L.flatten(L.head); L.printList(); }} // This code is contributed by umadevi9616
<script>// javascript program for flattening a Linked Listvar head; // head of list /* Linked list Node */ class Node { constructor(val) { this.data = val; this.down = null; this.next = null; } } // An utility function to merge two sorted linked lists function merge(a, b) { // if first linked list is empty then second // is the answer if (a == null) return b; // if second linked list is empty then first // is the result if (b == null) return a; // compare the data members of the two linked lists // and put the larger one in the result var result; if (a.data < b.data) { result = a; result.down = merge(a.down, b); } else { result = b; result.down = merge(a, b.down); } result.right = null; return result; } function flatten(root) { // Base Cases if (root == null || root.right == null) return root; // recur for list on right root.right = flatten(root.right); // now merge root = merge(root, root.right); // return the root // it will be in turn merged with its left return root; } /* * Utility function to insert a node at beginning of the linked list */ function push(head_ref , data) { /* * 1 & 2: Allocate the Node & Put in the data */ var new_node = new Node(data); /* 3. Make next of new Node as head */ new_node.down = head_ref; /* 4. Move the head to point to new Node */ head_ref = new_node; /* 5. return to link it back */ return head_ref; } function printList() { var temp = head; while (temp != null) { document.write(temp.data + " "); temp = temp.down; } document.write(); } /* Driver program to test above functions */ /* * Let us create the following linked list 5 -> 10 -> 19 -> 28 | | | | V V V V 7 * 20 22 35 | | | V V V 8 50 40 | | V V 30 45 */ head = push(head, 30); head = push(head, 8); head = push(head, 7); head = push(head, 5); head.right = push(head.right, 20); head.right = push(head.right, 10); head.right.right = push(head.right.right, 50); head.right.right = push(head.right.right, 22); head.right.right = push(head.right.right, 19); head.right.right.right = push(head.right.right.right, 45); head.right.right.right = push(head.right.right.right, 40); head.right.right.right = push(head.right.right.right, 35); head.right.right.right = push(head.right.right.right, 20); // flatten the list head = flatten(head); printList(); // This code contributed by aashish1995</script>
5 7 8 10 19 20 20 22 30 35 40 45 50
Time Complexity: O(N*N*M) – where N is the no of nodes in main linked list (reachable using right pointer) and M is the no of node in a single sub linked list (reachable using down pointer).
Explanation: As we are merging 2 lists at a time,
After adding first 2 lists, time taken will be O(M+M) = O(2M).
Then we will merge another list to above merged list -> time = O(2M + M) = O(3M).
Then we will merge another list -> time = O(3M + M).
We will keep merging lists to previously merged lists until all lists are merged.
Total time taken will be O(2M + 3M + 4M + .... N*M) = (2 + 3 + 4 + ... + N)*M
Using arithmetic sum formula: time = O((N*N + N – 2)*M/2)
Above expression is roughly equal to O(N*N*M) for large value of N
Space Complexity: O(N*M) – because of the recursion. The recursive functions will use recursive stack of size equivalent to total number of elements in the lists, which is N*M.
The idea is, to build min-heap and use Extract-min property to get minimum element from priority queue.
C++
#include <bits/stdc++.h> struct Node { int data; struct Node* next; struct Node* bottom; Node(int x) { data = x; next = NULL; bottom = NULL; }}; using namespace std; void flatten(Node* root); int main(void){ //this code builds the flattened linked list //of first picture in this article ; Node* head=new Node(5); auto temp=head; auto bt=head; bt->bottom=new Node(7); bt->bottom->bottom=new Node(8); bt->bottom->bottom->bottom=new Node(30); temp->next=new Node(10); temp=temp->next; bt=temp; bt->bottom=new Node(20); temp->next=new Node(19); temp=temp->next; bt=temp; bt->bottom=new Node(22); bt->bottom->bottom=new Node(50); temp->next=new Node(28); temp=temp->next; bt=temp; bt->bottom=new Node(35); bt->bottom->bottom=new Node(40); bt->bottom->bottom->bottom=new Node(45); flatten(head); cout << endl; return 0;} struct mycomp { bool operator()(Node* a, Node* b) { return a->data > b->data; }};void flatten(Node* root){ priority_queue<Node*, vector<Node*>, mycomp> p; //pushing main link nodes into priority_queue. while (root!=NULL) { p.push(root); root = root->next; } while (!p.empty()) { //extracting min auto k = p.top(); p.pop(); //printing least element cout << k->data << " "; if (k->bottom) p.push(k->bottom); } }//this code is contributed by user_990i
5 7 8 10 19 20 22 28 30 35 40 45 50
Time Complexity: O(N*M*log(N)) – where N is the no of nodes in main linked list (reachable using next pointer) and M is the no of node in a single sub linked list (reachable using bottom pointer).
Explanation:
1. Push all the nodes that are reachable using next pointer into priority queue till we encounter NULL.
2.while(priority_queue is not empty)
(i) Extract Node which contains minimum-value(k) from priority_queue and print k->data.
(ii) If k->bottom!=NULL ,insert k->bottom into priority_queue. Else our priority_queue size will decrease.
Space Complexity: O(N)-where N is the no of nodes in main linked list (reachable using next pointer).
NOTE: In above explanation, k means the Node which contains minimum-element.
YouTube<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=PSKZJDtitZw" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
kaviarasu
cherry0697
Akanksha_Rai
aashish1995
umadevi9616
maheswaripiyush9
rajsanghavi9
simranarora5sos
tanmayvijay
sagartomar9927
sweetyty
avtarkumar719
user_990i
hardikkoriintern
24*7 Innovation Labs
Amazon
Drishti-Soft
Flipkart
Goldman Sachs
Microsoft
Paytm
Payu
Snapdeal
Visa
Linked List
Paytm
Flipkart
Amazon
Microsoft
Snapdeal
24*7 Innovation Labs
Payu
Visa
Goldman Sachs
Drishti-Soft
Linked List
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stack Data Structure (Introduction and Program)
LinkedList in Java
Introduction to Data Structures
What is Data Structure: Types, Classifications and Applications
Implementing a Linked List in Java using Class
Add two numbers represented by linked lists | Set 1
Detect and Remove Loop in a Linked List
Queue - Linked List Implementation
Function to check if a singly linked list is palindrome
Implement a stack using singly linked list | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n17 Jun, 2022"
},
{
"code": null,
"e": 154,
"s": 52,
"text": "Given a linked list where every node represents a linked list and contains two pointers of its type: "
},
{
"code": null,
"e": 342,
"s": 154,
"text": "Pointer to next node in the main list (we call it ‘right’ pointer in the code below) Pointer to a linked list where this node is headed (we call it the ‘down’ pointer in the code below). "
},
{
"code": null,
"e": 428,
"s": 342,
"text": "Pointer to next node in the main list (we call it ‘right’ pointer in the code below) "
},
{
"code": null,
"e": 531,
"s": 428,
"text": "Pointer to a linked list where this node is headed (we call it the ‘down’ pointer in the code below). "
},
{
"code": null,
"e": 588,
"s": 531,
"text": "All linked lists are sorted. See the following example "
},
{
"code": null,
"e": 852,
"s": 588,
"text": " 5 -> 10 -> 19 -> 28\n | | | |\n V V V V\n 7 20 22 35\n | | |\n V V V\n 8 50 40\n | |\n V V\n 30 45"
},
{
"code": null,
"e": 1087,
"s": 852,
"text": "Write a function flatten() to flatten the lists into a single linked list. The flattened linked list should also be sorted. For example, for the above input list, output list should be 5->7->8->10->19->20->22->28->30->35->40->45->50. "
},
{
"code": null,
"e": 1335,
"s": 1087,
"text": "The idea is to use the Merge() process of merge sort for linked lists. We use merge() to merge lists one by one. We recursively merge() the current list with the already flattened list. The down pointer is used to link nodes of the flattened list."
},
{
"code": null,
"e": 1386,
"s": 1335,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1390,
"s": 1386,
"text": "C++"
},
{
"code": null,
"e": 1395,
"s": 1390,
"text": "Java"
},
{
"code": null,
"e": 1403,
"s": 1395,
"text": "Python3"
},
{
"code": null,
"e": 1406,
"s": 1403,
"text": "C#"
},
{
"code": null,
"e": 1417,
"s": 1406,
"text": "Javascript"
},
{
"code": "// C++ program for flattening a Linked List#include <bits/stdc++.h>using namespace std; // Link list nodeclass Node{ public: int data; Node *right, *down;}; Node* head = NULL; // An utility function to merge two sorted// linked listsNode* merge(Node* a, Node* b){ // If first linked list is empty then second // is the answer if (a == NULL) return b; // If second linked list is empty then first // is the result if (b == NULL) return a; // Compare the data members of the two linked // lists and put the larger one in the result Node* result; if (a->data < b->data) { result = a; result->down = merge(a->down, b); } else { result = b; result->down = merge(a, b->down); } result->right = NULL; return result;} Node* flatten(Node* root){ // Base Cases if (root == NULL || root->right == NULL) return root; // Recur for list on right root->right = flatten(root->right); // Now merge root = merge(root, root->right); // Return the root // it will be in turn merged with its left return root;} // Utility function to insert a node at// beginning of the linked listNode* push(Node* head_ref, int data){ // Allocate the Node & Put in the data Node* new_node = new Node(); new_node->data = data; new_node->right = NULL; // Make next of new Node as head new_node->down = head_ref; // Move the head to point to new Node head_ref = new_node; return head_ref;} void printList(){ Node* temp = head; while (temp != NULL) { cout << temp->data << \" \"; temp = temp->down; } cout << endl;} // Driver codeint main(){ /* Let us create the following linked list 5 -> 10 -> 19 -> 28 | | | | V V V V 7 20 22 35 | | | V V V 8 50 40 | | V V 30 45 */ head = push(head, 30); head = push(head, 8); head = push(head, 7); head = push(head, 5); head->right = push(head->right, 20); head->right = push(head->right, 10); head->right->right = push(head->right->right, 50); head->right->right = push(head->right->right, 22); head->right->right = push(head->right->right, 19); head->right->right->right = push(head->right->right->right, 45); head->right->right->right = push(head->right->right->right, 40); head->right->right->right = push(head->right->right->right, 35); head->right->right->right = push(head->right->right->right, 20); // Flatten the list head = flatten(head); printList(); return 0;} // This code is contributed by rajsanghavi9.",
"e": 4206,
"s": 1417,
"text": null
},
{
"code": "// Java program for flattening a Linked Listclass LinkedList{ Node head; // head of list /* Linked list Node*/ class Node { int data; Node right, down; Node(int data) { this.data = data; right = null; down = null; } } // An utility function to merge two sorted linked lists Node merge(Node a, Node b) { // if first linked list is empty then second // is the answer if (a == null) return b; // if second linked list is empty then first // is the result if (b == null) return a; // compare the data members of the two linked lists // and put the larger one in the result Node result; if (a.data < b.data) { result = a; result.down = merge(a.down, b); } else { result = b; result.down = merge(a, b.down); } result.right = null; return result; } Node flatten(Node root) { // Base Cases if (root == null || root.right == null) return root; // recur for list on right root.right = flatten(root.right); // now merge root = merge(root, root.right); // return the root // it will be in turn merged with its left return root; } /* Utility function to insert a node at beginning of the linked list */ Node push(Node head_ref, int data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(data); /* 3. Make next of new Node as head */ new_node.down = head_ref; /* 4. Move the head to point to new Node */ head_ref = new_node; /*5. return to link it back */ return head_ref; } void printList() { Node temp = head; while (temp != null) { System.out.print(temp.data + \" \"); temp = temp.down; } System.out.println(); } /* Driver program to test above functions */ public static void main(String args[]) { LinkedList L = new LinkedList(); /* Let us create the following linked list 5 -> 10 -> 19 -> 28 | | | | V V V V 7 20 22 35 | | | V V V 8 50 40 | | V V 30 45 */ L.head = L.push(L.head, 30); L.head = L.push(L.head, 8); L.head = L.push(L.head, 7); L.head = L.push(L.head, 5); L.head.right = L.push(L.head.right, 20); L.head.right = L.push(L.head.right, 10); L.head.right.right = L.push(L.head.right.right, 50); L.head.right.right = L.push(L.head.right.right, 22); L.head.right.right = L.push(L.head.right.right, 19); L.head.right.right.right = L.push(L.head.right.right.right, 45); L.head.right.right.right = L.push(L.head.right.right.right, 40); L.head.right.right.right = L.push(L.head.right.right.right, 35); L.head.right.right.right = L.push(L.head.right.right.right, 20); // flatten the list L.head = L.flatten(L.head); L.printList(); }} /* This code is contributed by Rajat Mishra */",
"e": 7606,
"s": 4206,
"text": null
},
{
"code": "# Python program for flattening a Linked List class Node(): def __init__(self,data): self.data = data self.right = None self.down = None class LinkedList(): def __init__(self): # head of list self.head = None # Utility function to insert a node at beginning of the # linked list def push(self,head_ref,data): # 1 & 2: Allocate the Node & # Put in the data new_node = Node(data) # Make next of new Node as head new_node.down = head_ref # 4. Move the head to point to new Node head_ref = new_node # 5. return to link it back return head_ref def printList(self): temp = self.head while(temp != None): print(temp.data,end=\" \") temp = temp.down print() # An utility function to merge two sorted linked lists def merge(self, a, b): # if first linked list is empty then second # is the answer if(a == None): return b # if second linked list is empty then first # is the result if(b == None): return a # compare the data members of the two linked lists # and put the larger one in the result result = None if (a.data < b.data): result = a result.down = self.merge(a.down,b) else: result = b result.down = self.merge(a,b.down) result.right = None return result def flatten(self, root): # Base Case if(root == None or root.right == None): return root # recur for list on right root.right = self.flatten(root.right) # now merge root = self.merge(root, root.right) # return the root # it will be in turn merged with its left return root # Driver program to test above functionsL = LinkedList() '''Let us create the following linked list 5 -> 10 -> 19 -> 28 | | | | V V V V 7 20 22 35 | | | V V V 8 50 40 | | V V 30 45'''L.head = L.push(L.head, 30);L.head = L.push(L.head, 8);L.head = L.push(L.head, 7);L.head = L.push(L.head, 5); L.head.right = L.push(L.head.right, 20);L.head.right = L.push(L.head.right, 10); L.head.right.right = L.push(L.head.right.right, 50);L.head.right.right = L.push(L.head.right.right, 22);L.head.right.right = L.push(L.head.right.right, 19); L.head.right.right.right = L.push(L.head.right.right.right, 45);L.head.right.right.right = L.push(L.head.right.right.right, 40);L.head.right.right.right = L.push(L.head.right.right.right, 35);L.head.right.right.right = L.push(L.head.right.right.right, 20); # flatten the listL.head = L.flatten(L.head); L.printList()# This code is contributed by maheshwaripiyush9",
"e": 10577,
"s": 7606,
"text": null
},
{
"code": "// C# program for flattening a Linked Listusing System;public class List { Node head; // head of list /* Linked list Node */ public class Node { public int data; public Node right, down; public Node(int data) { this.data = data; right = null; down = null; } } // An utility function to merge two sorted linked lists Node merge(Node a, Node b) { // if first linked list is empty then second // is the answer if (a == null) return b; // if second linked list is empty then first // is the result if (b == null) return a; // compare the data members of the two linked lists // and put the larger one in the result Node result; if (a.data < b.data) { result = a; result.down = merge(a.down, b); } else { result = b; result.down = merge(a, b.down); } result.right = null; return result; } Node flatten(Node root) { // Base Cases if (root == null || root.right == null) return root; // recur for list on right root.right = flatten(root.right); // now merge root = merge(root, root.right); // return the root // it will be in turn merged with its left return root; } /* * Utility function to insert a node at beginning of the linked list */ Node Push(Node head_ref, int data) { /* * 1 & 2: Allocate the Node & Put in the data */ Node new_node = new Node(data); /* 3. Make next of new Node as head */ new_node.down = head_ref; /* 4. Move the head to point to new Node */ head_ref = new_node; /* 5. return to link it back */ return head_ref; } void printList() { Node temp = head; while (temp != null) { Console.Write(temp.data + \" \"); temp = temp.down; } Console.WriteLine(); } /* Driver program to test above functions */ public static void Main(String []args) { List L = new List(); /* * Let us create the following linked list 5 -> 10 -> 19 -> 28 | | | | V V V V 7 * 20 22 35 | | | V V V 8 50 40 | | V V 30 45 */ L.head = L.Push(L.head, 30); L.head = L.Push(L.head, 8); L.head = L.Push(L.head, 7); L.head = L.Push(L.head, 5); L.head.right = L.Push(L.head.right, 20); L.head.right = L.Push(L.head.right, 10); L.head.right.right = L.Push(L.head.right.right, 50); L.head.right.right = L.Push(L.head.right.right, 22); L.head.right.right = L.Push(L.head.right.right, 19); L.head.right.right.right = L.Push(L.head.right.right.right, 45); L.head.right.right.right = L.Push(L.head.right.right.right, 40); L.head.right.right.right = L.Push(L.head.right.right.right, 35); L.head.right.right.right = L.Push(L.head.right.right.right, 20); // flatten the list L.head = L.flatten(L.head); L.printList(); }} // This code is contributed by umadevi9616",
"e": 13778,
"s": 10577,
"text": null
},
{
"code": "<script>// javascript program for flattening a Linked Listvar head; // head of list /* Linked list Node */ class Node { constructor(val) { this.data = val; this.down = null; this.next = null; } } // An utility function to merge two sorted linked lists function merge(a, b) { // if first linked list is empty then second // is the answer if (a == null) return b; // if second linked list is empty then first // is the result if (b == null) return a; // compare the data members of the two linked lists // and put the larger one in the result var result; if (a.data < b.data) { result = a; result.down = merge(a.down, b); } else { result = b; result.down = merge(a, b.down); } result.right = null; return result; } function flatten(root) { // Base Cases if (root == null || root.right == null) return root; // recur for list on right root.right = flatten(root.right); // now merge root = merge(root, root.right); // return the root // it will be in turn merged with its left return root; } /* * Utility function to insert a node at beginning of the linked list */ function push(head_ref , data) { /* * 1 & 2: Allocate the Node & Put in the data */ var new_node = new Node(data); /* 3. Make next of new Node as head */ new_node.down = head_ref; /* 4. Move the head to point to new Node */ head_ref = new_node; /* 5. return to link it back */ return head_ref; } function printList() { var temp = head; while (temp != null) { document.write(temp.data + \" \"); temp = temp.down; } document.write(); } /* Driver program to test above functions */ /* * Let us create the following linked list 5 -> 10 -> 19 -> 28 | | | | V V V V 7 * 20 22 35 | | | V V V 8 50 40 | | V V 30 45 */ head = push(head, 30); head = push(head, 8); head = push(head, 7); head = push(head, 5); head.right = push(head.right, 20); head.right = push(head.right, 10); head.right.right = push(head.right.right, 50); head.right.right = push(head.right.right, 22); head.right.right = push(head.right.right, 19); head.right.right.right = push(head.right.right.right, 45); head.right.right.right = push(head.right.right.right, 40); head.right.right.right = push(head.right.right.right, 35); head.right.right.right = push(head.right.right.right, 20); // flatten the list head = flatten(head); printList(); // This code contributed by aashish1995</script>",
"e": 16762,
"s": 13778,
"text": null
},
{
"code": null,
"e": 16799,
"s": 16762,
"text": "5 7 8 10 19 20 20 22 30 35 40 45 50 "
},
{
"code": null,
"e": 16991,
"s": 16799,
"text": "Time Complexity: O(N*N*M) – where N is the no of nodes in main linked list (reachable using right pointer) and M is the no of node in a single sub linked list (reachable using down pointer). "
},
{
"code": null,
"e": 17041,
"s": 16991,
"text": "Explanation: As we are merging 2 lists at a time,"
},
{
"code": null,
"e": 17104,
"s": 17041,
"text": "After adding first 2 lists, time taken will be O(M+M) = O(2M)."
},
{
"code": null,
"e": 17186,
"s": 17104,
"text": "Then we will merge another list to above merged list -> time = O(2M + M) = O(3M)."
},
{
"code": null,
"e": 17239,
"s": 17186,
"text": "Then we will merge another list -> time = O(3M + M)."
},
{
"code": null,
"e": 17321,
"s": 17239,
"text": "We will keep merging lists to previously merged lists until all lists are merged."
},
{
"code": null,
"e": 17399,
"s": 17321,
"text": "Total time taken will be O(2M + 3M + 4M + .... N*M) = (2 + 3 + 4 + ... + N)*M"
},
{
"code": null,
"e": 17457,
"s": 17399,
"text": "Using arithmetic sum formula: time = O((N*N + N – 2)*M/2)"
},
{
"code": null,
"e": 17524,
"s": 17457,
"text": "Above expression is roughly equal to O(N*N*M) for large value of N"
},
{
"code": null,
"e": 17701,
"s": 17524,
"text": "Space Complexity: O(N*M) – because of the recursion. The recursive functions will use recursive stack of size equivalent to total number of elements in the lists, which is N*M."
},
{
"code": null,
"e": 17807,
"s": 17701,
"text": "The idea is, to build min-heap and use Extract-min property to get minimum element from priority queue."
},
{
"code": null,
"e": 17811,
"s": 17807,
"text": "C++"
},
{
"code": "#include <bits/stdc++.h> struct Node { int data; struct Node* next; struct Node* bottom; Node(int x) { data = x; next = NULL; bottom = NULL; }}; using namespace std; void flatten(Node* root); int main(void){ //this code builds the flattened linked list //of first picture in this article ; Node* head=new Node(5); auto temp=head; auto bt=head; bt->bottom=new Node(7); bt->bottom->bottom=new Node(8); bt->bottom->bottom->bottom=new Node(30); temp->next=new Node(10); temp=temp->next; bt=temp; bt->bottom=new Node(20); temp->next=new Node(19); temp=temp->next; bt=temp; bt->bottom=new Node(22); bt->bottom->bottom=new Node(50); temp->next=new Node(28); temp=temp->next; bt=temp; bt->bottom=new Node(35); bt->bottom->bottom=new Node(40); bt->bottom->bottom->bottom=new Node(45); flatten(head); cout << endl; return 0;} struct mycomp { bool operator()(Node* a, Node* b) { return a->data > b->data; }};void flatten(Node* root){ priority_queue<Node*, vector<Node*>, mycomp> p; //pushing main link nodes into priority_queue. while (root!=NULL) { p.push(root); root = root->next; } while (!p.empty()) { //extracting min auto k = p.top(); p.pop(); //printing least element cout << k->data << \" \"; if (k->bottom) p.push(k->bottom); } }//this code is contributed by user_990i",
"e": 19252,
"s": 17811,
"text": null
},
{
"code": null,
"e": 19289,
"s": 19252,
"text": "5 7 8 10 19 20 22 28 30 35 40 45 50 "
},
{
"code": null,
"e": 19486,
"s": 19289,
"text": "Time Complexity: O(N*M*log(N)) – where N is the no of nodes in main linked list (reachable using next pointer) and M is the no of node in a single sub linked list (reachable using bottom pointer)."
},
{
"code": null,
"e": 19499,
"s": 19486,
"text": "Explanation:"
},
{
"code": null,
"e": 19604,
"s": 19499,
"text": "1. Push all the nodes that are reachable using next pointer into priority queue till we encounter NULL. "
},
{
"code": null,
"e": 19641,
"s": 19604,
"text": "2.while(priority_queue is not empty)"
},
{
"code": null,
"e": 19737,
"s": 19641,
"text": " (i) Extract Node which contains minimum-value(k) from priority_queue and print k->data."
},
{
"code": null,
"e": 19853,
"s": 19737,
"text": " (ii) If k->bottom!=NULL ,insert k->bottom into priority_queue. Else our priority_queue size will decrease."
},
{
"code": null,
"e": 19955,
"s": 19853,
"text": "Space Complexity: O(N)-where N is the no of nodes in main linked list (reachable using next pointer)."
},
{
"code": null,
"e": 20032,
"s": 19955,
"text": "NOTE: In above explanation, k means the Node which contains minimum-element."
},
{
"code": null,
"e": 20324,
"s": 20032,
"text": "YouTube<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=PSKZJDtitZw\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>"
},
{
"code": null,
"e": 20334,
"s": 20324,
"text": "kaviarasu"
},
{
"code": null,
"e": 20345,
"s": 20334,
"text": "cherry0697"
},
{
"code": null,
"e": 20358,
"s": 20345,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 20370,
"s": 20358,
"text": "aashish1995"
},
{
"code": null,
"e": 20382,
"s": 20370,
"text": "umadevi9616"
},
{
"code": null,
"e": 20399,
"s": 20382,
"text": "maheswaripiyush9"
},
{
"code": null,
"e": 20412,
"s": 20399,
"text": "rajsanghavi9"
},
{
"code": null,
"e": 20428,
"s": 20412,
"text": "simranarora5sos"
},
{
"code": null,
"e": 20440,
"s": 20428,
"text": "tanmayvijay"
},
{
"code": null,
"e": 20455,
"s": 20440,
"text": "sagartomar9927"
},
{
"code": null,
"e": 20464,
"s": 20455,
"text": "sweetyty"
},
{
"code": null,
"e": 20478,
"s": 20464,
"text": "avtarkumar719"
},
{
"code": null,
"e": 20488,
"s": 20478,
"text": "user_990i"
},
{
"code": null,
"e": 20505,
"s": 20488,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 20526,
"s": 20505,
"text": "24*7 Innovation Labs"
},
{
"code": null,
"e": 20533,
"s": 20526,
"text": "Amazon"
},
{
"code": null,
"e": 20546,
"s": 20533,
"text": "Drishti-Soft"
},
{
"code": null,
"e": 20555,
"s": 20546,
"text": "Flipkart"
},
{
"code": null,
"e": 20569,
"s": 20555,
"text": "Goldman Sachs"
},
{
"code": null,
"e": 20579,
"s": 20569,
"text": "Microsoft"
},
{
"code": null,
"e": 20585,
"s": 20579,
"text": "Paytm"
},
{
"code": null,
"e": 20590,
"s": 20585,
"text": "Payu"
},
{
"code": null,
"e": 20599,
"s": 20590,
"text": "Snapdeal"
},
{
"code": null,
"e": 20604,
"s": 20599,
"text": "Visa"
},
{
"code": null,
"e": 20616,
"s": 20604,
"text": "Linked List"
},
{
"code": null,
"e": 20622,
"s": 20616,
"text": "Paytm"
},
{
"code": null,
"e": 20631,
"s": 20622,
"text": "Flipkart"
},
{
"code": null,
"e": 20638,
"s": 20631,
"text": "Amazon"
},
{
"code": null,
"e": 20648,
"s": 20638,
"text": "Microsoft"
},
{
"code": null,
"e": 20657,
"s": 20648,
"text": "Snapdeal"
},
{
"code": null,
"e": 20678,
"s": 20657,
"text": "24*7 Innovation Labs"
},
{
"code": null,
"e": 20683,
"s": 20678,
"text": "Payu"
},
{
"code": null,
"e": 20688,
"s": 20683,
"text": "Visa"
},
{
"code": null,
"e": 20702,
"s": 20688,
"text": "Goldman Sachs"
},
{
"code": null,
"e": 20715,
"s": 20702,
"text": "Drishti-Soft"
},
{
"code": null,
"e": 20727,
"s": 20715,
"text": "Linked List"
},
{
"code": null,
"e": 20825,
"s": 20727,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 20873,
"s": 20825,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 20892,
"s": 20873,
"text": "LinkedList in Java"
},
{
"code": null,
"e": 20924,
"s": 20892,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 20988,
"s": 20924,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 21035,
"s": 20988,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 21087,
"s": 21035,
"text": "Add two numbers represented by linked lists | Set 1"
},
{
"code": null,
"e": 21127,
"s": 21087,
"text": "Detect and Remove Loop in a Linked List"
},
{
"code": null,
"e": 21162,
"s": 21127,
"text": "Queue - Linked List Implementation"
},
{
"code": null,
"e": 21218,
"s": 21162,
"text": "Function to check if a singly linked list is palindrome"
}
]
|
How to find the area of a triangle using JavaScript ? | 29 Jan, 2021
Given an HTML document containing input fields that holds the side of triangle i.e. side1, side2, and side 3. The task is to find the area of triangle using JavaScript.
Approach: First we will create three input fields using <input type=”number”> tag to holds number input. After filling the input value, when user click the button, then the JavaScript function Area() will be called.
In JavaScript function, we use document.getElementById(“side1”).value to get the input value and then apply parseInt() method on it to get the input value in number. And then use simple mathematical formula to find the area of triangle and use document.getElementById(“display”).innerHTML to display the output on the screen.
Formula to find the Area of Triangle:
var s = (side1 + side2 + side3) / 2;
var area = Math.sqrt(s * ((s - side1) * (s - side2) * (s - side3)));
Example:
HTML
<!DOCTYPE HTML><html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title> JavaScript function to find the area of a triangle </title></head> <body style="text-align: center;"> <h1 style="color: green;"> GeeksforGeeks </h1> <h4> JavaScript function to find the area of a triangle </h4> <label for="side1"> Enter the value of side 1: </label> <input type="number" id="side1" placeholder="Enter value of side 1"> <br><br> <label for="side2"> Enter the value of side 2: </label> <input type="number" id="side2" placeholder="Enter value of side 2"> <br><br> <label for="side3"> Enter the value of side 3: </label> <input type="number" id="side3" placeholder="Enter value of side 2"> <br><br> <button onclick="Area()">Click Here!</button> <p> Area of Triangle: <span id="display"></span> </p> <script type="text/javascript"> function Area() { var side1 = parseInt(document .getElementById("side1").value); var side2 = parseInt(document .getElementById("side2").value); var side3 = parseInt(document .getElementById("side3").value); console.log(typeof(side1)); var s = (side1 + side2 + side3) / 2; var area = Math.sqrt(s * ((s - side1) * (s - side2) * (s - side3))); document.getElementById( "display").innerHTML = area; } </script></body> </html>
Output:
CSS-Misc
HTML-Misc
JavaScript-Misc
CSS
HTML
JavaScript
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a Tribute Page using HTML & CSS
How to set space between the flexbox ?
Build a Survey Form using HTML and CSS
Design a web page using HTML and CSS
Form validation using jQuery
REST API (Introduction)
Hide or show elements in HTML using display property
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Design a Tribute Page using HTML & CSS | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Jan, 2021"
},
{
"code": null,
"e": 197,
"s": 28,
"text": "Given an HTML document containing input fields that holds the side of triangle i.e. side1, side2, and side 3. The task is to find the area of triangle using JavaScript."
},
{
"code": null,
"e": 414,
"s": 197,
"text": "Approach: First we will create three input fields using <input type=”number”> tag to holds number input. After filling the input value, when user click the button, then the JavaScript function Area() will be called. "
},
{
"code": null,
"e": 740,
"s": 414,
"text": "In JavaScript function, we use document.getElementById(“side1”).value to get the input value and then apply parseInt() method on it to get the input value in number. And then use simple mathematical formula to find the area of triangle and use document.getElementById(“display”).innerHTML to display the output on the screen."
},
{
"code": null,
"e": 778,
"s": 740,
"text": "Formula to find the Area of Triangle:"
},
{
"code": null,
"e": 885,
"s": 778,
"text": "var s = (side1 + side2 + side3) / 2;\n\nvar area = Math.sqrt(s * ((s - side1) * (s - side2) * (s - side3)));"
},
{
"code": null,
"e": 894,
"s": 885,
"text": "Example:"
},
{
"code": null,
"e": 899,
"s": 894,
"text": "HTML"
},
{
"code": "<!DOCTYPE HTML><html> <head> <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"> <title> JavaScript function to find the area of a triangle </title></head> <body style=\"text-align: center;\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <h4> JavaScript function to find the area of a triangle </h4> <label for=\"side1\"> Enter the value of side 1: </label> <input type=\"number\" id=\"side1\" placeholder=\"Enter value of side 1\"> <br><br> <label for=\"side2\"> Enter the value of side 2: </label> <input type=\"number\" id=\"side2\" placeholder=\"Enter value of side 2\"> <br><br> <label for=\"side3\"> Enter the value of side 3: </label> <input type=\"number\" id=\"side3\" placeholder=\"Enter value of side 2\"> <br><br> <button onclick=\"Area()\">Click Here!</button> <p> Area of Triangle: <span id=\"display\"></span> </p> <script type=\"text/javascript\"> function Area() { var side1 = parseInt(document .getElementById(\"side1\").value); var side2 = parseInt(document .getElementById(\"side2\").value); var side3 = parseInt(document .getElementById(\"side3\").value); console.log(typeof(side1)); var s = (side1 + side2 + side3) / 2; var area = Math.sqrt(s * ((s - side1) * (s - side2) * (s - side3))); document.getElementById( \"display\").innerHTML = area; } </script></body> </html>",
"e": 2561,
"s": 899,
"text": null
},
{
"code": null,
"e": 2569,
"s": 2561,
"text": "Output:"
},
{
"code": null,
"e": 2578,
"s": 2569,
"text": "CSS-Misc"
},
{
"code": null,
"e": 2588,
"s": 2578,
"text": "HTML-Misc"
},
{
"code": null,
"e": 2604,
"s": 2588,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 2608,
"s": 2604,
"text": "CSS"
},
{
"code": null,
"e": 2613,
"s": 2608,
"text": "HTML"
},
{
"code": null,
"e": 2624,
"s": 2613,
"text": "JavaScript"
},
{
"code": null,
"e": 2641,
"s": 2624,
"text": "Web Technologies"
},
{
"code": null,
"e": 2646,
"s": 2641,
"text": "HTML"
},
{
"code": null,
"e": 2744,
"s": 2646,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2783,
"s": 2744,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 2822,
"s": 2783,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 2861,
"s": 2822,
"text": "Build a Survey Form using HTML and CSS"
},
{
"code": null,
"e": 2898,
"s": 2861,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 2927,
"s": 2898,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 2951,
"s": 2927,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 3004,
"s": 2951,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 3064,
"s": 3004,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 3125,
"s": 3064,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
}
]
|
Get all fields names in a MongoDB collection? | You can use the concept of Map Reduce. Let us first create a collection with documents −
> db.getAllFieldNamesDemo.insertOne({"StudentFirstName":"David","StudentAge":23});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd998e9b50a6c6dd317ad90")
}
Following is the query to display all documents from a collection with the help of find() method −
> db.getAllFieldNamesDemo.find();
This will produce the following output −
{ "_id" : ObjectId("5cd998e9b50a6c6dd317ad90"), "StudentFirstName" : "David", "StudentAge" : 23 }
Following is the query to get all fields names in a MongoDB collection −
> myMapReduce = db.runCommand({
"mapreduce" : "getAllFieldNamesDemo",
"map" : function() {
for (var myKey in this) { emit(myKey, null); }
},
"reduce" : function(myKey, s) { return null; },
"out": "getAllFieldNamesDemo" + "_k"
})
{
"result" : "getAllFieldNamesDemo_k",
"timeMillis" : 1375,
"counts" : {
"input" : 1,
"emit" : 3,
"reduce" : 0,
"output" : 3
},
"ok" : 1
}
> db[myMapReduce.result].distinct("_id");
This will produce the following output displaying the filed names −
[ "StudentAge", "StudentFirstName", "_id" ] | [
{
"code": null,
"e": 1276,
"s": 1187,
"text": "You can use the concept of Map Reduce. Let us first create a collection with documents −"
},
{
"code": null,
"e": 1444,
"s": 1276,
"text": "> db.getAllFieldNamesDemo.insertOne({\"StudentFirstName\":\"David\",\"StudentAge\":23});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5cd998e9b50a6c6dd317ad90\")\n}"
},
{
"code": null,
"e": 1543,
"s": 1444,
"text": "Following is the query to display all documents from a collection with the help of find() method −"
},
{
"code": null,
"e": 1577,
"s": 1543,
"text": "> db.getAllFieldNamesDemo.find();"
},
{
"code": null,
"e": 1618,
"s": 1577,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1716,
"s": 1618,
"text": "{ \"_id\" : ObjectId(\"5cd998e9b50a6c6dd317ad90\"), \"StudentFirstName\" : \"David\", \"StudentAge\" : 23 }"
},
{
"code": null,
"e": 1789,
"s": 1716,
"text": "Following is the query to get all fields names in a MongoDB collection −"
},
{
"code": null,
"e": 2259,
"s": 1789,
"text": "> myMapReduce = db.runCommand({\n \"mapreduce\" : \"getAllFieldNamesDemo\",\n \"map\" : function() {\n for (var myKey in this) { emit(myKey, null); }\n },\n \"reduce\" : function(myKey, s) { return null; },\n \"out\": \"getAllFieldNamesDemo\" + \"_k\"\n})\n{\n \"result\" : \"getAllFieldNamesDemo_k\",\n \"timeMillis\" : 1375,\n \"counts\" : {\n \"input\" : 1,\n \"emit\" : 3,\n \"reduce\" : 0,\n \"output\" : 3\n },\n \"ok\" : 1\n}\n> db[myMapReduce.result].distinct(\"_id\");"
},
{
"code": null,
"e": 2327,
"s": 2259,
"text": "This will produce the following output displaying the filed names −"
},
{
"code": null,
"e": 2371,
"s": 2327,
"text": "[ \"StudentAge\", \"StudentFirstName\", \"_id\" ]"
}
]
|
SQL | LISTAGG - GeeksforGeeks | 22 Jun, 2018
LISTAGG function in DBMS is used to aggregate strings from data in columns in a database table.
It makes it very easy to concatenate strings. It is similar to concatenation but uses grouping.
The speciality about this function is that, it also allows to order the elements in the concatenated list.
Syntax:
LISTAGG (measure_expr [, 'delimiter']) WITHIN GROUP
(order_by_clause) [OVER query_partition_clause]
measure_expr : The column or expression to concatenate the values.
delimiter : Character in between each measure_expr, which is by default a comma (,) .
order_by_clause : Order of the concatenated values.
Let us have a table named Gfg having two columns showing the subject names and subject number that each subject belongs to, as shown below :
SQL> select * from GfG;
SUBNO SUBNAME
---------- ------------------------------
D20 Algorithm
D30 DataStructure
D30 C
D20 C++
D30 Python
D30 DBMS
D10 LinkedList
D20 Matrix
D10 String
D30 Graph
D20 Tree
11 rows selected.
Query 1: Write an SQL query using LISTAGG function to output the subject names in a single field with the values comma delimited.
SQL> SELECT LISTAGG(SubName, ' , ') WITHIN GROUP (ORDER BY SubName) AS SUBJECTS
2 FROM GfG ;
Output:
SUBJECTS
-----------------------------------------------------------------------------------
Algorithm , C , C++ , DBMS , DataStructure , Graph , LinkedList , Matrix , Python ,
String , Tree
Query 2: Write an SQL query to group each subject and show each subject in its respective department separated by comma with the help of LISTAGG function.
SQL> SELECT SubNo, LISTAGG(SubName, ' , ') WITHIN GROUP (ORDER BY SubName) AS SUBJECTS
2 FROM GfG
3 GROUP BY SubNo;
Output:
SUBNO SUBJECTS
------ --------------------------------------------------------------------------------
D10 LinkedList , String
D20 Algorithm , C++ , Matrix , Tree
D30 C , DBMS , DataStructure , Graph , Python
Query 3: Write an SQL query to show the subjects belonging to each department ordered by the subject number (SUBNO) with the help of LISTAGG function.
SQL> SELECT SubNo, LISTAGG(SubName, ',') WITHIN GROUP (ORDER BY SubName) AS SUBJECTS
2 FROM GfG
3 GROUP BY SubNo
4 ORDER BY SubNo;
Output:
SUBNO SUBJECTS
----- --------------------------------
D10 LinkedList, String
D20 Algorithm, C++, Matrix, Tree
D30 C, DBMS, DataStructure, Graph, Python
This article is contributed by MAZHAR IMAM KHAN. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
SQL-Functions
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
SQL Trigger | Student Database
SQL | Views
Difference between DELETE, DROP and TRUNCATE
SQL Interview Questions
Difference between DDL and DML in DBMS
CTE in SQL
How to Update Multiple Columns in Single Update Statement in SQL?
SQL Correlated Subqueries
SQL | TRANSACTIONS
What is Cursor in SQL ? | [
{
"code": null,
"e": 23874,
"s": 23846,
"text": "\n22 Jun, 2018"
},
{
"code": null,
"e": 23970,
"s": 23874,
"text": "LISTAGG function in DBMS is used to aggregate strings from data in columns in a database table."
},
{
"code": null,
"e": 24066,
"s": 23970,
"text": "It makes it very easy to concatenate strings. It is similar to concatenation but uses grouping."
},
{
"code": null,
"e": 24173,
"s": 24066,
"text": "The speciality about this function is that, it also allows to order the elements in the concatenated list."
},
{
"code": null,
"e": 24181,
"s": 24173,
"text": "Syntax:"
},
{
"code": null,
"e": 24487,
"s": 24181,
"text": "LISTAGG (measure_expr [, 'delimiter']) WITHIN GROUP \n(order_by_clause) [OVER query_partition_clause]\nmeasure_expr : The column or expression to concatenate the values.\ndelimiter : Character in between each measure_expr, which is by default a comma (,) .\norder_by_clause : Order of the concatenated values."
},
{
"code": null,
"e": 24628,
"s": 24487,
"text": "Let us have a table named Gfg having two columns showing the subject names and subject number that each subject belongs to, as shown below :"
},
{
"code": null,
"e": 24933,
"s": 24628,
"text": "SQL> select * from GfG;\n\nSUBNO SUBNAME\n---------- ------------------------------\nD20 Algorithm\nD30 DataStructure\nD30 C\nD20 C++\nD30 Python\nD30 DBMS\nD10 LinkedList\nD20 Matrix\nD10 String\nD30 Graph\nD20 Tree\n\n11 rows selected.\n"
},
{
"code": null,
"e": 25063,
"s": 24933,
"text": "Query 1: Write an SQL query using LISTAGG function to output the subject names in a single field with the values comma delimited."
},
{
"code": null,
"e": 25162,
"s": 25063,
"text": "SQL> SELECT LISTAGG(SubName, ' , ') WITHIN GROUP (ORDER BY SubName) AS SUBJECTS\n 2 FROM GfG ;\n"
},
{
"code": null,
"e": 25170,
"s": 25162,
"text": "Output:"
},
{
"code": null,
"e": 25362,
"s": 25170,
"text": "SUBJECTS\n-----------------------------------------------------------------------------------\nAlgorithm , C , C++ , DBMS , DataStructure , Graph , LinkedList , Matrix , Python ,\nString , Tree\n"
},
{
"code": null,
"e": 25517,
"s": 25362,
"text": "Query 2: Write an SQL query to group each subject and show each subject in its respective department separated by comma with the help of LISTAGG function."
},
{
"code": null,
"e": 25642,
"s": 25517,
"text": "SQL> SELECT SubNo, LISTAGG(SubName, ' , ') WITHIN GROUP (ORDER BY SubName) AS SUBJECTS\n 2 FROM GfG\n 3 GROUP BY SubNo;\n"
},
{
"code": null,
"e": 25650,
"s": 25642,
"text": "Output:"
},
{
"code": null,
"e": 25892,
"s": 25650,
"text": "SUBNO SUBJECTS\n------ --------------------------------------------------------------------------------\nD10 LinkedList , String\nD20 Algorithm , C++ , Matrix , Tree\nD30 C , DBMS , DataStructure , Graph , Python\n"
},
{
"code": null,
"e": 26043,
"s": 25892,
"text": "Query 3: Write an SQL query to show the subjects belonging to each department ordered by the subject number (SUBNO) with the help of LISTAGG function."
},
{
"code": null,
"e": 26186,
"s": 26043,
"text": "SQL> SELECT SubNo, LISTAGG(SubName, ',') WITHIN GROUP (ORDER BY SubName) AS SUBJECTS\n 2 FROM GfG\n 3 GROUP BY SubNo\n 4 ORDER BY SubNo;\n"
},
{
"code": null,
"e": 26194,
"s": 26186,
"text": "Output:"
},
{
"code": null,
"e": 26388,
"s": 26194,
"text": "SUBNO SUBJECTS\n----- --------------------------------\nD10 LinkedList, String\nD20 Algorithm, C++, Matrix, Tree\nD30 C, DBMS, DataStructure, Graph, Python\n"
},
{
"code": null,
"e": 26692,
"s": 26388,
"text": "This article is contributed by MAZHAR IMAM KHAN. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 26817,
"s": 26692,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 26831,
"s": 26817,
"text": "SQL-Functions"
},
{
"code": null,
"e": 26835,
"s": 26831,
"text": "SQL"
},
{
"code": null,
"e": 26839,
"s": 26835,
"text": "SQL"
},
{
"code": null,
"e": 26937,
"s": 26839,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26946,
"s": 26937,
"text": "Comments"
},
{
"code": null,
"e": 26959,
"s": 26946,
"text": "Old Comments"
},
{
"code": null,
"e": 26990,
"s": 26959,
"text": "SQL Trigger | Student Database"
},
{
"code": null,
"e": 27002,
"s": 26990,
"text": "SQL | Views"
},
{
"code": null,
"e": 27047,
"s": 27002,
"text": "Difference between DELETE, DROP and TRUNCATE"
},
{
"code": null,
"e": 27071,
"s": 27047,
"text": "SQL Interview Questions"
},
{
"code": null,
"e": 27110,
"s": 27071,
"text": "Difference between DDL and DML in DBMS"
},
{
"code": null,
"e": 27121,
"s": 27110,
"text": "CTE in SQL"
},
{
"code": null,
"e": 27187,
"s": 27121,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 27213,
"s": 27187,
"text": "SQL Correlated Subqueries"
},
{
"code": null,
"e": 27232,
"s": 27213,
"text": "SQL | TRANSACTIONS"
}
]
|
Apex - Arrays | Arrays in Apex are basically the same as Lists in Apex. There is no logical distinction between the Arrays and Lists as their internal data structure and methods are also same but the array syntax is little traditional like Java.
Below is the representation of an Array of Products −
Index 0 − HCL
Index 1 − H2SO4
Index 2 − NACL
Index 3 − H2O
Index 4 − N2
Index 5 − U296
<String> [] arrayOfProducts = new List<String>();
Suppose, we have to store the name of our Products – we can use the Array where in, we will store the Product Names as shown below. You can access the particular Product by specifying the index.
//Defining array
String [] arrayOfProducts = new List<String>();
//Adding elements in Array
arrayOfProducts.add('HCL');
arrayOfProducts.add('H2SO4');
arrayOfProducts.add('NACL');
arrayOfProducts.add('H2O');
arrayOfProducts.add('N2');
arrayOfProducts.add('U296');
for (Integer i = 0; i<arrayOfProducts.size(); i++) {
//This loop will print all the elements in array
system.debug('Values In Array: '+arrayOfProducts[i]);
}
You can access any element in array by using the index as shown below −
//Accessing the element in array
//We would access the element at Index 3
System.debug('Value at Index 3 is :'+arrayOfProducts[3]);
14 Lectures
2 hours
Vijay Thapa
7 Lectures
2 hours
Uplatz
29 Lectures
6 hours
Ramnarayan Ramakrishnan
49 Lectures
3 hours
Ali Saleh Ali
10 Lectures
4 hours
Soham Ghosh
48 Lectures
4.5 hours
GUHARAJANM
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2282,
"s": 2052,
"text": "Arrays in Apex are basically the same as Lists in Apex. There is no logical distinction between the Arrays and Lists as their internal data structure and methods are also same but the array syntax is little traditional like Java."
},
{
"code": null,
"e": 2336,
"s": 2282,
"text": "Below is the representation of an Array of Products −"
},
{
"code": null,
"e": 2350,
"s": 2336,
"text": "Index 0 − HCL"
},
{
"code": null,
"e": 2366,
"s": 2350,
"text": "Index 1 − H2SO4"
},
{
"code": null,
"e": 2381,
"s": 2366,
"text": "Index 2 − NACL"
},
{
"code": null,
"e": 2395,
"s": 2381,
"text": "Index 3 − H2O"
},
{
"code": null,
"e": 2408,
"s": 2395,
"text": "Index 4 − N2"
},
{
"code": null,
"e": 2423,
"s": 2408,
"text": "Index 5 − U296"
},
{
"code": null,
"e": 2474,
"s": 2423,
"text": "<String> [] arrayOfProducts = new List<String>();\n"
},
{
"code": null,
"e": 2669,
"s": 2474,
"text": "Suppose, we have to store the name of our Products – we can use the Array where in, we will store the Product Names as shown below. You can access the particular Product by specifying the index."
},
{
"code": null,
"e": 3098,
"s": 2669,
"text": "//Defining array\nString [] arrayOfProducts = new List<String>();\n\n//Adding elements in Array\narrayOfProducts.add('HCL');\narrayOfProducts.add('H2SO4');\narrayOfProducts.add('NACL');\narrayOfProducts.add('H2O');\narrayOfProducts.add('N2');\narrayOfProducts.add('U296');\n\nfor (Integer i = 0; i<arrayOfProducts.size(); i++) {\n //This loop will print all the elements in array\n system.debug('Values In Array: '+arrayOfProducts[i]);\n}"
},
{
"code": null,
"e": 3170,
"s": 3098,
"text": "You can access any element in array by using the index as shown below −"
},
{
"code": null,
"e": 3302,
"s": 3170,
"text": "//Accessing the element in array\n//We would access the element at Index 3\nSystem.debug('Value at Index 3 is :'+arrayOfProducts[3]);"
},
{
"code": null,
"e": 3335,
"s": 3302,
"text": "\n 14 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3348,
"s": 3335,
"text": " Vijay Thapa"
},
{
"code": null,
"e": 3380,
"s": 3348,
"text": "\n 7 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3388,
"s": 3380,
"text": " Uplatz"
},
{
"code": null,
"e": 3421,
"s": 3388,
"text": "\n 29 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3446,
"s": 3421,
"text": " Ramnarayan Ramakrishnan"
},
{
"code": null,
"e": 3479,
"s": 3446,
"text": "\n 49 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 3494,
"s": 3479,
"text": " Ali Saleh Ali"
},
{
"code": null,
"e": 3527,
"s": 3494,
"text": "\n 10 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 3540,
"s": 3527,
"text": " Soham Ghosh"
},
{
"code": null,
"e": 3575,
"s": 3540,
"text": "\n 48 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3587,
"s": 3575,
"text": " GUHARAJANM"
},
{
"code": null,
"e": 3594,
"s": 3587,
"text": " Print"
},
{
"code": null,
"e": 3605,
"s": 3594,
"text": " Add Notes"
}
]
|
Sum of the series 0.6, 0.06, 0.006, 0.0006, ...to n terms | 19 Mar, 2021
Given the number of terms i.e. n. Find the sum of the series 0.6, 0.06, 0.006, 0.0006, ...to n terms.Examples:
Input : 2
Output : 0.65934
Input : 3
Output : 0.665334
Lets denote the sum by S: Using the formula , we have [since r<1]Hence the required sum is Below is the implementation:
C++
Java
Python3
C#
PHP
Javascript
// CPP program to find sum of 0.6, 0.06,// 0.006, 0.0006, ...to n terms#include <bits/stdc++.h>using namespace std; // function which return the// the sum of seriesfloat sumOfSeries(int n){ return (0.666) * (1 - 1 / pow(10, n));} // Driver codeint main(){ int n = 2; cout << sumOfSeries(n);}
// java program to find sum of 0.6, 0.06,// 0.006, 0.0006, ...to n termsimport java.io.*; class GFG{ // function which return the // the sum of series static double sumOfSeries(int n) { return (0.666) * (1 - 1 /Math. pow(10, n)); } // Driver code public static void main (String[] args) { int n = 2; System.out.println ( sumOfSeries(n)); }} // This code is contributed by vt_m
# Python3 program to find# sum of 0.6, 0.06, 0.006,# 0.0006, ...to n termsimport math # function which return# the sum of seriesdef sumOfSeries(n): return ((0.666) * (1 - 1 / pow(10, n))); # Driver coden = 2;print(sumOfSeries(n)); # This code is contributed by mits
// C# program to find sum of 0.6, 0.06,// 0.006, 0.0006, ...to n termsusing System; class GFG { // function which return the // the sum of series static double sumOfSeries(int n) { return (0.666) * (1 - 1 /Math. Pow(10, n)); } // Driver code public static void Main () { int n = 2; Console.WriteLine( sumOfSeries(n)); }} // This code is contributed by vt_m
<?php// PHP program to find sum of 0.6, 0.06,// 0.006, 0.0006, ...to n terms // function which return the// the sum of seriesfunction sumOfSeries($n){ return (0.666) * (1 - 1 / pow(10, $n));} // Driver code$n = 2;echo(sumOfSeries($n)); // This code is contributed by Ajit.?>
<script>// javascript program to find sum of 0.6, 0.06,// 0.006, 0.0006, ...to n terms // function which return the// the sum of seriesfunction sumOfSeries( n){ return (0.666) * (1 - 1 / Math.pow(10, n));} // Driver Codelet n = 2 ; document.write(sumOfSeries(n).toFixed(5)) ; // This code is contributed by aashish1995 </script>
Output:
0.65934
jit_t
Mithun Kumar
aashish1995
series
series-sum
Mathematical
School Programming
Mathematical
series
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Mar, 2021"
},
{
"code": null,
"e": 141,
"s": 28,
"text": "Given the number of terms i.e. n. Find the sum of the series 0.6, 0.06, 0.006, 0.0006, ...to n terms.Examples: "
},
{
"code": null,
"e": 197,
"s": 141,
"text": "Input : 2\nOutput : 0.65934\n\nInput : 3\nOutput : 0.665334"
},
{
"code": null,
"e": 321,
"s": 199,
"text": "Lets denote the sum by S: Using the formula , we have [since r<1]Hence the required sum is Below is the implementation: "
},
{
"code": null,
"e": 325,
"s": 321,
"text": "C++"
},
{
"code": null,
"e": 330,
"s": 325,
"text": "Java"
},
{
"code": null,
"e": 338,
"s": 330,
"text": "Python3"
},
{
"code": null,
"e": 341,
"s": 338,
"text": "C#"
},
{
"code": null,
"e": 345,
"s": 341,
"text": "PHP"
},
{
"code": null,
"e": 356,
"s": 345,
"text": "Javascript"
},
{
"code": "// CPP program to find sum of 0.6, 0.06,// 0.006, 0.0006, ...to n terms#include <bits/stdc++.h>using namespace std; // function which return the// the sum of seriesfloat sumOfSeries(int n){ return (0.666) * (1 - 1 / pow(10, n));} // Driver codeint main(){ int n = 2; cout << sumOfSeries(n);}",
"e": 657,
"s": 356,
"text": null
},
{
"code": "// java program to find sum of 0.6, 0.06,// 0.006, 0.0006, ...to n termsimport java.io.*; class GFG{ // function which return the // the sum of series static double sumOfSeries(int n) { return (0.666) * (1 - 1 /Math. pow(10, n)); } // Driver code public static void main (String[] args) { int n = 2; System.out.println ( sumOfSeries(n)); }} // This code is contributed by vt_m",
"e": 1101,
"s": 657,
"text": null
},
{
"code": "# Python3 program to find# sum of 0.6, 0.06, 0.006,# 0.0006, ...to n termsimport math # function which return# the sum of seriesdef sumOfSeries(n): return ((0.666) * (1 - 1 / pow(10, n))); # Driver coden = 2;print(sumOfSeries(n)); # This code is contributed by mits",
"e": 1381,
"s": 1101,
"text": null
},
{
"code": "// C# program to find sum of 0.6, 0.06,// 0.006, 0.0006, ...to n termsusing System; class GFG { // function which return the // the sum of series static double sumOfSeries(int n) { return (0.666) * (1 - 1 /Math. Pow(10, n)); } // Driver code public static void Main () { int n = 2; Console.WriteLine( sumOfSeries(n)); }} // This code is contributed by vt_m",
"e": 1814,
"s": 1381,
"text": null
},
{
"code": "<?php// PHP program to find sum of 0.6, 0.06,// 0.006, 0.0006, ...to n terms // function which return the// the sum of seriesfunction sumOfSeries($n){ return (0.666) * (1 - 1 / pow(10, $n));} // Driver code$n = 2;echo(sumOfSeries($n)); // This code is contributed by Ajit.?>",
"e": 2107,
"s": 1814,
"text": null
},
{
"code": "<script>// javascript program to find sum of 0.6, 0.06,// 0.006, 0.0006, ...to n terms // function which return the// the sum of seriesfunction sumOfSeries( n){ return (0.666) * (1 - 1 / Math.pow(10, n));} // Driver Codelet n = 2 ; document.write(sumOfSeries(n).toFixed(5)) ; // This code is contributed by aashish1995 </script>",
"e": 2444,
"s": 2107,
"text": null
},
{
"code": null,
"e": 2454,
"s": 2444,
"text": "Output: "
},
{
"code": null,
"e": 2462,
"s": 2454,
"text": "0.65934"
},
{
"code": null,
"e": 2470,
"s": 2464,
"text": "jit_t"
},
{
"code": null,
"e": 2483,
"s": 2470,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 2495,
"s": 2483,
"text": "aashish1995"
},
{
"code": null,
"e": 2502,
"s": 2495,
"text": "series"
},
{
"code": null,
"e": 2513,
"s": 2502,
"text": "series-sum"
},
{
"code": null,
"e": 2526,
"s": 2513,
"text": "Mathematical"
},
{
"code": null,
"e": 2545,
"s": 2526,
"text": "School Programming"
},
{
"code": null,
"e": 2558,
"s": 2545,
"text": "Mathematical"
},
{
"code": null,
"e": 2565,
"s": 2558,
"text": "series"
}
]
|
Reverse an ArrayList in Java | 13 May, 2021
Assuming you have gone through arraylist in java and know about arraylist. This post contains different examples for reversing an arraylist which are given below:1. By writing our own function(Using additional space): reverseArrayList() method in RevArrayList class contains logic for reversing an arraylist with integer objects. This method takes an arraylist as a parameter, traverses in reverse order and adds all the elements to the newly created arraylist. Finally the reversed arraylist is returned.
Java
// Java program for reversing an arraylistimport java.io.*;import java.util.*;class RevArrayList { // Takes an arraylist as a parameter and returns // a reversed arraylist public ArrayList<Integer> reverseArrayList(ArrayList<Integer> alist) { // Arraylist for storing reversed elements ArrayList<Integer> revArrayList = new ArrayList<Integer>(); for (int i = alist.size() - 1; i >= 0; i--) { // Append the elements in reverse order revArrayList.add(alist.get(i)); } // Return the reversed arraylist return revArrayList; } // Iterate through all the elements and print public void printElements(ArrayList<Integer> alist) { for (int i = 0; i < alist.size(); i++) { System.out.print(alist.get(i) + " "); } }} public class GFG { public static void main(String[] args) { RevArrayList obj = new RevArrayList(); // Declaring arraylist without any initial size ArrayList<Integer> arrayli = new ArrayList<Integer>(); // Appending elements at the end of the list arrayli.add(new Integer(1)); arrayli.add(new Integer(2)); arrayli.add(new Integer(3)); arrayli.add(new Integer(4)); System.out.print("Elements before reversing:"); obj.printElements(arrayli); arrayli = obj.reverseArrayList(arrayli); System.out.print("\nElements after reversing:"); obj.printElements(arrayli); }}
Elements before reversing:1 2 3 4
Elements after reversing:4 3 2 1
1. By writing our own function(without using additional space): In the previous example, an arraylist is used additionally for storing all the reversed elements which takes more space. To avoid that, same arraylist can be used for reversing. Logic: 1. Run the loop for n/2 times where ‘n’ is the number of elements in the arraylist. 2. In the first pass, Swap the first and nth element 3. In the second pass, Swap the second and (n-1)th element and so on till you reach the mid of the arraylist. 4. Return the arraylist after the loop termination.
Java
// Java program for reversing an arraylistimport java.io.*;import java.util.*;class RevArrayList { // Takes an arraylist as a parameter and returns // a reversed arraylist public ArrayList<Integer> reverseArrayList(ArrayList<Integer> alist) { // Arraylist for storing reversed elements // this.revArrayList = alist; for (int i = 0; i < alist.size() / 2; i++) { Integer temp = alist.get(i); alist.set(i, alist.get(alist.size() - i - 1)); alist.set(alist.size() - i - 1, temp); } // Return the reversed arraylist return alist; } // Iterate through all the elements and print public void printElements(ArrayList<Integer> alist) { for (int i = 0; i < alist.size(); i++) { System.out.print(alist.get(i) + " "); } }} public class GFG1 { public static void main(String[] args) { RevArrayList obj = new RevArrayList(); // Declaring arraylist without any initial size ArrayList<Integer> arrayli = new ArrayList<Integer>(); // Appending elements at the end of the list arrayli.add(new Integer(12)); arrayli.add(new Integer(13)); arrayli.add(new Integer(123)); arrayli.add(new Integer(54)); arrayli.add(new Integer(1)); System.out.print("Elements before reversing: "); obj.printElements(arrayli); arrayli = obj.reverseArrayList(arrayli); System.out.print("\nElements after reversing: "); obj.printElements(arrayli); }}
Elements before reversing: 12 13 123 54 1
Elements after reversing: 1 54 123 13 12
2. By using Collections class: Collections is a class in java.util package which contains various static methods for searching, sorting, reversing, finding max, min....etc. We can make use of the In-built Collections.reverse() method for reversing an arraylist. It takes a list as an input parameter and returns the reversed list.
Java
// Java program for reversing an arraylistimport java.io.*;import java.util.*; public class GFG2 { public static void main(String[] args) { // Declaring arraylist without any initial size ArrayList<Integer> arrayli = new ArrayList<Integer>(); // Appending elements at the end of the list arrayli.add(new Integer(9)); arrayli.add(new Integer(145)); arrayli.add(new Integer(878)); arrayli.add(new Integer(343)); arrayli.add(new Integer(5)); System.out.print("Elements before reversing: "); printElements(arrayli); // Collections.reverse method takes a list as a // parameter and reverses the passed parameter //(no new array list is required) Collections.reverse(arrayli); System.out.print("\nElements after reversing: "); printElements(arrayli); } // Iterate through all the elements and print public static void printElements(ArrayList<Integer> alist) { for (int i = 0; i < alist.size(); i++) { System.out.print(alist.get(i) + " "); } }}
Elements before reversing: 9 145 878 343 5
Elements after reversing: 5 343 878 145 9
3. Reversing an arraylist of user defined objects: An Employee class is created for creating user defined objects with employeeID, employeeName, departmentName as class variables which are initialized in the constructor. An arraylist is created that takes only Employee(user defined) Objects. These objects are added to the arraylist using add() method. The arraylist is reversed using In-built reverse() method of Collections class. The printElements() static method is used only to avoid writing one more class in the program.
Java
// Java program for reversing an arraylistimport java.io.*;import java.util.*;class Employee { int empID; String empName; String deptName; // Constructor for initializing the class variables public Employee(int empID, String empName, String deptName) { this.empID = empID; this.empName = empName; this.deptName = deptName; }} public class GFG3 { public static void main(String[] args) { // Declaring arraylist without any initial size ArrayList<Employee> arrayli = new ArrayList<Employee>(); // Creating user defined objects Employee emp1 = new Employee(123, "Rama", "Facilities"); Employee emp2 = new Employee(124, "Lakshman", "Transport"); Employee emp3 = new Employee(125, "Ravan", "Packing"); // Appending all the objects for arraylist arrayli.add(emp1); arrayli.add(emp2); arrayli.add(emp3); System.out.print("Elements before reversing: "); printElements(arrayli); // Collections.reverse method takes a list as a // parameter and reverse the list Collections.reverse(arrayli); System.out.print("\nElements after reversing: "); printElements(arrayli); } // Iterate through all the elements and print public static void printElements(ArrayList<Employee> alist) { for (int i = 0; i < alist.size(); i++) { System.out.print("\n EmpID:" + alist.get(i).empID + ", EmpName:" + alist.get(i).empName + ", Department:" + alist.get(i).deptName); } }}
Elements before reversing:
EmpID:123, EmpName:Rama, Department:Facilities
EmpID:124, EmpName:Lakshman, Department:Transport
EmpID:125, EmpName:Ravan, Department:Packing
Elements after reversing:
EmpID:125, EmpName:Ravan, Department:Packing
EmpID:124, EmpName:Lakshman, Department:Transport
EmpID:123, EmpName:Rama, Department:Facilities
SujanM
sweekruth__17
Java-ArrayList
Java-Collections
Java-List-Programs
Picked
Reverse
Java
Java
Reverse
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n13 May, 2021"
},
{
"code": null,
"e": 559,
"s": 52,
"text": "Assuming you have gone through arraylist in java and know about arraylist. This post contains different examples for reversing an arraylist which are given below:1. By writing our own function(Using additional space): reverseArrayList() method in RevArrayList class contains logic for reversing an arraylist with integer objects. This method takes an arraylist as a parameter, traverses in reverse order and adds all the elements to the newly created arraylist. Finally the reversed arraylist is returned. "
},
{
"code": null,
"e": 564,
"s": 559,
"text": "Java"
},
{
"code": "// Java program for reversing an arraylistimport java.io.*;import java.util.*;class RevArrayList { // Takes an arraylist as a parameter and returns // a reversed arraylist public ArrayList<Integer> reverseArrayList(ArrayList<Integer> alist) { // Arraylist for storing reversed elements ArrayList<Integer> revArrayList = new ArrayList<Integer>(); for (int i = alist.size() - 1; i >= 0; i--) { // Append the elements in reverse order revArrayList.add(alist.get(i)); } // Return the reversed arraylist return revArrayList; } // Iterate through all the elements and print public void printElements(ArrayList<Integer> alist) { for (int i = 0; i < alist.size(); i++) { System.out.print(alist.get(i) + \" \"); } }} public class GFG { public static void main(String[] args) { RevArrayList obj = new RevArrayList(); // Declaring arraylist without any initial size ArrayList<Integer> arrayli = new ArrayList<Integer>(); // Appending elements at the end of the list arrayli.add(new Integer(1)); arrayli.add(new Integer(2)); arrayli.add(new Integer(3)); arrayli.add(new Integer(4)); System.out.print(\"Elements before reversing:\"); obj.printElements(arrayli); arrayli = obj.reverseArrayList(arrayli); System.out.print(\"\\nElements after reversing:\"); obj.printElements(arrayli); }}",
"e": 2052,
"s": 564,
"text": null
},
{
"code": null,
"e": 2120,
"s": 2052,
"text": "Elements before reversing:1 2 3 4 \nElements after reversing:4 3 2 1"
},
{
"code": null,
"e": 2671,
"s": 2122,
"text": "1. By writing our own function(without using additional space): In the previous example, an arraylist is used additionally for storing all the reversed elements which takes more space. To avoid that, same arraylist can be used for reversing. Logic: 1. Run the loop for n/2 times where ‘n’ is the number of elements in the arraylist. 2. In the first pass, Swap the first and nth element 3. In the second pass, Swap the second and (n-1)th element and so on till you reach the mid of the arraylist. 4. Return the arraylist after the loop termination. "
},
{
"code": null,
"e": 2676,
"s": 2671,
"text": "Java"
},
{
"code": "// Java program for reversing an arraylistimport java.io.*;import java.util.*;class RevArrayList { // Takes an arraylist as a parameter and returns // a reversed arraylist public ArrayList<Integer> reverseArrayList(ArrayList<Integer> alist) { // Arraylist for storing reversed elements // this.revArrayList = alist; for (int i = 0; i < alist.size() / 2; i++) { Integer temp = alist.get(i); alist.set(i, alist.get(alist.size() - i - 1)); alist.set(alist.size() - i - 1, temp); } // Return the reversed arraylist return alist; } // Iterate through all the elements and print public void printElements(ArrayList<Integer> alist) { for (int i = 0; i < alist.size(); i++) { System.out.print(alist.get(i) + \" \"); } }} public class GFG1 { public static void main(String[] args) { RevArrayList obj = new RevArrayList(); // Declaring arraylist without any initial size ArrayList<Integer> arrayli = new ArrayList<Integer>(); // Appending elements at the end of the list arrayli.add(new Integer(12)); arrayli.add(new Integer(13)); arrayli.add(new Integer(123)); arrayli.add(new Integer(54)); arrayli.add(new Integer(1)); System.out.print(\"Elements before reversing: \"); obj.printElements(arrayli); arrayli = obj.reverseArrayList(arrayli); System.out.print(\"\\nElements after reversing: \"); obj.printElements(arrayli); }}",
"e": 4223,
"s": 2676,
"text": null
},
{
"code": null,
"e": 4307,
"s": 4223,
"text": "Elements before reversing: 12 13 123 54 1 \nElements after reversing: 1 54 123 13 12"
},
{
"code": null,
"e": 4641,
"s": 4309,
"text": "2. By using Collections class: Collections is a class in java.util package which contains various static methods for searching, sorting, reversing, finding max, min....etc. We can make use of the In-built Collections.reverse() method for reversing an arraylist. It takes a list as an input parameter and returns the reversed list. "
},
{
"code": null,
"e": 4646,
"s": 4641,
"text": "Java"
},
{
"code": "// Java program for reversing an arraylistimport java.io.*;import java.util.*; public class GFG2 { public static void main(String[] args) { // Declaring arraylist without any initial size ArrayList<Integer> arrayli = new ArrayList<Integer>(); // Appending elements at the end of the list arrayli.add(new Integer(9)); arrayli.add(new Integer(145)); arrayli.add(new Integer(878)); arrayli.add(new Integer(343)); arrayli.add(new Integer(5)); System.out.print(\"Elements before reversing: \"); printElements(arrayli); // Collections.reverse method takes a list as a // parameter and reverses the passed parameter //(no new array list is required) Collections.reverse(arrayli); System.out.print(\"\\nElements after reversing: \"); printElements(arrayli); } // Iterate through all the elements and print public static void printElements(ArrayList<Integer> alist) { for (int i = 0; i < alist.size(); i++) { System.out.print(alist.get(i) + \" \"); } }}",
"e": 5743,
"s": 4646,
"text": null
},
{
"code": null,
"e": 5829,
"s": 5743,
"text": "Elements before reversing: 9 145 878 343 5 \nElements after reversing: 5 343 878 145 9"
},
{
"code": null,
"e": 6361,
"s": 5831,
"text": "3. Reversing an arraylist of user defined objects: An Employee class is created for creating user defined objects with employeeID, employeeName, departmentName as class variables which are initialized in the constructor. An arraylist is created that takes only Employee(user defined) Objects. These objects are added to the arraylist using add() method. The arraylist is reversed using In-built reverse() method of Collections class. The printElements() static method is used only to avoid writing one more class in the program. "
},
{
"code": null,
"e": 6366,
"s": 6361,
"text": "Java"
},
{
"code": "// Java program for reversing an arraylistimport java.io.*;import java.util.*;class Employee { int empID; String empName; String deptName; // Constructor for initializing the class variables public Employee(int empID, String empName, String deptName) { this.empID = empID; this.empName = empName; this.deptName = deptName; }} public class GFG3 { public static void main(String[] args) { // Declaring arraylist without any initial size ArrayList<Employee> arrayli = new ArrayList<Employee>(); // Creating user defined objects Employee emp1 = new Employee(123, \"Rama\", \"Facilities\"); Employee emp2 = new Employee(124, \"Lakshman\", \"Transport\"); Employee emp3 = new Employee(125, \"Ravan\", \"Packing\"); // Appending all the objects for arraylist arrayli.add(emp1); arrayli.add(emp2); arrayli.add(emp3); System.out.print(\"Elements before reversing: \"); printElements(arrayli); // Collections.reverse method takes a list as a // parameter and reverse the list Collections.reverse(arrayli); System.out.print(\"\\nElements after reversing: \"); printElements(arrayli); } // Iterate through all the elements and print public static void printElements(ArrayList<Employee> alist) { for (int i = 0; i < alist.size(); i++) { System.out.print(\"\\n EmpID:\" + alist.get(i).empID + \", EmpName:\" + alist.get(i).empName + \", Department:\" + alist.get(i).deptName); } }}",
"e": 7976,
"s": 6366,
"text": null
},
{
"code": null,
"e": 8321,
"s": 7976,
"text": "Elements before reversing: \n EmpID:123, EmpName:Rama, Department:Facilities\n EmpID:124, EmpName:Lakshman, Department:Transport\n EmpID:125, EmpName:Ravan, Department:Packing\nElements after reversing: \n EmpID:125, EmpName:Ravan, Department:Packing\n EmpID:124, EmpName:Lakshman, Department:Transport\n EmpID:123, EmpName:Rama, Department:Facilities"
},
{
"code": null,
"e": 8330,
"s": 8323,
"text": "SujanM"
},
{
"code": null,
"e": 8344,
"s": 8330,
"text": "sweekruth__17"
},
{
"code": null,
"e": 8359,
"s": 8344,
"text": "Java-ArrayList"
},
{
"code": null,
"e": 8376,
"s": 8359,
"text": "Java-Collections"
},
{
"code": null,
"e": 8395,
"s": 8376,
"text": "Java-List-Programs"
},
{
"code": null,
"e": 8402,
"s": 8395,
"text": "Picked"
},
{
"code": null,
"e": 8410,
"s": 8402,
"text": "Reverse"
},
{
"code": null,
"e": 8415,
"s": 8410,
"text": "Java"
},
{
"code": null,
"e": 8420,
"s": 8415,
"text": "Java"
},
{
"code": null,
"e": 8428,
"s": 8420,
"text": "Reverse"
},
{
"code": null,
"e": 8445,
"s": 8428,
"text": "Java-Collections"
}
]
|
Programs for printing pyramid patterns in C++ | 12 Jun, 2022
This article is aimed at giving a C++ implementation for pattern printing.
Simple pyramid pattern
CPP
// C++ code to demonstrate star pattern#include <iostream>using namespace std; // Function to demonstrate printing patternvoid pypart(int n){ // Outer loop to handle number of rows // n in this case for (int i = 0; i < n; i++) { // Inner loop to handle number of columns // values changing acc. to outer loop for (int j = 0; j <= i; j++) { // Printing stars cout << "* "; } // Ending line after each row cout << endl; }} // Driver Functionint main(){ int n = 5; pypart(n); return 0;}
*
* *
* * *
* * * *
* * * * *
Printing above pattern using while Loop
CPP
// C++ code to demonstrate star pattern#include <iostream>using namespace std; // Function to demonstrate printing patternvoid pypart(int n){ // Outer loop to handle number of rows // n in this case int i = 0, j = 0; while (i < n) { // Inner loop to handle number of columns // values changing acc. to outer loop while (j <= i) { // Printing stars cout << "* "; j++; } j = 0; // we have to reset j value so as it can // start from beginning and print * equal to i. i++; // Ending line after each row cout << endl; }} // Driver Codeint main(){ int n = 5; pypart(n); return 0;}
*
* *
* * *
* * * *
* * * * *
After 180 degree rotation
CPP
// C++ code to demonstrate star pattern#include <iostream>using namespace std; // Driver Codeint main(){ int n = 5; //looping rows for(int i=n; i>0; i--) { for(int j=0; j<=n; j++) //looping columns { if (j>=i) { cout<<"*"; } else { cout<<" "; } } cout<<endl; } return 0;}
*
**
***
****
*****
Printing above pattern using while loop
CPP
// C++ code to demonstrate pattern printing#include <iostream>using namespace std; // Function to demonstrate printing patternvoid pypart2(int n){ int i = 0, j = 0, k = 0; while (i < n) { // for number of spaces while (k < (n - i - 1)) { cout << " "; k++; } // resetting k because we want to run k from // beginning. k = 0; while (j <= i) { cout << "* "; j++; } // resetting k so as it can start from 0. j = 0; i++; cout << endl; }} // Driver Codeint main(){ int n = 5; // Function Call pypart2(n); return 0;}
*
* *
* * *
* * * *
* * * * *
Inverted Pyramid Pattern
C++
// C++ code to demonstrate star pattern#include <iostream>using namespace std; // Function to demonstrate printing patternvoid pypart(int n){ // Outer loop to handle number of rows // n in this case for (int i = n; i > 0; i--) { // Inner loop to handle number of columns // values changing acc. to outer loop for (int j = 0; j < i; j++) { // Printing stars cout << "* "; } // Ending line after each row cout << endl; }} // Driver Functionint main(){ int n = 5; pypart(n); return 0;}
* * * * *
* * * *
* * *
* *
*
Printing above pattern using while loop
C++
// C++ code to demonstrate star pattern#include <iostream>using namespace std; // Function to demonstrate printing patternvoid pypart(int n){ // Outer loop to handle number of rows // n in this case int i = n, j = 0; while (i > 0) { // Inner loop to handle number of columns // values changing acc. to outer loop while (j < i) { // Printing stars cout << "* "; j++; } j = 0; // we have to reset j value so as it can // start from beginning and print * equal to i. i--; // Ending line after each row cout << endl; }} // Driver Codeint main(){ int n = 5; pypart(n); return 0;}
* * * * *
* * * *
* * *
* *
*
Method#2: Printing above pattern using recursion
C++
// C++ code to print Inverted Pyramid Pattern using recursion#include <bits/stdc++.h>using namespace std; void pypart(int n){ if(n==0){ return; } for(int i =1;i<=n;i++){ cout<<"* "; } cout<<endl; pypart(n-1); } // driver functionint main(){ int n = 5; pypart(n); return 0;}//This code is contribured by Shivesh Kumar Dwivedi
* * * * *
* * * *
* * *
* *
*
After 180 degree rotation
C++
// C++ code to demonstrate star pattern#include <iostream>using namespace std; // Function to demonstrate printing patternvoid pypart2(int n){ // number of spaces int k = 2 * n - 2; // Outer loop to handle number of rows // n in this case for (int i = n; i > 0; i--) { // Inner loop to handle number spaces // values changing acc. to requirement for (int j = 0; j < n-i; j++) cout << " "; // Decrementing k after each loop k = k - 2; // Inner loop to handle number of columns // values changing acc. to outer loop for (int j = 0; j < i; j++) { // Printing stars cout << "* "; } // Ending line after each row cout << endl; }} // Driver Codeint main(){ int n = 5; // Function Call pypart2(n); return 0;}
* * * * *
* * * *
* * *
* *
*
Printing above pattern using while loop
C++
// C++ code to demonstrate pattern printing#include <iostream>using namespace std; // Function to demonstrate printing patternvoid pypart2(int n){ int i = n, j = 0, k = 0; while (i > 0) { // for number of spaces while (k < (n - i)) { cout << " "; k++; } // resetting k because we want to run k from // beginning. k = 0; while (j < i) { cout << "* "; j++; } // resetting k so as it can start from 0. j = 0; i--; cout << endl; }} // Driver Codeint main(){ int n = 5; // Function Call pypart2(n); return 0;}
* * * * *
* * * *
* * *
* *
*
Printing Triangle
Method 1
Method 2
// C++ code to demonstrate star pattern#include <iostream>using namespace std; // Function to demonstrate printing patternvoid triangle(int n){ // number of spaces int k = 2 * n - 2; // Outer loop to handle number of rows // n in this case for (int i = 0; i < n; i++) { // Inner loop to handle number spaces // values changing acc. to requirement for (int j = 0; j < k; j++) cout << " "; // Decrementing k after each loop k = k - 1; // Inner loop to handle number of columns // values changing acc. to outer loop for (int j = 0; j <= i; j++) { // Printing stars cout << "* "; } // Ending line after each row cout << endl; }} // Driver Codeint main(){ int n = 5; // Function Call triangle(n); return 0;}
// C++ code to demonstrate star pattern#include <iostream>using namespace std; // Function to demonstrate printing patternvoid pypart2(int n){ // Number of spaces int i, j, k = n; // Outer loop to handle number of rows // n in this case for (i = 1; i <= n; i++) { // Inner loop for columns for (j = 1; j <= n; j++) { // Condition to print star pattern if (j >= k) cout << "* "; else cout << " "; } k--; cout << "\n"; }} // Driver Codeint main(){ int n = 5; // Function Call pypart2(n); return 0;}
*
* *
* * *
* * * *
* * * * *
Method 3
// C++ code to demonstrate star pattern#include <iostream>using namespace std; // Function to demonstrate printing patternvoid pypart2(int n){ int i = 0, j = 0, k = 0; while (i < n) { // for spacing while (k <= n - i - 2) { cout << " "; k++; } k = 0; // For Pattern printing while (j < 2 * i - 1) { cout << "*"; j++; } j = 0; i++; cout << endl; }} // Driver Codeint main(){ int n = 5; // Function Call pypart2(n); return 0;}
*
***
*****
*******
Number Pattern
CPP
// C++ code to demonstrate printing// pattern of numbers#include <iostream>using namespace std; // Function to demonstrate printing// patternvoid numpat(int n){ // initializing starting number int num = 1; // Outer loop to handle number of rows // n in this case for (int i = 0; i < n; i++) { // Inner loop to handle number of columns // values changing acc. to outer loop for (int j = 0; j <= i; j++) cout << num << " "; // Incrementing number at each column num = num + 1; // Ending line after each row cout << endl; }} // Driver Codeint main(){ int n = 5; // Function Call numpat(n); return 0;}
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
Above Pattern Using while loop
CPP
// C++ Code for pattern Printing#include <iostream>using namespace std; // Function to demonstrate printing patternvoid pypart(int n){ int i = 1, j = 0; while (i <= n) { while (j <= i - 1) { cout << i << " "; j++; } j = 0; i++; cout << endl; }} // Driver Codeint main(){ int n = 5; // Function Call pypart(n); return 0;}
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
Numbers without reassigning
CPP
// C++ code to demonstrate printing pattern of numbers#include <iostream>using namespace std; // Function to demonstrate printing patternvoid numpat(int n){ // Initialising starting number int num = 1; // Outer loop to handle number of rows // n in this case for (int i = 0; i < n; i++) { // Inner loop to handle number of columns // values changing acc. to outer loop for (int j = 0; j <= i; j++) { // Printing number cout << num << " "; // Incrementing number at each column num = num + 1; } // Ending line after each row cout << endl; }} // Driver Codeint main(){ int n = 5; // Function Call numpat(n); return 0;}
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
Above pattern using while loop
CPP
// C++ code to demonstrate printing pattern of numbers#include <iostream>using namespace std; // Function to demonstrate printing patternvoid pypart(int n){ int i = 1, j = 0; // here we declare an num variable which is // assigned value 1 int num = 1; while (i <= n) { while (j <= i - 1) { // Printing numbers cout << num << " "; // here we are increasing num for every // iteration. num++; j++; } j = 0; i++; // Ending line after each row cout << endl; }} // Driver Codeint main(){ int n = 5; // Function Call pypart(n); return 0;}
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
C++
#include <iostream>using namespace std; int main(){ int rows = 5, count = 0, count1 = 0, k = 0; for(int i = 1; i <= rows; ++i) { for(int space = 1; space <= rows-i; ++space) { cout << " "; ++count; } while(k != 2*i-1) { if (count <= rows-1) { cout << i+k << " "; ++count; } ++k; } count1 = count = k = 0; cout << endl; } return 0;} //code by Kashif RB
1
2 3
3 4 5
4 5 6 7
5 6 7 8 9
C++
#include <iostream>using namespace std; int main(){ int rows=5, count = 0, count1 = 0, k = 0; for(int i = 1; i <= rows; ++i) { for(int space = 1; space <= rows-i; ++space) { cout << " "; ++count; } while(k != 2*i-1) { if (count <= rows-1) { cout << i+k << " "; ++count; } else { ++count1; cout << i+k-2*count1 << " "; } ++k; } count1 = count = k = 0; cout << endl; } return 0;} // code by Kashif Rb
1
2 3 2
3 4 5 4 3
4 5 6 7 6 5 4
5 6 7 8 9 8 7 6 5
Character Pattern
CPP
// C++ code to demonstrate printing pattern of alphabets#include <iostream>using namespace std; // Function to demonstrate printing patternvoid alphabet(int n){ // Initializing value corresponding to 'A' // ASCII value int num = 65; // Outer loop to handle number of rows // n in this case for (int i = 0; i < n; i++) { // Inner loop to handle number of columns // values changing acc. to outer loop for (int j = 0; j <= i; j++) { // Explicitly converting to char char ch = char(num); // Printing char value cout << ch << " "; } // Incrementing number num = num + 1; // Ending line after each row cout << endl; }} // Driver Functionint main(){ int n = 5; alphabet(n); return 0;}
A
B B
C C C
D D D D
E E E E E
Above pattern using while loop
CPP
// C++ code to demonstrate printing pattern of alphabets#include <iostream>using namespace std; // Function to demonstrate printing patternvoid alphabet(int n){ int i = 1, j = 0; // assigning ASCII value of A which is 65 int num = 65; // converting ASCII value to character, // now our alpha variable is having // value A after typecasting. char alpha = char(num); while (i <= n) { // alpha is having A value and it // will change as soon as alpha // increased or decreased. while (j <= i - 1) { cout << alpha << " "; j++; } // incrementing alpha value so as it can // point to next character alpha++; // we have to reset j value so as it can // start from beginning and print * equal to // i. j = 0; i++; // Ending line after each row cout << endl; }} // Driver Codeint main(){ int n = 5; // Function Call alphabet(n); return 0;}
A
B B
C C C
D D D D
E E E E E
Continuous Character pattern
CPP
// C++ code to demonstrate printing pattern of alphabets#include <iostream>using namespace std; // Function to demonstrate printing patternvoid contalpha(int n){ // Initializing value corresponding to 'A' // ASCII value int num = 65; // Outer loop to handle number of rows // n in this case for (int i = 0; i < n; i++) { // Inner loop to handle number of columns // values changing acc. to outer loop for (int j = 0; j <= i; j++) { // Explicitly converting to char char ch = char(num); // Printing char value cout << ch << " "; // Incrementing number at each column num = num + 1; } // Ending line after each row cout << endl; }} // Driver Codeint main(){ int n = 5; // Function Call contalpha(n); return 0;}
A
B C
D E F
G H I J
K L M N O
Above pattern using while loop
CPP
// C++ code to demonstrate printing pattern of alphabets#include <iostream>using namespace std; // Function to demonstrate printing patternvoid contalpha(int n){ int i = 1, j = 0; int num = 65; char alpha = char(num); while (i <= n) { while (j <= i - 1) { cout << alpha << " "; // incrementing alpha value in every // iteration so as it can assign to // next character alpha++; j++; } j = 0; i++; // Ending line after each row cout << endl; }} // Driver Codeint main(){ int n = 5; // Function Call contalpha(n); return 0;}
A
B C
D E F
G H I J
K L M N O
Printing patterns in python language are discussed in the article below :Programs for printing pyramid patterns in PythonThis article is contributed by Manjeet Singh(S.Nandini). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
prathvirsingh18
gauravdalvi2012
deysoumavo65
dhruvrohilla
saurabh1990aror
ruhelaa48
adnanirshad158
arorakashish0911
muhammadkashifbhatti70
cpdwivedi916
pattern-printing
C++
School Programming
pattern-printing
CPP
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, 2022"
},
{
"code": null,
"e": 128,
"s": 52,
"text": "This article is aimed at giving a C++ implementation for pattern printing. "
},
{
"code": null,
"e": 151,
"s": 128,
"text": "Simple pyramid pattern"
},
{
"code": null,
"e": 155,
"s": 151,
"text": "CPP"
},
{
"code": "// C++ code to demonstrate star pattern#include <iostream>using namespace std; // Function to demonstrate printing patternvoid pypart(int n){ // Outer loop to handle number of rows // n in this case for (int i = 0; i < n; i++) { // Inner loop to handle number of columns // values changing acc. to outer loop for (int j = 0; j <= i; j++) { // Printing stars cout << \"* \"; } // Ending line after each row cout << endl; }} // Driver Functionint main(){ int n = 5; pypart(n); return 0;}",
"e": 727,
"s": 155,
"text": null
},
{
"code": null,
"e": 763,
"s": 727,
"text": "* \n* * \n* * * \n* * * * \n* * * * * \n"
},
{
"code": null,
"e": 804,
"s": 763,
"text": "Printing above pattern using while Loop "
},
{
"code": null,
"e": 808,
"s": 804,
"text": "CPP"
},
{
"code": "// C++ code to demonstrate star pattern#include <iostream>using namespace std; // Function to demonstrate printing patternvoid pypart(int n){ // Outer loop to handle number of rows // n in this case int i = 0, j = 0; while (i < n) { // Inner loop to handle number of columns // values changing acc. to outer loop while (j <= i) { // Printing stars cout << \"* \"; j++; } j = 0; // we have to reset j value so as it can // start from beginning and print * equal to i. i++; // Ending line after each row cout << endl; }} // Driver Codeint main(){ int n = 5; pypart(n); return 0;}",
"e": 1513,
"s": 808,
"text": null
},
{
"code": null,
"e": 1549,
"s": 1513,
"text": "* \n* * \n* * * \n* * * * \n* * * * * \n"
},
{
"code": null,
"e": 1575,
"s": 1549,
"text": "After 180 degree rotation"
},
{
"code": null,
"e": 1579,
"s": 1575,
"text": "CPP"
},
{
"code": "// C++ code to demonstrate star pattern#include <iostream>using namespace std; // Driver Codeint main(){ int n = 5; //looping rows for(int i=n; i>0; i--) { for(int j=0; j<=n; j++) //looping columns { if (j>=i) { cout<<\"*\"; } else { cout<<\" \"; } } cout<<endl; } return 0;}",
"e": 1952,
"s": 1579,
"text": null
},
{
"code": null,
"e": 1988,
"s": 1952,
"text": " *\n **\n ***\n ****\n *****\n"
},
{
"code": null,
"e": 2031,
"s": 1990,
"text": "Printing above pattern using while loop "
},
{
"code": null,
"e": 2035,
"s": 2031,
"text": "CPP"
},
{
"code": "// C++ code to demonstrate pattern printing#include <iostream>using namespace std; // Function to demonstrate printing patternvoid pypart2(int n){ int i = 0, j = 0, k = 0; while (i < n) { // for number of spaces while (k < (n - i - 1)) { cout << \" \"; k++; } // resetting k because we want to run k from // beginning. k = 0; while (j <= i) { cout << \"* \"; j++; } // resetting k so as it can start from 0. j = 0; i++; cout << endl; }} // Driver Codeint main(){ int n = 5; // Function Call pypart2(n); return 0;}",
"e": 2721,
"s": 2035,
"text": null
},
{
"code": null,
"e": 2777,
"s": 2721,
"text": " * \n * * \n * * * \n * * * * \n* * * * * \n"
},
{
"code": null,
"e": 2803,
"s": 2777,
"text": " Inverted Pyramid Pattern"
},
{
"code": null,
"e": 2807,
"s": 2803,
"text": "C++"
},
{
"code": "// C++ code to demonstrate star pattern#include <iostream>using namespace std; // Function to demonstrate printing patternvoid pypart(int n){ // Outer loop to handle number of rows // n in this case for (int i = n; i > 0; i--) { // Inner loop to handle number of columns // values changing acc. to outer loop for (int j = 0; j < i; j++) { // Printing stars cout << \"* \"; } // Ending line after each row cout << endl; }} // Driver Functionint main(){ int n = 5; pypart(n); return 0;}",
"e": 3378,
"s": 2807,
"text": null
},
{
"code": null,
"e": 3414,
"s": 3378,
"text": "* * * * * \n* * * * \n* * * \n* * \n* \n"
},
{
"code": null,
"e": 3454,
"s": 3414,
"text": "Printing above pattern using while loop"
},
{
"code": null,
"e": 3458,
"s": 3454,
"text": "C++"
},
{
"code": "// C++ code to demonstrate star pattern#include <iostream>using namespace std; // Function to demonstrate printing patternvoid pypart(int n){ // Outer loop to handle number of rows // n in this case int i = n, j = 0; while (i > 0) { // Inner loop to handle number of columns // values changing acc. to outer loop while (j < i) { // Printing stars cout << \"* \"; j++; } j = 0; // we have to reset j value so as it can // start from beginning and print * equal to i. i--; // Ending line after each row cout << endl; }} // Driver Codeint main(){ int n = 5; pypart(n); return 0;}",
"e": 4162,
"s": 3458,
"text": null
},
{
"code": null,
"e": 4198,
"s": 4162,
"text": "* * * * * \n* * * * \n* * * \n* * \n* \n"
},
{
"code": null,
"e": 4247,
"s": 4198,
"text": "Method#2: Printing above pattern using recursion"
},
{
"code": null,
"e": 4251,
"s": 4247,
"text": "C++"
},
{
"code": "// C++ code to print Inverted Pyramid Pattern using recursion#include <bits/stdc++.h>using namespace std; void pypart(int n){ if(n==0){ return; } for(int i =1;i<=n;i++){ cout<<\"* \"; } cout<<endl; pypart(n-1); } // driver functionint main(){ int n = 5; pypart(n); return 0;}//This code is contribured by Shivesh Kumar Dwivedi",
"e": 4624,
"s": 4251,
"text": null
},
{
"code": null,
"e": 4660,
"s": 4624,
"text": "* * * * * \n* * * * \n* * * \n* * \n* \n"
},
{
"code": null,
"e": 4686,
"s": 4660,
"text": "After 180 degree rotation"
},
{
"code": null,
"e": 4690,
"s": 4686,
"text": "C++"
},
{
"code": "// C++ code to demonstrate star pattern#include <iostream>using namespace std; // Function to demonstrate printing patternvoid pypart2(int n){ // number of spaces int k = 2 * n - 2; // Outer loop to handle number of rows // n in this case for (int i = n; i > 0; i--) { // Inner loop to handle number spaces // values changing acc. to requirement for (int j = 0; j < n-i; j++) cout << \" \"; // Decrementing k after each loop k = k - 2; // Inner loop to handle number of columns // values changing acc. to outer loop for (int j = 0; j < i; j++) { // Printing stars cout << \"* \"; } // Ending line after each row cout << endl; }} // Driver Codeint main(){ int n = 5; // Function Call pypart2(n); return 0;}",
"e": 5543,
"s": 4690,
"text": null
},
{
"code": null,
"e": 5599,
"s": 5543,
"text": "* * * * * \n * * * * \n * * * \n * * \n * \n"
},
{
"code": null,
"e": 5639,
"s": 5599,
"text": "Printing above pattern using while loop"
},
{
"code": null,
"e": 5643,
"s": 5639,
"text": "C++"
},
{
"code": "// C++ code to demonstrate pattern printing#include <iostream>using namespace std; // Function to demonstrate printing patternvoid pypart2(int n){ int i = n, j = 0, k = 0; while (i > 0) { // for number of spaces while (k < (n - i)) { cout << \" \"; k++; } // resetting k because we want to run k from // beginning. k = 0; while (j < i) { cout << \"* \"; j++; } // resetting k so as it can start from 0. j = 0; i--; cout << endl; }} // Driver Codeint main(){ int n = 5; // Function Call pypart2(n); return 0;}",
"e": 6324,
"s": 5643,
"text": null
},
{
"code": null,
"e": 6380,
"s": 6324,
"text": "* * * * * \n * * * * \n * * * \n * * \n * \n"
},
{
"code": null,
"e": 6398,
"s": 6380,
"text": "Printing Triangle"
},
{
"code": null,
"e": 6407,
"s": 6398,
"text": "Method 1"
},
{
"code": null,
"e": 6416,
"s": 6407,
"text": "Method 2"
},
{
"code": "// C++ code to demonstrate star pattern#include <iostream>using namespace std; // Function to demonstrate printing patternvoid triangle(int n){ // number of spaces int k = 2 * n - 2; // Outer loop to handle number of rows // n in this case for (int i = 0; i < n; i++) { // Inner loop to handle number spaces // values changing acc. to requirement for (int j = 0; j < k; j++) cout << \" \"; // Decrementing k after each loop k = k - 1; // Inner loop to handle number of columns // values changing acc. to outer loop for (int j = 0; j <= i; j++) { // Printing stars cout << \"* \"; } // Ending line after each row cout << endl; }} // Driver Codeint main(){ int n = 5; // Function Call triangle(n); return 0;}",
"e": 7269,
"s": 6416,
"text": null
},
{
"code": "// C++ code to demonstrate star pattern#include <iostream>using namespace std; // Function to demonstrate printing patternvoid pypart2(int n){ // Number of spaces int i, j, k = n; // Outer loop to handle number of rows // n in this case for (i = 1; i <= n; i++) { // Inner loop for columns for (j = 1; j <= n; j++) { // Condition to print star pattern if (j >= k) cout << \"* \"; else cout << \" \"; } k--; cout << \"\\n\"; }} // Driver Codeint main(){ int n = 5; // Function Call pypart2(n); return 0;}",
"e": 7900,
"s": 7269,
"text": null
},
{
"code": null,
"e": 7966,
"s": 7900,
"text": " * \n * * \n * * * \n * * * * \n * * * * * \n"
},
{
"code": null,
"e": 7977,
"s": 7968,
"text": "Method 3"
},
{
"code": "// C++ code to demonstrate star pattern#include <iostream>using namespace std; // Function to demonstrate printing patternvoid pypart2(int n){ int i = 0, j = 0, k = 0; while (i < n) { // for spacing while (k <= n - i - 2) { cout << \" \"; k++; } k = 0; // For Pattern printing while (j < 2 * i - 1) { cout << \"*\"; j++; } j = 0; i++; cout << endl; }} // Driver Codeint main(){ int n = 5; // Function Call pypart2(n); return 0;}",
"e": 8558,
"s": 7977,
"text": null
},
{
"code": null,
"e": 8590,
"s": 8558,
"text": " \n *\n ***\n *****\n*******\n"
},
{
"code": null,
"e": 8605,
"s": 8590,
"text": "Number Pattern"
},
{
"code": null,
"e": 8609,
"s": 8605,
"text": "CPP"
},
{
"code": "// C++ code to demonstrate printing// pattern of numbers#include <iostream>using namespace std; // Function to demonstrate printing// patternvoid numpat(int n){ // initializing starting number int num = 1; // Outer loop to handle number of rows // n in this case for (int i = 0; i < n; i++) { // Inner loop to handle number of columns // values changing acc. to outer loop for (int j = 0; j <= i; j++) cout << num << \" \"; // Incrementing number at each column num = num + 1; // Ending line after each row cout << endl; }} // Driver Codeint main(){ int n = 5; // Function Call numpat(n); return 0;}",
"e": 9302,
"s": 8609,
"text": null
},
{
"code": null,
"e": 9338,
"s": 9302,
"text": "1 \n2 2 \n3 3 3 \n4 4 4 4 \n5 5 5 5 5 \n"
},
{
"code": null,
"e": 9371,
"s": 9338,
"text": "Above Pattern Using while loop "
},
{
"code": null,
"e": 9375,
"s": 9371,
"text": "CPP"
},
{
"code": "// C++ Code for pattern Printing#include <iostream>using namespace std; // Function to demonstrate printing patternvoid pypart(int n){ int i = 1, j = 0; while (i <= n) { while (j <= i - 1) { cout << i << \" \"; j++; } j = 0; i++; cout << endl; }} // Driver Codeint main(){ int n = 5; // Function Call pypart(n); return 0;}",
"e": 9779,
"s": 9375,
"text": null
},
{
"code": null,
"e": 9815,
"s": 9779,
"text": "1 \n2 2 \n3 3 3 \n4 4 4 4 \n5 5 5 5 5 \n"
},
{
"code": null,
"e": 9845,
"s": 9817,
"text": "Numbers without reassigning"
},
{
"code": null,
"e": 9849,
"s": 9845,
"text": "CPP"
},
{
"code": "// C++ code to demonstrate printing pattern of numbers#include <iostream>using namespace std; // Function to demonstrate printing patternvoid numpat(int n){ // Initialising starting number int num = 1; // Outer loop to handle number of rows // n in this case for (int i = 0; i < n; i++) { // Inner loop to handle number of columns // values changing acc. to outer loop for (int j = 0; j <= i; j++) { // Printing number cout << num << \" \"; // Incrementing number at each column num = num + 1; } // Ending line after each row cout << endl; }} // Driver Codeint main(){ int n = 5; // Function Call numpat(n); return 0;}",
"e": 10589,
"s": 9849,
"text": null
},
{
"code": null,
"e": 10631,
"s": 10589,
"text": "1 \n2 3 \n4 5 6 \n7 8 9 10 \n11 12 13 14 15 \n"
},
{
"code": null,
"e": 10662,
"s": 10631,
"text": "Above pattern using while loop"
},
{
"code": null,
"e": 10666,
"s": 10662,
"text": "CPP"
},
{
"code": "// C++ code to demonstrate printing pattern of numbers#include <iostream>using namespace std; // Function to demonstrate printing patternvoid pypart(int n){ int i = 1, j = 0; // here we declare an num variable which is // assigned value 1 int num = 1; while (i <= n) { while (j <= i - 1) { // Printing numbers cout << num << \" \"; // here we are increasing num for every // iteration. num++; j++; } j = 0; i++; // Ending line after each row cout << endl; }} // Driver Codeint main(){ int n = 5; // Function Call pypart(n); return 0;}",
"e": 11363,
"s": 10666,
"text": null
},
{
"code": null,
"e": 11405,
"s": 11363,
"text": "1 \n2 3 \n4 5 6 \n7 8 9 10 \n11 12 13 14 15 \n"
},
{
"code": null,
"e": 11409,
"s": 11405,
"text": "C++"
},
{
"code": "#include <iostream>using namespace std; int main(){ int rows = 5, count = 0, count1 = 0, k = 0; for(int i = 1; i <= rows; ++i) { for(int space = 1; space <= rows-i; ++space) { cout << \" \"; ++count; } while(k != 2*i-1) { if (count <= rows-1) { cout << i+k << \" \"; ++count; } ++k; } count1 = count = k = 0; cout << endl; } return 0;} //code by Kashif RB",
"e": 11946,
"s": 11409,
"text": null
},
{
"code": null,
"e": 12002,
"s": 11946,
"text": " 1 \n 2 3 \n 3 4 5 \n 4 5 6 7 \n5 6 7 8 9 \n"
},
{
"code": null,
"e": 12006,
"s": 12002,
"text": "C++"
},
{
"code": "#include <iostream>using namespace std; int main(){ int rows=5, count = 0, count1 = 0, k = 0; for(int i = 1; i <= rows; ++i) { for(int space = 1; space <= rows-i; ++space) { cout << \" \"; ++count; } while(k != 2*i-1) { if (count <= rows-1) { cout << i+k << \" \"; ++count; } else { ++count1; cout << i+k-2*count1 << \" \"; } ++k; } count1 = count = k = 0; cout << endl; } return 0;} // code by Kashif Rb",
"e": 12640,
"s": 12006,
"text": null
},
{
"code": null,
"e": 12716,
"s": 12640,
"text": " 1 \n 2 3 2 \n 3 4 5 4 3 \n 4 5 6 7 6 5 4 \n5 6 7 8 9 8 7 6 5 \n"
},
{
"code": null,
"e": 12734,
"s": 12716,
"text": "Character Pattern"
},
{
"code": null,
"e": 12738,
"s": 12734,
"text": "CPP"
},
{
"code": "// C++ code to demonstrate printing pattern of alphabets#include <iostream>using namespace std; // Function to demonstrate printing patternvoid alphabet(int n){ // Initializing value corresponding to 'A' // ASCII value int num = 65; // Outer loop to handle number of rows // n in this case for (int i = 0; i < n; i++) { // Inner loop to handle number of columns // values changing acc. to outer loop for (int j = 0; j <= i; j++) { // Explicitly converting to char char ch = char(num); // Printing char value cout << ch << \" \"; } // Incrementing number num = num + 1; // Ending line after each row cout << endl; }} // Driver Functionint main(){ int n = 5; alphabet(n); return 0;}",
"e": 13553,
"s": 12738,
"text": null
},
{
"code": null,
"e": 13589,
"s": 13553,
"text": "A \nB B \nC C C \nD D D D \nE E E E E \n"
},
{
"code": null,
"e": 13622,
"s": 13591,
"text": "Above pattern using while loop"
},
{
"code": null,
"e": 13626,
"s": 13622,
"text": "CPP"
},
{
"code": "// C++ code to demonstrate printing pattern of alphabets#include <iostream>using namespace std; // Function to demonstrate printing patternvoid alphabet(int n){ int i = 1, j = 0; // assigning ASCII value of A which is 65 int num = 65; // converting ASCII value to character, // now our alpha variable is having // value A after typecasting. char alpha = char(num); while (i <= n) { // alpha is having A value and it // will change as soon as alpha // increased or decreased. while (j <= i - 1) { cout << alpha << \" \"; j++; } // incrementing alpha value so as it can // point to next character alpha++; // we have to reset j value so as it can // start from beginning and print * equal to // i. j = 0; i++; // Ending line after each row cout << endl; }} // Driver Codeint main(){ int n = 5; // Function Call alphabet(n); return 0;}",
"e": 14640,
"s": 13626,
"text": null
},
{
"code": null,
"e": 14676,
"s": 14640,
"text": "A \nB B \nC C C \nD D D D \nE E E E E \n"
},
{
"code": null,
"e": 14707,
"s": 14678,
"text": "Continuous Character pattern"
},
{
"code": null,
"e": 14711,
"s": 14707,
"text": "CPP"
},
{
"code": "// C++ code to demonstrate printing pattern of alphabets#include <iostream>using namespace std; // Function to demonstrate printing patternvoid contalpha(int n){ // Initializing value corresponding to 'A' // ASCII value int num = 65; // Outer loop to handle number of rows // n in this case for (int i = 0; i < n; i++) { // Inner loop to handle number of columns // values changing acc. to outer loop for (int j = 0; j <= i; j++) { // Explicitly converting to char char ch = char(num); // Printing char value cout << ch << \" \"; // Incrementing number at each column num = num + 1; } // Ending line after each row cout << endl; }} // Driver Codeint main(){ int n = 5; // Function Call contalpha(n); return 0;}",
"e": 15572,
"s": 14711,
"text": null
},
{
"code": null,
"e": 15608,
"s": 15572,
"text": "A \nB C \nD E F \nG H I J \nK L M N O \n"
},
{
"code": null,
"e": 15639,
"s": 15608,
"text": "Above pattern using while loop"
},
{
"code": null,
"e": 15643,
"s": 15639,
"text": "CPP"
},
{
"code": "// C++ code to demonstrate printing pattern of alphabets#include <iostream>using namespace std; // Function to demonstrate printing patternvoid contalpha(int n){ int i = 1, j = 0; int num = 65; char alpha = char(num); while (i <= n) { while (j <= i - 1) { cout << alpha << \" \"; // incrementing alpha value in every // iteration so as it can assign to // next character alpha++; j++; } j = 0; i++; // Ending line after each row cout << endl; }} // Driver Codeint main(){ int n = 5; // Function Call contalpha(n); return 0;}",
"e": 16328,
"s": 15643,
"text": null
},
{
"code": null,
"e": 16364,
"s": 16328,
"text": "A \nB C \nD E F \nG H I J \nK L M N O \n"
},
{
"code": null,
"e": 16918,
"s": 16364,
"text": "Printing patterns in python language are discussed in the article below :Programs for printing pyramid patterns in PythonThis article is contributed by Manjeet Singh(S.Nandini). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 16934,
"s": 16918,
"text": "prathvirsingh18"
},
{
"code": null,
"e": 16950,
"s": 16934,
"text": "gauravdalvi2012"
},
{
"code": null,
"e": 16963,
"s": 16950,
"text": "deysoumavo65"
},
{
"code": null,
"e": 16976,
"s": 16963,
"text": "dhruvrohilla"
},
{
"code": null,
"e": 16992,
"s": 16976,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 17002,
"s": 16992,
"text": "ruhelaa48"
},
{
"code": null,
"e": 17017,
"s": 17002,
"text": "adnanirshad158"
},
{
"code": null,
"e": 17034,
"s": 17017,
"text": "arorakashish0911"
},
{
"code": null,
"e": 17057,
"s": 17034,
"text": "muhammadkashifbhatti70"
},
{
"code": null,
"e": 17070,
"s": 17057,
"text": "cpdwivedi916"
},
{
"code": null,
"e": 17087,
"s": 17070,
"text": "pattern-printing"
},
{
"code": null,
"e": 17091,
"s": 17087,
"text": "C++"
},
{
"code": null,
"e": 17110,
"s": 17091,
"text": "School Programming"
},
{
"code": null,
"e": 17127,
"s": 17110,
"text": "pattern-printing"
},
{
"code": null,
"e": 17131,
"s": 17127,
"text": "CPP"
}
]
|
MongoDB – Maximum operator ( $max ) | 19 Apr, 2020
MongoDB provides different types of field update operators to update the values of the fields in the documents and the maximum operator ( $max ) is one of them. This operator updates the field with the specified value if the specified value is greater than the current value.
This operator will compare the values of different data types according to the BSON comparison order.
You can also use this operator in embedded/nested documents using dot notation.
You can use this operator in methods like update(), updateOne() etc. according to your requirements.
If the given field does not exists, then this operator will create field and set the value of that field.
Syntax:
{ $max: { field1: value1, field2: value2 ... } }
In the following examples, we are working with:
Database: GeeksforGeeksCollection: contributorDocument: three documents that contain the details of the contributors in the form of field-value pairs.
In this example, we are comparing values(or numbers) of the salary fields with the specified value, i.e., 5000. Here, the specified value is greater than the current value. So, $max operator updates the value of the salary field with the help of update() method to 5000.
db.contributor.update({name: "Mohit"}, {$max: {salary: 5000}})
If the current value of the salary field is less than the specified value, then this operator will not update the value of the salary field with the specified value, i.e., 4000.
db.contributor.update({name: "Mohit"}, {$max: {salary: 4000}})
In this example, we are comparing values(or numbers) of the rank fields with the specified value, i.e., 30. Here, the specified value is greater than the current value. So, $max operator updates the value of the salary field with the help of update() method to 30.
db.contributor.update({name: "Priya"}, {$max: {"personal.rank": 30}})
If the current value of the rank field is less than the specified value, then this operator will not update the value of the rank field with the specified value, i.e., 13.
db.contributor.update({name: "Priya"}, {$max: {"personal.rank": 13}})
MongoDB
Advanced Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Apr, 2020"
},
{
"code": null,
"e": 304,
"s": 28,
"text": "MongoDB provides different types of field update operators to update the values of the fields in the documents and the maximum operator ( $max ) is one of them. This operator updates the field with the specified value if the specified value is greater than the current value."
},
{
"code": null,
"e": 406,
"s": 304,
"text": "This operator will compare the values of different data types according to the BSON comparison order."
},
{
"code": null,
"e": 486,
"s": 406,
"text": "You can also use this operator in embedded/nested documents using dot notation."
},
{
"code": null,
"e": 587,
"s": 486,
"text": "You can use this operator in methods like update(), updateOne() etc. according to your requirements."
},
{
"code": null,
"e": 693,
"s": 587,
"text": "If the given field does not exists, then this operator will create field and set the value of that field."
},
{
"code": null,
"e": 701,
"s": 693,
"text": "Syntax:"
},
{
"code": null,
"e": 750,
"s": 701,
"text": "{ $max: { field1: value1, field2: value2 ... } }"
},
{
"code": null,
"e": 798,
"s": 750,
"text": "In the following examples, we are working with:"
},
{
"code": null,
"e": 949,
"s": 798,
"text": "Database: GeeksforGeeksCollection: contributorDocument: three documents that contain the details of the contributors in the form of field-value pairs."
},
{
"code": null,
"e": 1220,
"s": 949,
"text": "In this example, we are comparing values(or numbers) of the salary fields with the specified value, i.e., 5000. Here, the specified value is greater than the current value. So, $max operator updates the value of the salary field with the help of update() method to 5000."
},
{
"code": "db.contributor.update({name: \"Mohit\"}, {$max: {salary: 5000}})",
"e": 1283,
"s": 1220,
"text": null
},
{
"code": null,
"e": 1461,
"s": 1283,
"text": "If the current value of the salary field is less than the specified value, then this operator will not update the value of the salary field with the specified value, i.e., 4000."
},
{
"code": "db.contributor.update({name: \"Mohit\"}, {$max: {salary: 4000}})",
"e": 1524,
"s": 1461,
"text": null
},
{
"code": null,
"e": 1789,
"s": 1524,
"text": "In this example, we are comparing values(or numbers) of the rank fields with the specified value, i.e., 30. Here, the specified value is greater than the current value. So, $max operator updates the value of the salary field with the help of update() method to 30."
},
{
"code": "db.contributor.update({name: \"Priya\"}, {$max: {\"personal.rank\": 30}})",
"e": 1859,
"s": 1789,
"text": null
},
{
"code": null,
"e": 2031,
"s": 1859,
"text": "If the current value of the rank field is less than the specified value, then this operator will not update the value of the rank field with the specified value, i.e., 13."
},
{
"code": "db.contributor.update({name: \"Priya\"}, {$max: {\"personal.rank\": 13}})",
"e": 2101,
"s": 2031,
"text": null
},
{
"code": null,
"e": 2109,
"s": 2101,
"text": "MongoDB"
},
{
"code": null,
"e": 2135,
"s": 2109,
"text": "Advanced Computer Subject"
}
]
|
Multiply two polynomials | 24 Jun, 2022
Given two polynomials represented by two arrays, write a function that multiplies given two polynomials.
Example:
Input: A[] = {5, 0, 10, 6}
B[] = {1, 2, 4}
Output: prod[] = {5, 10, 30, 26, 52, 24}
The first input array represents "5 + 0x^1 + 10x^2 + 6x^3"
The second array represents "1 + 2x^1 + 4x^2"
And Output is "5 + 10x^1 + 30x^2 + 26x^3 + 52x^4 + 24x^5"
A simple solution is to one by one consider every term of the first polynomial and multiply it with every term of the second polynomial. Following is the algorithm of this simple method.
multiply(A[0..m-1], B[0..n01])
1) Create a product array prod[] of size m+n-1.
2) Initialize all entries in prod[] as 0.
3) Traverse array A[] and do following for every element A[i]
...(3.a) Traverse array B[] and do following for every element B[j]
prod[i+j] = prod[i+j] + A[i] * B[j]
4) Return prod[].
The following is the implementation of the above algorithm.
C++
Java
Python3
C#
PHP
Javascript
// Simple C++ program to multiply two polynomials#include <iostream>using namespace std; // A[] represents coefficients of first polynomial// B[] represents coefficients of second polynomial// m and n are sizes of A[] and B[] respectivelyint *multiply(int A[], int B[], int m, int n){ int *prod = new int[m+n-1]; // Initialize the product polynomial for (int i = 0; i<m+n-1; i++) prod[i] = 0; // Multiply two polynomials term by term // Take ever term of first polynomial for (int i=0; i<m; i++) { // Multiply the current term of first polynomial // with every term of second polynomial. for (int j=0; j<n; j++) prod[i+j] += A[i]*B[j]; } return prod;} // A utility function to print a polynomialvoid printPoly(int poly[], int n){ for (int i=0; i<n; i++) { cout << poly[i]; if (i != 0) cout << "x^" << i ; if (i != n-1) cout << " + "; }} // Driver program to test above functionsint main(){ // The following array represents polynomial 5 + 10x^2 + 6x^3 int A[] = {5, 0, 10, 6}; // The following array represents polynomial 1 + 2x + 4x^2 int B[] = {1, 2, 4}; int m = sizeof(A)/sizeof(A[0]); int n = sizeof(B)/sizeof(B[0]); cout << "First polynomial is "; printPoly(A, m); cout <<endl<< "Second polynomial is "; printPoly(B, n); int *prod = multiply(A, B, m, n); cout <<endl<< "Product polynomial is "; printPoly(prod, m+n-1); return 0;}
// Java program to multiply two polynomialsclass GFG{ // A[] represents coefficients // of first polynomial // B[] represents coefficients // of second polynomial // m and n are sizes of A[] and B[] respectively static int[] multiply(int A[], int B[], int m, int n) { int[] prod = new int[m + n - 1]; // Initialize the product polynomial for (int i = 0; i < m + n - 1; i++) { prod[i] = 0; } // Multiply two polynomials term by term // Take ever term of first polynomial for (int i = 0; i < m; i++) { // Multiply the current term of first polynomial // with every term of second polynomial. for (int j = 0; j < n; j++) { prod[i + j] += A[i] * B[j]; } } return prod; } // A utility function to print a polynomial static void printPoly(int poly[], int n) { for (int i = 0; i < n; i++) { System.out.print(poly[i]); if (i != 0) { System.out.print("x^" + i); } if (i != n - 1) { System.out.print(" + "); } } } // Driver code public static void main(String[] args) { // The following array represents // polynomial 5 + 10x^2 + 6x^3 int A[] = {5, 0, 10, 6}; // The following array represents // polynomial 1 + 2x + 4x^2 int B[] = {1, 2, 4}; int m = A.length; int n = B.length; System.out.println("First polynomial is n"); printPoly(A, m); System.out.println("nSecond polynomial is n"); printPoly(B, n); int[] prod = multiply(A, B, m, n); System.out.println("nProduct polynomial is n"); printPoly(prod, m + n - 1); }} // This code contributed by Rajput-Ji
# Simple Python3 program to multiply two polynomials # A[] represents coefficients of first polynomial# B[] represents coefficients of second polynomial# m and n are sizes of A[] and B[] respectivelydef multiply(A, B, m, n): prod = [0] * (m + n - 1); # Multiply two polynomials term by term # Take ever term of first polynomial for i in range(m): # Multiply the current term of first # polynomial with every term of # second polynomial. for j in range(n): prod[i + j] += A[i] * B[j]; return prod; # A utility function to print a polynomialdef printPoly(poly, n): for i in range(n): print(poly[i], end = ""); if (i != 0): print("x^", i, end = ""); if (i != n - 1): print(" + ", end = ""); # Driver Code # The following array represents# polynomial 5 + 10x^2 + 6x^3A = [5, 0, 10, 6]; # The following array represents # polynomial 1 + 2x + 4x^2B = [1, 2, 4];m = len(A);n = len(B); print("First polynomial is ");printPoly(A, m);print("\nSecond polynomial is ");printPoly(B, n); prod = multiply(A, B, m, n); print("\nProduct polynomial is ");printPoly(prod, m+n-1); # This code is contributed by chandan_jnu
// C# program to multiply two polynomialsusing System; class GFG { // A[] represents coefficients // of first polynomial // B[] represents coefficients // of second polynomial // m and n are sizes of A[] // and B[] respectively static int[] multiply(int []A, int []B, int m, int n) { int[] prod = new int[m + n - 1]; // Initialize the product polynomial for (int i = 0; i < m + n - 1; i++) { prod[i] = 0; } // Multiply two polynomials term by term // Take ever term of first polynomial for (int i = 0; i < m; i++) { // Multiply the current term of first polynomial // with every term of second polynomial. for (int j = 0; j < n; j++) { prod[i + j] += A[i] * B[j]; } } return prod; } // A utility function to print a polynomial static void printPoly(int []poly, int n) { for (int i = 0; i < n; i++) { Console.Write(poly[i]); if (i != 0) { Console.Write("x^" + i); } if (i != n - 1) { Console.Write(" + "); } } } // Driver code public static void Main(String[] args) { // The following array represents // polynomial 5 + 10x^2 + 6x^3 int []A = {5, 0, 10, 6}; // The following array represents // polynomial 1 + 2x + 4x^2 int []B = {1, 2, 4}; int m = A.Length; int n = B.Length; Console.WriteLine("First polynomial is n"); printPoly(A, m); Console.WriteLine("nSecond polynomial is n"); printPoly(B, n); int[] prod = multiply(A, B, m, n); Console.WriteLine("nProduct polynomial is n"); printPoly(prod, m + n - 1); }} // This code has been contributed by 29AjayKumar
<?php// Simple PHP program to multiply two polynomials // A[] represents coefficients of first polynomial// B[] represents coefficients of second polynomial// m and n are sizes of A[] and B[] respectivelyfunction multiply($A, $B, $m, $n){ $prod = array_fill(0, $m + $n - 1, 0); // Multiply two polynomials term by term // Take ever term of first polynomial for ($i = 0; $i < $m; $i++) { // Multiply the current term of first // polynomial with every term of // second polynomial. for ($j = 0; $j < $n; $j++) $prod[$i + $j] += $A[$i] * $B[$j]; } return $prod;} // A utility function to print a polynomialfunction printPoly($poly, $n){ for ($i = 0; $i < $n; $i++) { echo $poly[$i]; if ($i != 0) echo "x^" . $i; if ($i != $n - 1) echo " + "; }} // Driver Code // The following array represents// polynomial 5 + 10x^2 + 6x^3$A = array(5, 0, 10, 6); // The following array represents // polynomial 1 + 2x + 4x^2$B = array(1, 2, 4);$m = count($A);$n = count($B); echo "First polynomial is \n";printPoly($A, $m);echo "\nSecond polynomial is \n";printPoly($B, $n); $prod = multiply($A, $B, $m, $n); echo "\nProduct polynomial is \n";printPoly($prod, $m+$n-1); // This code is contributed by chandan_jnu?>
<script> // Simple JavaScript program to multiply two polynomials // A[] represents coefficients of first polynomial // B[] represents coefficients of second polynomial // m and n are sizes of A[] and B[] respectively function multiply(A, B, m, n){ var prod = []; for (var i = 0; i < m + n - 1; i++) prod[i] = 0; // Multiply two polynomials term by term // Take ever term of first polynomial for(var i = 0; i < m ; i++){ // Multiply the current term of first // polynomial with every term of // second polynomial. for (var j = 0; j < n ; j++) prod[i + j] += A[i] * B[j]; } return prod; } // A utility function to print a polynomial function printPoly(poly, n){ let ans= ''; for (var i = 0; i < n ; i++){ ans += poly[i]; if (i != 0) ans +="x^ "+i; if (i != n - 1) ans += " + "; } document.write(ans) } // Driver Code // The following array represents // polynomial 5 + 10x^2 + 6x^3 A = [5, 0, 10, 6]; // The following array represents // polynomial 1 + 2x + 4x^2 let B = [1, 2, 4]; let m = (A).length; let n = (B).length; document.write("First polynomial is " + "<br>"); printPoly(A, m); document.write("<br>"); document.write("Second polynomial is " + "<br>"); printPoly(B, n); let prod = multiply(A, B, m, n); document.write("<br>"); document.write("Product polynomial is " + "<br>"); printPoly(prod, m+n-1); </script>
First polynomial is 5 + 0x^1 + 10x^2 + 6x^3
Second polynomial is 1 + 2x^1 + 4x^2
Product polynomial is 5 + 10x^1 + 30x^2 + 26x^3 + 52x^4 + 24x^5
The time complexity of the above solution is O(mn). If the size of two polynomials same, then the time complexity is O(n2).
Auxiliary Space: O(m + n)
Can we do better? There are methods to do multiplication faster than O(n2) time. These methods are mainly based on divide and conquer. Following is one simple method that divides the given polynomial (of degree n) into two polynomials one containing lower degree terms(lower than n/2) and the other containing higher degree terms (higher than or equal to n/2)
Let the two given polynomials be A and B.
For simplicity, Let us assume that the given two polynomials are of
same degree and have degree in powers of 2, i.e., n = 2i
The polynomial 'A' can be written as A0 + A1*xn/2
The polynomial 'B' can be written as B0 + B1*xn/2
For example 1 + 10x + 6x2 - 4x3 + 5x4 can be
written as (1 + 10x) + (6 - 4x + 5x2)*x2
A * B = (A0 + A1*xn/2) * (B0 + B1*xn/2)
= A0*B0 + A0*B1*xn/2 + A1*B0*xn/2 + A1*B1*xn
= A0*B0 + (A0*B1 + A1*B0)xn/2 + A1*B1*xn
So the above divide and conquer approach requires 4 multiplications and O(n) time to add all 4 results. Therefore the time complexity is T(n) = 4T(n/2) + O(n). The solution of the recurrence is O(n2) which is the same as the above simple solution.The idea is to reduce the number of multiplications to 3 and make the recurrence as T(n) = 3T(n/2) + O(n)
How to reduce the number of multiplications? This requires a little trick similar to Strassen’s Matrix Multiplication. We do the following 3 multiplications.
X = (A0 + A1)*(B0 + B1) // First Multiplication
Y = A0B0 // Second
Z = A1B1 // Third
The missing middle term in above multiplication equation A0*B0 + (A0*B1 +
A1*B0)xn/2 + A1*B1*xn can obtained using below.
A0B1 + A1B0 = X - Y - Z
In-Depth Explanation Conventional polynomial multiplication uses 4 coefficient multiplications:
(ax + b)(cx + d) = acx2 + (ad + bc)x + bd
However, notice the following relation:
(a + b)(c + d) = ad + bc + ac + bd
The rest of the two components are exactly the middle coefficient for the product of two polynomials. Therefore, the product can be computed as:
(ax + b)(cx + d) = acx2 +
((a + b)(c + d) - ac - bd )x + bd
Hence, the latter expression has only three multiplications.So the time taken by this algorithm is T(n) = 3T(n/2) + O(n) The solution of the above recurrence is O(nLg3) which is better than O(n2).We will soon be discussing the implementation of the above approach. There is an O(nLogn) algorithm also that uses Fast Fourier Transform to multiply two polynomials (Refer to this and this for details)
Mr.L
Chandan_Kumar
Rajput-Ji
29AjayKumar
sumeshthakur402
shubham_singh
rohitsingh07052
surindertarika1234
simmytarika5
subham348
chhabradhanvi
hardikkoriintern
maths-polynomial
Samsung
Divide and Conquer
Linked List
Mathematical
Samsung
Linked List
Mathematical
Divide and Conquer
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n24 Jun, 2022"
},
{
"code": null,
"e": 158,
"s": 52,
"text": "Given two polynomials represented by two arrays, write a function that multiplies given two polynomials. "
},
{
"code": null,
"e": 168,
"s": 158,
"text": "Example: "
},
{
"code": null,
"e": 428,
"s": 168,
"text": "Input: A[] = {5, 0, 10, 6} \n B[] = {1, 2, 4} \nOutput: prod[] = {5, 10, 30, 26, 52, 24}\n\nThe first input array represents \"5 + 0x^1 + 10x^2 + 6x^3\"\nThe second array represents \"1 + 2x^1 + 4x^2\" \nAnd Output is \"5 + 10x^1 + 30x^2 + 26x^3 + 52x^4 + 24x^5\""
},
{
"code": null,
"e": 616,
"s": 428,
"text": "A simple solution is to one by one consider every term of the first polynomial and multiply it with every term of the second polynomial. Following is the algorithm of this simple method. "
},
{
"code": null,
"e": 931,
"s": 616,
"text": "multiply(A[0..m-1], B[0..n01])\n1) Create a product array prod[] of size m+n-1.\n2) Initialize all entries in prod[] as 0.\n3) Traverse array A[] and do following for every element A[i]\n...(3.a) Traverse array B[] and do following for every element B[j]\n prod[i+j] = prod[i+j] + A[i] * B[j]\n4) Return prod[]."
},
{
"code": null,
"e": 992,
"s": 931,
"text": "The following is the implementation of the above algorithm. "
},
{
"code": null,
"e": 996,
"s": 992,
"text": "C++"
},
{
"code": null,
"e": 1001,
"s": 996,
"text": "Java"
},
{
"code": null,
"e": 1009,
"s": 1001,
"text": "Python3"
},
{
"code": null,
"e": 1012,
"s": 1009,
"text": "C#"
},
{
"code": null,
"e": 1016,
"s": 1012,
"text": "PHP"
},
{
"code": null,
"e": 1027,
"s": 1016,
"text": "Javascript"
},
{
"code": "// Simple C++ program to multiply two polynomials#include <iostream>using namespace std; // A[] represents coefficients of first polynomial// B[] represents coefficients of second polynomial// m and n are sizes of A[] and B[] respectivelyint *multiply(int A[], int B[], int m, int n){ int *prod = new int[m+n-1]; // Initialize the product polynomial for (int i = 0; i<m+n-1; i++) prod[i] = 0; // Multiply two polynomials term by term // Take ever term of first polynomial for (int i=0; i<m; i++) { // Multiply the current term of first polynomial // with every term of second polynomial. for (int j=0; j<n; j++) prod[i+j] += A[i]*B[j]; } return prod;} // A utility function to print a polynomialvoid printPoly(int poly[], int n){ for (int i=0; i<n; i++) { cout << poly[i]; if (i != 0) cout << \"x^\" << i ; if (i != n-1) cout << \" + \"; }} // Driver program to test above functionsint main(){ // The following array represents polynomial 5 + 10x^2 + 6x^3 int A[] = {5, 0, 10, 6}; // The following array represents polynomial 1 + 2x + 4x^2 int B[] = {1, 2, 4}; int m = sizeof(A)/sizeof(A[0]); int n = sizeof(B)/sizeof(B[0]); cout << \"First polynomial is \"; printPoly(A, m); cout <<endl<< \"Second polynomial is \"; printPoly(B, n); int *prod = multiply(A, B, m, n); cout <<endl<< \"Product polynomial is \"; printPoly(prod, m+n-1); return 0;}",
"e": 2507,
"s": 1027,
"text": null
},
{
"code": "// Java program to multiply two polynomialsclass GFG{ // A[] represents coefficients // of first polynomial // B[] represents coefficients // of second polynomial // m and n are sizes of A[] and B[] respectively static int[] multiply(int A[], int B[], int m, int n) { int[] prod = new int[m + n - 1]; // Initialize the product polynomial for (int i = 0; i < m + n - 1; i++) { prod[i] = 0; } // Multiply two polynomials term by term // Take ever term of first polynomial for (int i = 0; i < m; i++) { // Multiply the current term of first polynomial // with every term of second polynomial. for (int j = 0; j < n; j++) { prod[i + j] += A[i] * B[j]; } } return prod; } // A utility function to print a polynomial static void printPoly(int poly[], int n) { for (int i = 0; i < n; i++) { System.out.print(poly[i]); if (i != 0) { System.out.print(\"x^\" + i); } if (i != n - 1) { System.out.print(\" + \"); } } } // Driver code public static void main(String[] args) { // The following array represents // polynomial 5 + 10x^2 + 6x^3 int A[] = {5, 0, 10, 6}; // The following array represents // polynomial 1 + 2x + 4x^2 int B[] = {1, 2, 4}; int m = A.length; int n = B.length; System.out.println(\"First polynomial is n\"); printPoly(A, m); System.out.println(\"nSecond polynomial is n\"); printPoly(B, n); int[] prod = multiply(A, B, m, n); System.out.println(\"nProduct polynomial is n\"); printPoly(prod, m + n - 1); }} // This code contributed by Rajput-Ji",
"e": 4454,
"s": 2507,
"text": null
},
{
"code": "# Simple Python3 program to multiply two polynomials # A[] represents coefficients of first polynomial# B[] represents coefficients of second polynomial# m and n are sizes of A[] and B[] respectivelydef multiply(A, B, m, n): prod = [0] * (m + n - 1); # Multiply two polynomials term by term # Take ever term of first polynomial for i in range(m): # Multiply the current term of first # polynomial with every term of # second polynomial. for j in range(n): prod[i + j] += A[i] * B[j]; return prod; # A utility function to print a polynomialdef printPoly(poly, n): for i in range(n): print(poly[i], end = \"\"); if (i != 0): print(\"x^\", i, end = \"\"); if (i != n - 1): print(\" + \", end = \"\"); # Driver Code # The following array represents# polynomial 5 + 10x^2 + 6x^3A = [5, 0, 10, 6]; # The following array represents # polynomial 1 + 2x + 4x^2B = [1, 2, 4];m = len(A);n = len(B); print(\"First polynomial is \");printPoly(A, m);print(\"\\nSecond polynomial is \");printPoly(B, n); prod = multiply(A, B, m, n); print(\"\\nProduct polynomial is \");printPoly(prod, m+n-1); # This code is contributed by chandan_jnu",
"e": 5696,
"s": 4454,
"text": null
},
{
"code": "// C# program to multiply two polynomialsusing System; class GFG { // A[] represents coefficients // of first polynomial // B[] represents coefficients // of second polynomial // m and n are sizes of A[] // and B[] respectively static int[] multiply(int []A, int []B, int m, int n) { int[] prod = new int[m + n - 1]; // Initialize the product polynomial for (int i = 0; i < m + n - 1; i++) { prod[i] = 0; } // Multiply two polynomials term by term // Take ever term of first polynomial for (int i = 0; i < m; i++) { // Multiply the current term of first polynomial // with every term of second polynomial. for (int j = 0; j < n; j++) { prod[i + j] += A[i] * B[j]; } } return prod; } // A utility function to print a polynomial static void printPoly(int []poly, int n) { for (int i = 0; i < n; i++) { Console.Write(poly[i]); if (i != 0) { Console.Write(\"x^\" + i); } if (i != n - 1) { Console.Write(\" + \"); } } } // Driver code public static void Main(String[] args) { // The following array represents // polynomial 5 + 10x^2 + 6x^3 int []A = {5, 0, 10, 6}; // The following array represents // polynomial 1 + 2x + 4x^2 int []B = {1, 2, 4}; int m = A.Length; int n = B.Length; Console.WriteLine(\"First polynomial is n\"); printPoly(A, m); Console.WriteLine(\"nSecond polynomial is n\"); printPoly(B, n); int[] prod = multiply(A, B, m, n); Console.WriteLine(\"nProduct polynomial is n\"); printPoly(prod, m + n - 1); }} // This code has been contributed by 29AjayKumar ",
"e": 7639,
"s": 5696,
"text": null
},
{
"code": "<?php// Simple PHP program to multiply two polynomials // A[] represents coefficients of first polynomial// B[] represents coefficients of second polynomial// m and n are sizes of A[] and B[] respectivelyfunction multiply($A, $B, $m, $n){ $prod = array_fill(0, $m + $n - 1, 0); // Multiply two polynomials term by term // Take ever term of first polynomial for ($i = 0; $i < $m; $i++) { // Multiply the current term of first // polynomial with every term of // second polynomial. for ($j = 0; $j < $n; $j++) $prod[$i + $j] += $A[$i] * $B[$j]; } return $prod;} // A utility function to print a polynomialfunction printPoly($poly, $n){ for ($i = 0; $i < $n; $i++) { echo $poly[$i]; if ($i != 0) echo \"x^\" . $i; if ($i != $n - 1) echo \" + \"; }} // Driver Code // The following array represents// polynomial 5 + 10x^2 + 6x^3$A = array(5, 0, 10, 6); // The following array represents // polynomial 1 + 2x + 4x^2$B = array(1, 2, 4);$m = count($A);$n = count($B); echo \"First polynomial is \\n\";printPoly($A, $m);echo \"\\nSecond polynomial is \\n\";printPoly($B, $n); $prod = multiply($A, $B, $m, $n); echo \"\\nProduct polynomial is \\n\";printPoly($prod, $m+$n-1); // This code is contributed by chandan_jnu?>",
"e": 8969,
"s": 7639,
"text": null
},
{
"code": "<script> // Simple JavaScript program to multiply two polynomials // A[] represents coefficients of first polynomial // B[] represents coefficients of second polynomial // m and n are sizes of A[] and B[] respectively function multiply(A, B, m, n){ var prod = []; for (var i = 0; i < m + n - 1; i++) prod[i] = 0; // Multiply two polynomials term by term // Take ever term of first polynomial for(var i = 0; i < m ; i++){ // Multiply the current term of first // polynomial with every term of // second polynomial. for (var j = 0; j < n ; j++) prod[i + j] += A[i] * B[j]; } return prod; } // A utility function to print a polynomial function printPoly(poly, n){ let ans= ''; for (var i = 0; i < n ; i++){ ans += poly[i]; if (i != 0) ans +=\"x^ \"+i; if (i != n - 1) ans += \" + \"; } document.write(ans) } // Driver Code // The following array represents // polynomial 5 + 10x^2 + 6x^3 A = [5, 0, 10, 6]; // The following array represents // polynomial 1 + 2x + 4x^2 let B = [1, 2, 4]; let m = (A).length; let n = (B).length; document.write(\"First polynomial is \" + \"<br>\"); printPoly(A, m); document.write(\"<br>\"); document.write(\"Second polynomial is \" + \"<br>\"); printPoly(B, n); let prod = multiply(A, B, m, n); document.write(\"<br>\"); document.write(\"Product polynomial is \" + \"<br>\"); printPoly(prod, m+n-1); </script>",
"e": 10495,
"s": 8969,
"text": null
},
{
"code": null,
"e": 10640,
"s": 10495,
"text": "First polynomial is 5 + 0x^1 + 10x^2 + 6x^3\nSecond polynomial is 1 + 2x^1 + 4x^2\nProduct polynomial is 5 + 10x^1 + 30x^2 + 26x^3 + 52x^4 + 24x^5"
},
{
"code": null,
"e": 10764,
"s": 10640,
"text": "The time complexity of the above solution is O(mn). If the size of two polynomials same, then the time complexity is O(n2)."
},
{
"code": null,
"e": 10790,
"s": 10764,
"text": "Auxiliary Space: O(m + n)"
},
{
"code": null,
"e": 11151,
"s": 10790,
"text": "Can we do better? There are methods to do multiplication faster than O(n2) time. These methods are mainly based on divide and conquer. Following is one simple method that divides the given polynomial (of degree n) into two polynomials one containing lower degree terms(lower than n/2) and the other containing higher degree terms (higher than or equal to n/2) "
},
{
"code": null,
"e": 11652,
"s": 11151,
"text": "Let the two given polynomials be A and B. \nFor simplicity, Let us assume that the given two polynomials are of\nsame degree and have degree in powers of 2, i.e., n = 2i\n\nThe polynomial 'A' can be written as A0 + A1*xn/2\nThe polynomial 'B' can be written as B0 + B1*xn/2\n\nFor example 1 + 10x + 6x2 - 4x3 + 5x4 can be\nwritten as (1 + 10x) + (6 - 4x + 5x2)*x2\n\nA * B = (A0 + A1*xn/2) * (B0 + B1*xn/2)\n = A0*B0 + A0*B1*xn/2 + A1*B0*xn/2 + A1*B1*xn\n = A0*B0 + (A0*B1 + A1*B0)xn/2 + A1*B1*xn "
},
{
"code": null,
"e": 12006,
"s": 11652,
"text": "So the above divide and conquer approach requires 4 multiplications and O(n) time to add all 4 results. Therefore the time complexity is T(n) = 4T(n/2) + O(n). The solution of the recurrence is O(n2) which is the same as the above simple solution.The idea is to reduce the number of multiplications to 3 and make the recurrence as T(n) = 3T(n/2) + O(n) "
},
{
"code": null,
"e": 12165,
"s": 12006,
"text": "How to reduce the number of multiplications? This requires a little trick similar to Strassen’s Matrix Multiplication. We do the following 3 multiplications. "
},
{
"code": null,
"e": 12403,
"s": 12165,
"text": "X = (A0 + A1)*(B0 + B1) // First Multiplication\nY = A0B0 // Second \nZ = A1B1 // Third\n\nThe missing middle term in above multiplication equation A0*B0 + (A0*B1 + \nA1*B0)xn/2 + A1*B1*xn can obtained using below.\nA0B1 + A1B0 = X - Y - Z "
},
{
"code": null,
"e": 12500,
"s": 12403,
"text": "In-Depth Explanation Conventional polynomial multiplication uses 4 coefficient multiplications: "
},
{
"code": null,
"e": 12542,
"s": 12500,
"text": "(ax + b)(cx + d) = acx2 + (ad + bc)x + bd"
},
{
"code": null,
"e": 12582,
"s": 12542,
"text": "However, notice the following relation:"
},
{
"code": null,
"e": 12617,
"s": 12582,
"text": "(a + b)(c + d) = ad + bc + ac + bd"
},
{
"code": null,
"e": 12762,
"s": 12617,
"text": "The rest of the two components are exactly the middle coefficient for the product of two polynomials. Therefore, the product can be computed as:"
},
{
"code": null,
"e": 12823,
"s": 12762,
"text": "(ax + b)(cx + d) = acx2 + \n((a + b)(c + d) - ac - bd )x + bd"
},
{
"code": null,
"e": 13222,
"s": 12823,
"text": "Hence, the latter expression has only three multiplications.So the time taken by this algorithm is T(n) = 3T(n/2) + O(n) The solution of the above recurrence is O(nLg3) which is better than O(n2).We will soon be discussing the implementation of the above approach. There is an O(nLogn) algorithm also that uses Fast Fourier Transform to multiply two polynomials (Refer to this and this for details)"
},
{
"code": null,
"e": 13227,
"s": 13222,
"text": "Mr.L"
},
{
"code": null,
"e": 13241,
"s": 13227,
"text": "Chandan_Kumar"
},
{
"code": null,
"e": 13251,
"s": 13241,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 13263,
"s": 13251,
"text": "29AjayKumar"
},
{
"code": null,
"e": 13279,
"s": 13263,
"text": "sumeshthakur402"
},
{
"code": null,
"e": 13293,
"s": 13279,
"text": "shubham_singh"
},
{
"code": null,
"e": 13309,
"s": 13293,
"text": "rohitsingh07052"
},
{
"code": null,
"e": 13328,
"s": 13309,
"text": "surindertarika1234"
},
{
"code": null,
"e": 13341,
"s": 13328,
"text": "simmytarika5"
},
{
"code": null,
"e": 13351,
"s": 13341,
"text": "subham348"
},
{
"code": null,
"e": 13365,
"s": 13351,
"text": "chhabradhanvi"
},
{
"code": null,
"e": 13382,
"s": 13365,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 13399,
"s": 13382,
"text": "maths-polynomial"
},
{
"code": null,
"e": 13407,
"s": 13399,
"text": "Samsung"
},
{
"code": null,
"e": 13426,
"s": 13407,
"text": "Divide and Conquer"
},
{
"code": null,
"e": 13438,
"s": 13426,
"text": "Linked List"
},
{
"code": null,
"e": 13451,
"s": 13438,
"text": "Mathematical"
},
{
"code": null,
"e": 13459,
"s": 13451,
"text": "Samsung"
},
{
"code": null,
"e": 13471,
"s": 13459,
"text": "Linked List"
},
{
"code": null,
"e": 13484,
"s": 13471,
"text": "Mathematical"
},
{
"code": null,
"e": 13503,
"s": 13484,
"text": "Divide and Conquer"
}
]
|
Python – Retain Numbers in String | 03 Jul, 2020
Sometimes, while working with Python Strings, we can have a problem in which we need to perform the removal of all the characters other than integers. This kind of problem can have application in many data domains such as Machine Learning and web development. Let’s discuss certain ways in which this task can be performed.
Input : test_str = ‘G4g is No. 1’Output : 41
Input : test_str = ‘Gfg is No. 1’Output : 1
Method #1 : Using list comprehension + join() + isdigit()The combination of above functions can be used to solve this problem. In this, we perform the task of extracting integers using isdigit(), list comprehension is used for iteration and join() is used to perform join of numbers filtered.
# Python3 code to demonstrate working of # Retain Numbers in String# Using list comprehension + join() + isdigit() # initializing stringtest_str = 'G4g is No. 1 for Geeks 7' # printing original stringprint("The original string is : " + str(test_str)) # Retain Numbers in String# Using list comprehension + join() + isdigit()res = "".join([ele for ele in test_str if ele.isdigit()]) # printing result print("String after integer retention : " + str(res))
The original string is : G4g is No. 1 for Geeks 7
String after integer retention : 417
Method #2 : Using regex()The solution of problem can also be found by using regex. In this, we formulate appropriate regex to filter only numbers from string.
# Python3 code to demonstrate working of # Retain Numbers in String# Using regex()import re # initializing stringtest_str = 'G4g is No. 1 for Geeks 7' # printing original stringprint("The original string is : " + str(test_str)) # Retain Numbers in String# Using regex()res = re.sub(r'[^\d]+', '', test_str) # printing result print("String after integer retention : " + str(res))
The original string is : G4g is No. 1 for Geeks 7
String after integer retention : 417
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n03 Jul, 2020"
},
{
"code": null,
"e": 352,
"s": 28,
"text": "Sometimes, while working with Python Strings, we can have a problem in which we need to perform the removal of all the characters other than integers. This kind of problem can have application in many data domains such as Machine Learning and web development. Let’s discuss certain ways in which this task can be performed."
},
{
"code": null,
"e": 397,
"s": 352,
"text": "Input : test_str = ‘G4g is No. 1’Output : 41"
},
{
"code": null,
"e": 441,
"s": 397,
"text": "Input : test_str = ‘Gfg is No. 1’Output : 1"
},
{
"code": null,
"e": 734,
"s": 441,
"text": "Method #1 : Using list comprehension + join() + isdigit()The combination of above functions can be used to solve this problem. In this, we perform the task of extracting integers using isdigit(), list comprehension is used for iteration and join() is used to perform join of numbers filtered."
},
{
"code": "# Python3 code to demonstrate working of # Retain Numbers in String# Using list comprehension + join() + isdigit() # initializing stringtest_str = 'G4g is No. 1 for Geeks 7' # printing original stringprint(\"The original string is : \" + str(test_str)) # Retain Numbers in String# Using list comprehension + join() + isdigit()res = \"\".join([ele for ele in test_str if ele.isdigit()]) # printing result print(\"String after integer retention : \" + str(res)) ",
"e": 1193,
"s": 734,
"text": null
},
{
"code": null,
"e": 1281,
"s": 1193,
"text": "The original string is : G4g is No. 1 for Geeks 7\nString after integer retention : 417\n"
},
{
"code": null,
"e": 1442,
"s": 1283,
"text": "Method #2 : Using regex()The solution of problem can also be found by using regex. In this, we formulate appropriate regex to filter only numbers from string."
},
{
"code": "# Python3 code to demonstrate working of # Retain Numbers in String# Using regex()import re # initializing stringtest_str = 'G4g is No. 1 for Geeks 7' # printing original stringprint(\"The original string is : \" + str(test_str)) # Retain Numbers in String# Using regex()res = re.sub(r'[^\\d]+', '', test_str) # printing result print(\"String after integer retention : \" + str(res)) ",
"e": 1827,
"s": 1442,
"text": null
},
{
"code": null,
"e": 1915,
"s": 1827,
"text": "The original string is : G4g is No. 1 for Geeks 7\nString after integer retention : 417\n"
},
{
"code": null,
"e": 1938,
"s": 1915,
"text": "Python string-programs"
},
{
"code": null,
"e": 1945,
"s": 1938,
"text": "Python"
},
{
"code": null,
"e": 1961,
"s": 1945,
"text": "Python Programs"
}
]
|
Java Sound API | 17 May, 2022
JavaSound is a collection of classes and interfaces for effecting and controlling sound media in java. It consists of two packages.
javax.sound.sampled: This package provides an interface for the capture, mixing digital audio.
javax.sound.midi: This package provides an interface for MIDI (Musical Instrument Digital Interface) synthesis, sequencing, and event transport.
What is MIDI?
We will be exploring MIDI more about MIDI here. So MIDI is like a sheet of notes that the midi capable instrument can play, think of it as an HTML document and midi capable instrument as a web browser. MIDI file has information about how a song should be played, just like an instruction sheet for a guitar player. MIDI devices know how to read a midi file and generate sound.
In order to make actual sound we need four things for this:
Instrument (that plays the music) SEQUENCERSong (the music to be played) SEQUENCETrack (which holds the notes)Notes (the actual music information) MIDI EVENTS
Instrument (that plays the music) SEQUENCER
Song (the music to be played) SEQUENCE
Track (which holds the notes)
Notes (the actual music information) MIDI EVENTS
JavaSound API got all of these covered.
SEQUENCER ⇒ SEQUENCE ⇒ TRACK ⇒ MIDI EVENTS
Procedure:
Step 1: Get a Sequencer and open it
// Make a sequencer named player and open it
Sequencer player = MIDISystem.getSequencer();
player.open();
Step 2: Make a new Sequence
// Make a new sequence
Sequence seq = new Sequence(Sequence.PPQ, 4);
Step 3: Get a new Track from the Sequence
// Creating new Track
Track t = seq.createTrack();
Step 4: Fill the Track with MIDIEVENTS
// Filling the Track with MidiEvent and
// giving the Sequence to the Sequencer
t.add(myMidiEvent1);
player.setSequence(seq);
// Play it using start
player.start();
Implementation:
Example
Java
// Java Program to Illustrate JAva Sound API // Importing classes from// javax.sound packageimport javax.sound.midi.*; // Main class// MiniMusicApppublic class GFG { // Method 1 // Main driver method public static void main(String[] args) { // Creating object of class inside main() GFG minimusic = new GFG(); // Calling method 2 to play the sound minimusic.play(); // Display message on the console for // successful execution of program System.out.print( "Successfully compiled and executed"); } // Method 2 // To play the sound public void play() { // Try block to check for exceptions try { // Getting a sequencer and open it Sequencer player = MidiSystem.getSequencer(); player.open(); // Making 1a new Sequence Sequence seq = new Sequence(Sequence.PPQ, 4); // Creating a new track Track track = seq.createTrack(); // Making a Message ShortMessage a = new ShortMessage(); // Put the Instruction in the Message a.setMessage(144, 1, 44, 100); // Make a new MidiEvent MidiEvent noteOn = new MidiEvent(a, 1); // Add MidiEvent to the Track track.add(noteOn); ShortMessage b = new ShortMessage(); b.setMessage(128, 1, 44, 100); MidiEvent noteOff = new MidiEvent(b, 16); track.add(noteOff); // Giving sequence to Sequencer player.setSequence(seq); // Start the Sequencer using start() method player.start(); } // Catch block to handle exceptions catch (Exception ex) { // Display the exception on console // along with line number ex.printStackTrace(); } }}
Output:
Successfully compiled and executed
saurabh1990aror
sweetyty
anikaseth98
adnanirshad158
sagartomar9927
Blogathon-2021
Java 8
Blogathon
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Import JSON Data into SQL Server?
SQL Query to Convert Datetime to Date
Python program to convert XML to Dictionary
Scrape LinkedIn Using Selenium And Beautiful Soup in Python
Modes of DMA Transfer
Arrays in Java
Arrays.sort() in Java with examples
Split() String method in Java with examples
Reverse a string in Java
Object Oriented Programming (OOPs) Concept in Java | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 May, 2022"
},
{
"code": null,
"e": 160,
"s": 28,
"text": "JavaSound is a collection of classes and interfaces for effecting and controlling sound media in java. It consists of two packages."
},
{
"code": null,
"e": 255,
"s": 160,
"text": "javax.sound.sampled: This package provides an interface for the capture, mixing digital audio."
},
{
"code": null,
"e": 400,
"s": 255,
"text": "javax.sound.midi: This package provides an interface for MIDI (Musical Instrument Digital Interface) synthesis, sequencing, and event transport."
},
{
"code": null,
"e": 414,
"s": 400,
"text": "What is MIDI?"
},
{
"code": null,
"e": 791,
"s": 414,
"text": "We will be exploring MIDI more about MIDI here. So MIDI is like a sheet of notes that the midi capable instrument can play, think of it as an HTML document and midi capable instrument as a web browser. MIDI file has information about how a song should be played, just like an instruction sheet for a guitar player. MIDI devices know how to read a midi file and generate sound."
},
{
"code": null,
"e": 851,
"s": 791,
"text": "In order to make actual sound we need four things for this:"
},
{
"code": null,
"e": 1012,
"s": 851,
"text": "Instrument (that plays the music) SEQUENCERSong (the music to be played) SEQUENCETrack (which holds the notes)Notes (the actual music information) MIDI EVENTS"
},
{
"code": null,
"e": 1056,
"s": 1012,
"text": "Instrument (that plays the music) SEQUENCER"
},
{
"code": null,
"e": 1096,
"s": 1056,
"text": "Song (the music to be played) SEQUENCE"
},
{
"code": null,
"e": 1126,
"s": 1096,
"text": "Track (which holds the notes)"
},
{
"code": null,
"e": 1176,
"s": 1126,
"text": "Notes (the actual music information) MIDI EVENTS"
},
{
"code": null,
"e": 1216,
"s": 1176,
"text": "JavaSound API got all of these covered."
},
{
"code": null,
"e": 1261,
"s": 1216,
"text": "SEQUENCER ⇒ SEQUENCE ⇒ TRACK ⇒ MIDI EVENTS"
},
{
"code": null,
"e": 1272,
"s": 1261,
"text": "Procedure:"
},
{
"code": null,
"e": 1308,
"s": 1272,
"text": "Step 1: Get a Sequencer and open it"
},
{
"code": null,
"e": 1414,
"s": 1308,
"text": "// Make a sequencer named player and open it\nSequencer player = MIDISystem.getSequencer();\nplayer.open();"
},
{
"code": null,
"e": 1442,
"s": 1414,
"text": "Step 2: Make a new Sequence"
},
{
"code": null,
"e": 1512,
"s": 1442,
"text": "// Make a new sequence \nSequence seq = new Sequence(Sequence.PPQ, 4);"
},
{
"code": null,
"e": 1554,
"s": 1512,
"text": "Step 3: Get a new Track from the Sequence"
},
{
"code": null,
"e": 1605,
"s": 1554,
"text": "// Creating new Track\nTrack t = seq.createTrack();"
},
{
"code": null,
"e": 1646,
"s": 1605,
"text": "Step 4: Fill the Track with MIDIEVENTS "
},
{
"code": null,
"e": 1813,
"s": 1646,
"text": "// Filling the Track with MidiEvent and\n// giving the Sequence to the Sequencer\n\nt.add(myMidiEvent1);\nplayer.setSequence(seq);\n\n// Play it using start\nplayer.start();"
},
{
"code": null,
"e": 1829,
"s": 1813,
"text": "Implementation:"
},
{
"code": null,
"e": 1837,
"s": 1829,
"text": "Example"
},
{
"code": null,
"e": 1842,
"s": 1837,
"text": "Java"
},
{
"code": "// Java Program to Illustrate JAva Sound API // Importing classes from// javax.sound packageimport javax.sound.midi.*; // Main class// MiniMusicApppublic class GFG { // Method 1 // Main driver method public static void main(String[] args) { // Creating object of class inside main() GFG minimusic = new GFG(); // Calling method 2 to play the sound minimusic.play(); // Display message on the console for // successful execution of program System.out.print( \"Successfully compiled and executed\"); } // Method 2 // To play the sound public void play() { // Try block to check for exceptions try { // Getting a sequencer and open it Sequencer player = MidiSystem.getSequencer(); player.open(); // Making 1a new Sequence Sequence seq = new Sequence(Sequence.PPQ, 4); // Creating a new track Track track = seq.createTrack(); // Making a Message ShortMessage a = new ShortMessage(); // Put the Instruction in the Message a.setMessage(144, 1, 44, 100); // Make a new MidiEvent MidiEvent noteOn = new MidiEvent(a, 1); // Add MidiEvent to the Track track.add(noteOn); ShortMessage b = new ShortMessage(); b.setMessage(128, 1, 44, 100); MidiEvent noteOff = new MidiEvent(b, 16); track.add(noteOff); // Giving sequence to Sequencer player.setSequence(seq); // Start the Sequencer using start() method player.start(); } // Catch block to handle exceptions catch (Exception ex) { // Display the exception on console // along with line number ex.printStackTrace(); } }}",
"e": 3731,
"s": 1842,
"text": null
},
{
"code": null,
"e": 3739,
"s": 3731,
"text": "Output:"
},
{
"code": null,
"e": 3774,
"s": 3739,
"text": "Successfully compiled and executed"
},
{
"code": null,
"e": 3790,
"s": 3774,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 3799,
"s": 3790,
"text": "sweetyty"
},
{
"code": null,
"e": 3811,
"s": 3799,
"text": "anikaseth98"
},
{
"code": null,
"e": 3826,
"s": 3811,
"text": "adnanirshad158"
},
{
"code": null,
"e": 3841,
"s": 3826,
"text": "sagartomar9927"
},
{
"code": null,
"e": 3856,
"s": 3841,
"text": "Blogathon-2021"
},
{
"code": null,
"e": 3863,
"s": 3856,
"text": "Java 8"
},
{
"code": null,
"e": 3873,
"s": 3863,
"text": "Blogathon"
},
{
"code": null,
"e": 3878,
"s": 3873,
"text": "Java"
},
{
"code": null,
"e": 3883,
"s": 3878,
"text": "Java"
},
{
"code": null,
"e": 3981,
"s": 3883,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4022,
"s": 3981,
"text": "How to Import JSON Data into SQL Server?"
},
{
"code": null,
"e": 4060,
"s": 4022,
"text": "SQL Query to Convert Datetime to Date"
},
{
"code": null,
"e": 4104,
"s": 4060,
"text": "Python program to convert XML to Dictionary"
},
{
"code": null,
"e": 4164,
"s": 4104,
"text": "Scrape LinkedIn Using Selenium And Beautiful Soup in Python"
},
{
"code": null,
"e": 4186,
"s": 4164,
"text": "Modes of DMA Transfer"
},
{
"code": null,
"e": 4201,
"s": 4186,
"text": "Arrays in Java"
},
{
"code": null,
"e": 4237,
"s": 4201,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 4281,
"s": 4237,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 4306,
"s": 4281,
"text": "Reverse a string in Java"
}
]
|
Program to remotely Power On a PC over the internet using the Wake-on-LAN protocol. | 18 Oct, 2021
Wake-on-LAN (WoL) is an Ethernet or token ring computer networking standard that allows a computer to be turned on or awakened by a network message.
The message is usually sent to the target computer by a program executed on a device connected to the same local area network, such as a smartphone.
It is also possible to initiate the message from another network by using subnet-directed broadcasts or a WOL gateway service.
Equivalent terms include wake on WAN, remote wake-up, power on by LAN, power up by LAN, resume by LAN, resume on LAN and wake up on LAN.
Principle of operation
Wake-on-LAN (“WOL”) is implemented using a specially designed packet called a magic packet, which is sent to all computers in a network, among them the computer to be awakened.
The magic packet contains the MAC address of the destination computer, an identifying number built into each network interface card (“NIC”) or other ethernet devices in a computer, that enables it to be uniquely recognized and addressed on a network.
Powered-down or turned-off computers capable of Wake-on-LAN will contain network devices able to “listen” to incoming packets in low-power mode while the system is powered down.
If a magic packet is received that is directed to the device’s MAC address, the NIC signals the computer’s power supply or motherboard to initiate system wake-up, much in the same way as pressing the power button would do.
The magic packet is sent on the data link layer (layer 2 in the OSI model) and when sent, is broadcast to all attached devices on a given network, using the network broadcast address; the IP-address (layer 3 in the OSI model) is not used.
In order for Wake-on-LAN to work, parts of the network interface need to stay on. This consumes a small amount of standby power, much less than normal operating power. Disabling wake-on-LAN when not needed can therefore vary slightly reduce power consumption on computers that are switched off but still plugged into a power socket.
Magic Packet Structure The magic packet is a broadcast frame containing anywhere within its payload 6 bytes of all 255 (FF FF FF FF FF FF in hexadecimal), followed by sixteen repetitions of the target computer’s 48-bit MAC address, for a total of 102 bytes. Since the magic packet is only scanned for the string above, and not actually parsed by a full protocol stack, it may be sent as any network- and transport-layer protocol, although it is typically sent as a UDP datagram to port 0, 7, or 9, or directly over Ethernet as EtherType 0x0842.
A standard magic packet has the following basic limitations:
Requires destination computer MAC address (also may require a SecureOn password).Do not provide a delivery confirmation.May not work outside of the local network.Requires hardware support of Wake-On-LAN on the destination computer.Most 802.11 wireless interfaces do not maintain a link in low power states and cannot receive a magic packet.
Requires destination computer MAC address (also may require a SecureOn password).
Do not provide a delivery confirmation.
May not work outside of the local network.
Requires hardware support of Wake-On-LAN on the destination computer.
Most 802.11 wireless interfaces do not maintain a link in low power states and cannot receive a magic packet.
The Wake-on-LAN implementation is designed to be very simple and to be quickly processed by the circuitry present on the network interface card with minimal power requirement. Because Wake-on-LAN operates below the IP protocol layer the MAC address is required and makes IP addresses and DNS names meaningless.
C++
// C program to remotely Power On a PC over the// internet using the Wake-on-LAN protocol.#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <sys/socket.h>#include <netinet/in.h>#include <arpa/inet.h>#include <string.h>#include <sys/types.h> int main(){ int i; unsigned char toSend[102],mac[6]; struct sockaddr_in udpClient, udpServer; int broadcast = 1 ; // UDP Socket creation int udpSocket = socket(AF_INET, SOCK_DGRAM, 0); // Manipulating the Socket if (setsockopt(udpSocket, SOL_SOCKET, SO_BROADCAST, &broadcast, sizeof broadcast) == -1) { perror("setsockopt (SO_BROADCAST)"); exit(EXIT_FAILURE); } udpClient.sin_family = AF_INET; udpClient.sin_addr.s_addr = INADDR_ANY; udpClient.sin_port = 0; //Binding the socket bind(udpSocket, (struct sockaddr*)&udpClient, sizeof(udpClient)); for (i=0; i<6; i++) toSend[i] = 0xFF; // Let the MAC Address be ab:cd:ef:gh:ij:kl mac[0] = 0xab; // 1st octet of the MAC Address mac[1] = 0xcd; // 2nd octet of the MAC Address mac[2] = 0xef; // 3rd octet of the MAC Address mac[3] = 0xgh; // 4th octet of the MAC Address mac[4] = 0xij; // 5th octet of the MAC Address mac[5] = 0xkl; // 6th octet of the MAC Address for (i=1; i<=16; i++) memcpy(&toSend[i*6], &mac, 6*sizeof(unsigned char)); udpServer.sin_family = AF_INET; // Broadcast address udpServer.sin_addr.s_addr = inet_addr("10.89.255.255"); udpServer.sin_port = htons(9); sendto(udpSocket, &toSend, sizeof(unsigned char) * 102, 0, (struct sockaddr*)&udpServer, sizeof(udpServer)); return 0;}
Output:
This program will power on the switched-off PC
whose MAC Address is used in this program (the
PC and the Host computer must be connected over
LAN).
This article is contributed by Kishlay Verma. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Reference : https://en.wikipedia.org/wiki/Wake-on-LANPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
rohanpa9876632
sagartomar9927
vaibhavsinghtanwar3
Data Link Layer
system-programming
Computer Networks
Project
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GSM in Wireless Communication
Socket Programming in Python
Differences between IPv4 and IPv6
Secure Socket Layer (SSL)
Wireless Application Protocol
SDE SHEET - A Complete Guide for SDE Preparation
Implementing Web Scraping in Python with BeautifulSoup
Working with zip files in Python
XML parsing in Python
Python | Simple GUI calculator using Tkinter | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n18 Oct, 2021"
},
{
"code": null,
"e": 202,
"s": 52,
"text": "Wake-on-LAN (WoL) is an Ethernet or token ring computer networking standard that allows a computer to be turned on or awakened by a network message. "
},
{
"code": null,
"e": 351,
"s": 202,
"text": "The message is usually sent to the target computer by a program executed on a device connected to the same local area network, such as a smartphone."
},
{
"code": null,
"e": 478,
"s": 351,
"text": "It is also possible to initiate the message from another network by using subnet-directed broadcasts or a WOL gateway service."
},
{
"code": null,
"e": 615,
"s": 478,
"text": "Equivalent terms include wake on WAN, remote wake-up, power on by LAN, power up by LAN, resume by LAN, resume on LAN and wake up on LAN."
},
{
"code": null,
"e": 639,
"s": 615,
"text": "Principle of operation "
},
{
"code": null,
"e": 816,
"s": 639,
"text": "Wake-on-LAN (“WOL”) is implemented using a specially designed packet called a magic packet, which is sent to all computers in a network, among them the computer to be awakened."
},
{
"code": null,
"e": 1067,
"s": 816,
"text": "The magic packet contains the MAC address of the destination computer, an identifying number built into each network interface card (“NIC”) or other ethernet devices in a computer, that enables it to be uniquely recognized and addressed on a network."
},
{
"code": null,
"e": 1245,
"s": 1067,
"text": "Powered-down or turned-off computers capable of Wake-on-LAN will contain network devices able to “listen” to incoming packets in low-power mode while the system is powered down."
},
{
"code": null,
"e": 1468,
"s": 1245,
"text": "If a magic packet is received that is directed to the device’s MAC address, the NIC signals the computer’s power supply or motherboard to initiate system wake-up, much in the same way as pressing the power button would do."
},
{
"code": null,
"e": 1707,
"s": 1468,
"text": "The magic packet is sent on the data link layer (layer 2 in the OSI model) and when sent, is broadcast to all attached devices on a given network, using the network broadcast address; the IP-address (layer 3 in the OSI model) is not used."
},
{
"code": null,
"e": 2040,
"s": 1707,
"text": "In order for Wake-on-LAN to work, parts of the network interface need to stay on. This consumes a small amount of standby power, much less than normal operating power. Disabling wake-on-LAN when not needed can therefore vary slightly reduce power consumption on computers that are switched off but still plugged into a power socket."
},
{
"code": null,
"e": 2585,
"s": 2040,
"text": "Magic Packet Structure The magic packet is a broadcast frame containing anywhere within its payload 6 bytes of all 255 (FF FF FF FF FF FF in hexadecimal), followed by sixteen repetitions of the target computer’s 48-bit MAC address, for a total of 102 bytes. Since the magic packet is only scanned for the string above, and not actually parsed by a full protocol stack, it may be sent as any network- and transport-layer protocol, although it is typically sent as a UDP datagram to port 0, 7, or 9, or directly over Ethernet as EtherType 0x0842."
},
{
"code": null,
"e": 2648,
"s": 2585,
"text": "A standard magic packet has the following basic limitations: "
},
{
"code": null,
"e": 2989,
"s": 2648,
"text": "Requires destination computer MAC address (also may require a SecureOn password).Do not provide a delivery confirmation.May not work outside of the local network.Requires hardware support of Wake-On-LAN on the destination computer.Most 802.11 wireless interfaces do not maintain a link in low power states and cannot receive a magic packet."
},
{
"code": null,
"e": 3071,
"s": 2989,
"text": "Requires destination computer MAC address (also may require a SecureOn password)."
},
{
"code": null,
"e": 3111,
"s": 3071,
"text": "Do not provide a delivery confirmation."
},
{
"code": null,
"e": 3154,
"s": 3111,
"text": "May not work outside of the local network."
},
{
"code": null,
"e": 3224,
"s": 3154,
"text": "Requires hardware support of Wake-On-LAN on the destination computer."
},
{
"code": null,
"e": 3334,
"s": 3224,
"text": "Most 802.11 wireless interfaces do not maintain a link in low power states and cannot receive a magic packet."
},
{
"code": null,
"e": 3645,
"s": 3334,
"text": "The Wake-on-LAN implementation is designed to be very simple and to be quickly processed by the circuitry present on the network interface card with minimal power requirement. Because Wake-on-LAN operates below the IP protocol layer the MAC address is required and makes IP addresses and DNS names meaningless."
},
{
"code": null,
"e": 3649,
"s": 3645,
"text": "C++"
},
{
"code": "// C program to remotely Power On a PC over the// internet using the Wake-on-LAN protocol.#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <sys/socket.h>#include <netinet/in.h>#include <arpa/inet.h>#include <string.h>#include <sys/types.h> int main(){ int i; unsigned char toSend[102],mac[6]; struct sockaddr_in udpClient, udpServer; int broadcast = 1 ; // UDP Socket creation int udpSocket = socket(AF_INET, SOCK_DGRAM, 0); // Manipulating the Socket if (setsockopt(udpSocket, SOL_SOCKET, SO_BROADCAST, &broadcast, sizeof broadcast) == -1) { perror(\"setsockopt (SO_BROADCAST)\"); exit(EXIT_FAILURE); } udpClient.sin_family = AF_INET; udpClient.sin_addr.s_addr = INADDR_ANY; udpClient.sin_port = 0; //Binding the socket bind(udpSocket, (struct sockaddr*)&udpClient, sizeof(udpClient)); for (i=0; i<6; i++) toSend[i] = 0xFF; // Let the MAC Address be ab:cd:ef:gh:ij:kl mac[0] = 0xab; // 1st octet of the MAC Address mac[1] = 0xcd; // 2nd octet of the MAC Address mac[2] = 0xef; // 3rd octet of the MAC Address mac[3] = 0xgh; // 4th octet of the MAC Address mac[4] = 0xij; // 5th octet of the MAC Address mac[5] = 0xkl; // 6th octet of the MAC Address for (i=1; i<=16; i++) memcpy(&toSend[i*6], &mac, 6*sizeof(unsigned char)); udpServer.sin_family = AF_INET; // Broadcast address udpServer.sin_addr.s_addr = inet_addr(\"10.89.255.255\"); udpServer.sin_port = htons(9); sendto(udpSocket, &toSend, sizeof(unsigned char) * 102, 0, (struct sockaddr*)&udpServer, sizeof(udpServer)); return 0;}",
"e": 5311,
"s": 3649,
"text": null
},
{
"code": null,
"e": 5320,
"s": 5311,
"text": "Output: "
},
{
"code": null,
"e": 5470,
"s": 5320,
"text": "This program will power on the switched-off PC\nwhose MAC Address is used in this program (the \nPC and the Host computer must be connected over\nLAN). "
},
{
"code": null,
"e": 5767,
"s": 5470,
"text": "This article is contributed by Kishlay Verma. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 5946,
"s": 5767,
"text": "Reference : https://en.wikipedia.org/wiki/Wake-on-LANPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 5961,
"s": 5946,
"text": "rohanpa9876632"
},
{
"code": null,
"e": 5976,
"s": 5961,
"text": "sagartomar9927"
},
{
"code": null,
"e": 5996,
"s": 5976,
"text": "vaibhavsinghtanwar3"
},
{
"code": null,
"e": 6012,
"s": 5996,
"text": "Data Link Layer"
},
{
"code": null,
"e": 6031,
"s": 6012,
"text": "system-programming"
},
{
"code": null,
"e": 6049,
"s": 6031,
"text": "Computer Networks"
},
{
"code": null,
"e": 6057,
"s": 6049,
"text": "Project"
},
{
"code": null,
"e": 6075,
"s": 6057,
"text": "Computer Networks"
},
{
"code": null,
"e": 6173,
"s": 6075,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6203,
"s": 6173,
"text": "GSM in Wireless Communication"
},
{
"code": null,
"e": 6232,
"s": 6203,
"text": "Socket Programming in Python"
},
{
"code": null,
"e": 6266,
"s": 6232,
"text": "Differences between IPv4 and IPv6"
},
{
"code": null,
"e": 6292,
"s": 6266,
"text": "Secure Socket Layer (SSL)"
},
{
"code": null,
"e": 6322,
"s": 6292,
"text": "Wireless Application Protocol"
},
{
"code": null,
"e": 6371,
"s": 6322,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 6426,
"s": 6371,
"text": "Implementing Web Scraping in Python with BeautifulSoup"
},
{
"code": null,
"e": 6459,
"s": 6426,
"text": "Working with zip files in Python"
},
{
"code": null,
"e": 6481,
"s": 6459,
"text": "XML parsing in Python"
}
]
|
Carrier Sense Multiple Access (CSMA) | 16 Jun, 2022
Prerequisite – Multiple Access Protocols This method was developed to decrease the chances of collisions when two or more stations start sending their signals over the data link layer. Carrier Sense multiple access requires that each station first check the state of the medium before sending.
Vulnerable Time –
Vulnerable time = Propagation time (Tp)
The persistence methods can be applied to help the station take action when the channel is busy/idle.
In this method, a station monitors the medium after it sends a frame to see if the transmission was successful. If successful, the station is finished, if not, the frame is sent again.
In the diagram, A starts sending the first bit of its frame at t1 and since C sees the channel idle at t2, starts sending its frame at t2. C detects A’s frame at t3 and aborts transmission. A detects C’s frame at t4 and aborts its transmission. Transmission time for C’s frame is, therefore, and for A’s frame is
So, the frame transmission time (Tfr) should be at least twice the maximum propagation time (Tp). This can be deduced when the two stations involved in a collision are a maximum distance apart.
Process – The entire process of collision detection can be explained as follows:
Throughput and Efficiency – The throughput of CSMA/CD is much greater than pure or slotted ALOHA.
For the 1-persistent method, throughput is 50% when G=1.
For the non-persistent method, throughput can go up to 90%.
The basic idea behind CSMA/CA is that the station should be able to receive while transmitting to detect a collision from different stations. In wired networks, if a collision has occurred then the energy of the received signal almost doubles, and the station can sense the possibility of collision. In the case of wireless networks, most of the energy is used for transmission, and the energy of the received signal increases by only 5-10% if a collision occurs. It can’t be used by the station to sense collision. Therefore CSMA/CA has been specially designed for wireless networks.
These are three types of strategies:
InterFrame Space (IFS) – When a station finds the channel busy it senses the channel again, when the station finds a channel to be idle it waits for a period of time called IFS time. IFS can also be used to define the priority of a station or a frame. Higher the IFS lower is the priority.Contention Window – It is the amount of time divided into slots. A station that is ready to send frames chooses a random number of slots as wait time.Acknowledgements – The positive acknowledgements and time-out timer can help guarantee a successful transmission of the frame.
InterFrame Space (IFS) – When a station finds the channel busy it senses the channel again, when the station finds a channel to be idle it waits for a period of time called IFS time. IFS can also be used to define the priority of a station or a frame. Higher the IFS lower is the priority.
Contention Window – It is the amount of time divided into slots. A station that is ready to send frames chooses a random number of slots as wait time.
Acknowledgements – The positive acknowledgements and time-out timer can help guarantee a successful transmission of the frame.
Process – The entire process of collision avoidance can be explained as follows:
AjayMakhecha
abhinav__singh
vivekpal23123451254
vaibhavsinghtanwar
mawesh1999
krishna_97
Computer Networks
GATE CS
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GSM in Wireless Communication
Socket Programming in Python
Differences between IPv4 and IPv6
Secure Socket Layer (SSL)
Wireless Application Protocol
ACID Properties in DBMS
Types of Operating Systems
Normal Forms in DBMS
Page Replacement Algorithms in Operating Systems
Introduction of Operating System - Set 1 | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n16 Jun, 2022"
},
{
"code": null,
"e": 349,
"s": 54,
"text": "Prerequisite – Multiple Access Protocols This method was developed to decrease the chances of collisions when two or more stations start sending their signals over the data link layer. Carrier Sense multiple access requires that each station first check the state of the medium before sending. "
},
{
"code": null,
"e": 368,
"s": 349,
"text": "Vulnerable Time – "
},
{
"code": null,
"e": 409,
"s": 368,
"text": " Vulnerable time = Propagation time (Tp)"
},
{
"code": null,
"e": 513,
"s": 409,
"text": "The persistence methods can be applied to help the station take action when the channel is busy/idle. "
},
{
"code": null,
"e": 699,
"s": 513,
"text": "In this method, a station monitors the medium after it sends a frame to see if the transmission was successful. If successful, the station is finished, if not, the frame is sent again. "
},
{
"code": null,
"e": 1014,
"s": 699,
"text": "In the diagram, A starts sending the first bit of its frame at t1 and since C sees the channel idle at t2, starts sending its frame at t2. C detects A’s frame at t3 and aborts transmission. A detects C’s frame at t4 and aborts its transmission. Transmission time for C’s frame is, therefore, and for A’s frame is "
},
{
"code": null,
"e": 1209,
"s": 1014,
"text": "So, the frame transmission time (Tfr) should be at least twice the maximum propagation time (Tp). This can be deduced when the two stations involved in a collision are a maximum distance apart. "
},
{
"code": null,
"e": 1291,
"s": 1209,
"text": "Process – The entire process of collision detection can be explained as follows: "
},
{
"code": null,
"e": 1391,
"s": 1291,
"text": "Throughput and Efficiency – The throughput of CSMA/CD is much greater than pure or slotted ALOHA. "
},
{
"code": null,
"e": 1448,
"s": 1391,
"text": "For the 1-persistent method, throughput is 50% when G=1."
},
{
"code": null,
"e": 1508,
"s": 1448,
"text": "For the non-persistent method, throughput can go up to 90%."
},
{
"code": null,
"e": 2094,
"s": 1508,
"text": "The basic idea behind CSMA/CA is that the station should be able to receive while transmitting to detect a collision from different stations. In wired networks, if a collision has occurred then the energy of the received signal almost doubles, and the station can sense the possibility of collision. In the case of wireless networks, most of the energy is used for transmission, and the energy of the received signal increases by only 5-10% if a collision occurs. It can’t be used by the station to sense collision. Therefore CSMA/CA has been specially designed for wireless networks. "
},
{
"code": null,
"e": 2132,
"s": 2094,
"text": "These are three types of strategies: "
},
{
"code": null,
"e": 2698,
"s": 2132,
"text": "InterFrame Space (IFS) – When a station finds the channel busy it senses the channel again, when the station finds a channel to be idle it waits for a period of time called IFS time. IFS can also be used to define the priority of a station or a frame. Higher the IFS lower is the priority.Contention Window – It is the amount of time divided into slots. A station that is ready to send frames chooses a random number of slots as wait time.Acknowledgements – The positive acknowledgements and time-out timer can help guarantee a successful transmission of the frame."
},
{
"code": null,
"e": 2988,
"s": 2698,
"text": "InterFrame Space (IFS) – When a station finds the channel busy it senses the channel again, when the station finds a channel to be idle it waits for a period of time called IFS time. IFS can also be used to define the priority of a station or a frame. Higher the IFS lower is the priority."
},
{
"code": null,
"e": 3139,
"s": 2988,
"text": "Contention Window – It is the amount of time divided into slots. A station that is ready to send frames chooses a random number of slots as wait time."
},
{
"code": null,
"e": 3266,
"s": 3139,
"text": "Acknowledgements – The positive acknowledgements and time-out timer can help guarantee a successful transmission of the frame."
},
{
"code": null,
"e": 3349,
"s": 3266,
"text": "Process – The entire process of collision avoidance can be explained as follows: "
},
{
"code": null,
"e": 3364,
"s": 3351,
"text": "AjayMakhecha"
},
{
"code": null,
"e": 3379,
"s": 3364,
"text": "abhinav__singh"
},
{
"code": null,
"e": 3399,
"s": 3379,
"text": "vivekpal23123451254"
},
{
"code": null,
"e": 3418,
"s": 3399,
"text": "vaibhavsinghtanwar"
},
{
"code": null,
"e": 3429,
"s": 3418,
"text": "mawesh1999"
},
{
"code": null,
"e": 3440,
"s": 3429,
"text": "krishna_97"
},
{
"code": null,
"e": 3458,
"s": 3440,
"text": "Computer Networks"
},
{
"code": null,
"e": 3466,
"s": 3458,
"text": "GATE CS"
},
{
"code": null,
"e": 3484,
"s": 3466,
"text": "Computer Networks"
},
{
"code": null,
"e": 3582,
"s": 3484,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3612,
"s": 3582,
"text": "GSM in Wireless Communication"
},
{
"code": null,
"e": 3641,
"s": 3612,
"text": "Socket Programming in Python"
},
{
"code": null,
"e": 3675,
"s": 3641,
"text": "Differences between IPv4 and IPv6"
},
{
"code": null,
"e": 3701,
"s": 3675,
"text": "Secure Socket Layer (SSL)"
},
{
"code": null,
"e": 3731,
"s": 3701,
"text": "Wireless Application Protocol"
},
{
"code": null,
"e": 3755,
"s": 3731,
"text": "ACID Properties in DBMS"
},
{
"code": null,
"e": 3782,
"s": 3755,
"text": "Types of Operating Systems"
},
{
"code": null,
"e": 3803,
"s": 3782,
"text": "Normal Forms in DBMS"
},
{
"code": null,
"e": 3852,
"s": 3803,
"text": "Page Replacement Algorithms in Operating Systems"
}
]
|
GATE | GATE-CS-2005 | Question 86 | 28 Jun, 2021
Consider the following expression grammar. The semantic rules for expression calculation are stated next to each grammar production.
E → number E.val = number. val
| E '+' E E(1).val = E(2).val + E(3).val
| E '×' E E(1).val = E(2).val × E(3).val
Assume the conflicts in Part (a) of this question are resolved and an LALR(1) parser is generated for parsing arithmetic expressions as per the given grammar. Consider an expression 3 × 2 + 1. What precedence and associativity properties does the generated parser realize?(A) Equal precedence and left associativity; expression is evaluated to 7(B) Equal precedence and right associativity; expression is evaluated to 9(C) Precedence of ‘×’ is higher than that of ‘+’, and both operators are left associative; expression is evaluated to 7(D) Precedence of ‘+’ is higher than that of ‘×’, and both operators are left associative; expression is evaluated to 9Answer: (B)Explanation: Answer is B as the productions belong to the same non-terminal and since YACC resolves by shift over reduce, the associativity will be right associative.Quiz of this Question
GATE-CS-2005
GATE-GATE-CS-2005
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 162,
"s": 28,
"text": "Consider the following expression grammar. The semantic rules for expression calculation are stated next to each grammar production."
},
{
"code": null,
"e": 299,
"s": 162,
"text": " E → number E.val = number. val\n | E '+' E E(1).val = E(2).val + E(3).val\n | E '×' E E(1).val = E(2).val × E(3).val "
},
{
"code": null,
"e": 1157,
"s": 299,
"text": "Assume the conflicts in Part (a) of this question are resolved and an LALR(1) parser is generated for parsing arithmetic expressions as per the given grammar. Consider an expression 3 × 2 + 1. What precedence and associativity properties does the generated parser realize?(A) Equal precedence and left associativity; expression is evaluated to 7(B) Equal precedence and right associativity; expression is evaluated to 9(C) Precedence of ‘×’ is higher than that of ‘+’, and both operators are left associative; expression is evaluated to 7(D) Precedence of ‘+’ is higher than that of ‘×’, and both operators are left associative; expression is evaluated to 9Answer: (B)Explanation: Answer is B as the productions belong to the same non-terminal and since YACC resolves by shift over reduce, the associativity will be right associative.Quiz of this Question"
},
{
"code": null,
"e": 1170,
"s": 1157,
"text": "GATE-CS-2005"
},
{
"code": null,
"e": 1188,
"s": 1170,
"text": "GATE-GATE-CS-2005"
},
{
"code": null,
"e": 1193,
"s": 1188,
"text": "GATE"
}
]
|
Spring Autowiring by Constructor | This mode is very similar to byType, but it applies to constructor arguments. Spring container looks at the beans on which autowire attribute is set constructor in the XML configuration file. It then tries to match and wire its constructor's argument with exactly one of the beans name in the configuration file. If matches are found, it will inject those beans. Otherwise, bean(s) will not be wired.
For example, if a bean definition is set to autowire by constructor in configuration file, and it has a constructor with one of the arguments of SpellChecker type, Spring looks for a bean definition named SpellChecker, and uses it to set the constructor's argument. Still you can wire remaining arguments using <constructor-arg> tags. The Following example will illustrate the concept.
Let us have a working Eclipse IDE in place and take the following steps to create a Spring application −
Here is the content of TextEditor.java file −
package com.tutorialspoint;
public class TextEditor {
private SpellChecker spellChecker;
private String name;
public TextEditor( SpellChecker spellChecker, String name ) {
this.spellChecker = spellChecker;
this.name = name;
}
public SpellChecker getSpellChecker() {
return spellChecker;
}
public String getName() {
return name;
}
public void spellCheck() {
spellChecker.checkSpelling();
}
}
Following is the content of another dependent class file SpellChecker.java −
package com.tutorialspoint;
public class SpellChecker {
public SpellChecker(){
System.out.println("Inside SpellChecker constructor." );
}
public void checkSpelling(){
System.out.println("Inside checkSpelling." );
}
}
Following is the content of the MainApp.java file −
package com.tutorialspoint;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
TextEditor te = (TextEditor) context.getBean("textEditor");
te.spellCheck();
}
}
Following is the configuration file Beans.xml in normal condition −
<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<!-- Definition for textEditor bean -->
<bean id = "textEditor" class = "com.tutorialspoint.TextEditor">
<constructor-arg ref = "spellChecker" />
<constructor-arg value = "Generic Text Editor"/>
</bean>
<!-- Definition for spellChecker bean -->
<bean id = "spellChecker" class = "com.tutorialspoint.SpellChecker"></bean>
</beans>
But if you are going to use autowiring 'by constructor', then your XML configuration file will become as follows −
<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<!-- Definition for textEditor bean -->
<bean id = "textEditor" class = "com.tutorialspoint.TextEditor"
autowire = "constructor">
<constructor-arg value = "Generic Text Editor"/>
</bean>
<!-- Definition for spellChecker bean -->
<bean id = "SpellChecker" class = "com.tutorialspoint.SpellChecker"></bean>
</beans>
Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message −
Inside SpellChecker constructor. | [
{
"code": null,
"e": 2827,
"s": 2426,
"text": "This mode is very similar to byType, but it applies to constructor arguments. Spring container looks at the beans on which autowire attribute is set constructor in the XML configuration file. It then tries to match and wire its constructor's argument with exactly one of the beans name in the configuration file. If matches are found, it will inject those beans. Otherwise, bean(s) will not be wired."
},
{
"code": null,
"e": 3213,
"s": 2827,
"text": "For example, if a bean definition is set to autowire by constructor in configuration file, and it has a constructor with one of the arguments of SpellChecker type, Spring looks for a bean definition named SpellChecker, and uses it to set the constructor's argument. Still you can wire remaining arguments using <constructor-arg> tags. The Following example will illustrate the concept."
},
{
"code": null,
"e": 3318,
"s": 3213,
"text": "Let us have a working Eclipse IDE in place and take the following steps to create a Spring application −"
},
{
"code": null,
"e": 3364,
"s": 3318,
"text": "Here is the content of TextEditor.java file −"
},
{
"code": null,
"e": 3817,
"s": 3364,
"text": "package com.tutorialspoint;\n\npublic class TextEditor {\n private SpellChecker spellChecker;\n private String name;\n\n public TextEditor( SpellChecker spellChecker, String name ) {\n this.spellChecker = spellChecker;\n this.name = name;\n }\n public SpellChecker getSpellChecker() {\n return spellChecker;\n }\n public String getName() {\n return name;\n }\n public void spellCheck() {\n spellChecker.checkSpelling();\n }\n}"
},
{
"code": null,
"e": 3894,
"s": 3817,
"text": "Following is the content of another dependent class file SpellChecker.java −"
},
{
"code": null,
"e": 4136,
"s": 3894,
"text": "package com.tutorialspoint;\n\npublic class SpellChecker {\n public SpellChecker(){\n System.out.println(\"Inside SpellChecker constructor.\" );\n }\n public void checkSpelling(){\n System.out.println(\"Inside checkSpelling.\" );\n }\n}"
},
{
"code": null,
"e": 4188,
"s": 4136,
"text": "Following is the content of the MainApp.java file −"
},
{
"code": null,
"e": 4595,
"s": 4188,
"text": "package com.tutorialspoint;\n\nimport org.springframework.context.ApplicationContext;\nimport org.springframework.context.support.ClassPathXmlApplicationContext;\n\npublic class MainApp {\n public static void main(String[] args) {\n ApplicationContext context = new ClassPathXmlApplicationContext(\"Beans.xml\");\n TextEditor te = (TextEditor) context.getBean(\"textEditor\");\n te.spellCheck();\n }\n}"
},
{
"code": null,
"e": 4663,
"s": 4595,
"text": "Following is the configuration file Beans.xml in normal condition −"
},
{
"code": null,
"e": 5327,
"s": 4663,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n\n<beans xmlns = \"http://www.springframework.org/schema/beans\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://www.springframework.org/schema/beans\n http://www.springframework.org/schema/beans/spring-beans-3.0.xsd\">\n\n <!-- Definition for textEditor bean -->\n <bean id = \"textEditor\" class = \"com.tutorialspoint.TextEditor\">\n <constructor-arg ref = \"spellChecker\" />\n <constructor-arg value = \"Generic Text Editor\"/>\n </bean>\n\n <!-- Definition for spellChecker bean -->\n <bean id = \"spellChecker\" class = \"com.tutorialspoint.SpellChecker\"></bean>\n</beans>"
},
{
"code": null,
"e": 5442,
"s": 5327,
"text": "But if you are going to use autowiring 'by constructor', then your XML configuration file will become as follows −"
},
{
"code": null,
"e": 6090,
"s": 5442,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n\n<beans xmlns = \"http://www.springframework.org/schema/beans\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://www.springframework.org/schema/beans\n http://www.springframework.org/schema/beans/spring-beans-3.0.xsd\">\n\n <!-- Definition for textEditor bean -->\n <bean id = \"textEditor\" class = \"com.tutorialspoint.TextEditor\" \n autowire = \"constructor\">\n <constructor-arg value = \"Generic Text Editor\"/>\n </bean>\n\n <!-- Definition for spellChecker bean -->\n <bean id = \"SpellChecker\" class = \"com.tutorialspoint.SpellChecker\"></bean>\n\n</beans>"
},
{
"code": null,
"e": 6269,
"s": 6090,
"text": "Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message −"
}
]
|
How to style the Border of Label in C#? | 30 Jun, 2019
In Windows Forms, Label control is used to display text on the form and it does not take part in user input or in mouse or keyboard events. You are allowed to style the border of the Label control using the BorderStyle Property. You can style the border of the label in three different ways and these values are provided by the BorderStyle enum:
Fixed3D: The border of the label is a 3-D border.
FixedSingle: The border of the label is single-line border.
None: Label without border.
The default value of this property is BorderStyle.None. You can set this property using two different methods:
1. Design-Time: It is the easiest method to set the BorderStyle property of the Label control using the following steps:
Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp
Step 2: Drag the Label control from the ToolBox and drop it on the windows form. You are allowed to place a Label control anywhere on the windows form according to your need.
Step 3: After drag and drop you will go to the properties of the Label control to set the BorderStyle property of the Label.Output:
Output:
2. Run-Time: It is a little bit trickier than the above method. In this method, you can style the border of the Label control programmatically with the help of given syntax:
public virtual System.Windows.Forms.BorderStyle BorderStyle { get; set; }
Here, BorderStyle indicates border style values. It will throw an InvalidEnumArgumentException if the value assigned to this property does not belong to BorderStyle values. Following steps are used to set the BorderStyle property of the Label:
Step 1: Create a label using the Label() constructor is provided by the Label class.// Creating label using Label class
Label mylab = new Label();
// Creating label using Label class
Label mylab = new Label();
Step 2: After creating Label, set the BorderStyle property of the Label provided by the Label class.// Set BorderStyle property of the label
mylab.BorderStyle = BorderStyle.FixedSingle;
// Set BorderStyle property of the label
mylab.BorderStyle = BorderStyle.FixedSingle;
Step 3: And last add this Label control to form using Add() method.// Add this label to the form
this.Controls.Add(mylab);
Example:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp16 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the label Label mylab = new Label(); mylab.Text = "GeeksforGeeks"; mylab.Location = new Point(222, 90); mylab.Size = new Size(120, 25); mylab.BorderStyle = BorderStyle.FixedSingle; // Adding this control to the form this.Controls.Add(mylab); }}}Output:
// Add this label to the form
this.Controls.Add(mylab);
Example:
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp16 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the label Label mylab = new Label(); mylab.Text = "GeeksforGeeks"; mylab.Location = new Point(222, 90); mylab.Size = new Size(120, 25); mylab.BorderStyle = BorderStyle.FixedSingle; // Adding this control to the form this.Controls.Add(mylab); }}}
Output:
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# Dictionary with examples
C# | Multiple inheritance using interfaces
Introduction to .NET Framework
C# | Delegates
Differences Between .NET Core and .NET Framework
C# | Data Types
C# | Method Overriding
C# | Constructors
C# | Class and Object
C# | Replace() Method | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Jun, 2019"
},
{
"code": null,
"e": 374,
"s": 28,
"text": "In Windows Forms, Label control is used to display text on the form and it does not take part in user input or in mouse or keyboard events. You are allowed to style the border of the Label control using the BorderStyle Property. You can style the border of the label in three different ways and these values are provided by the BorderStyle enum:"
},
{
"code": null,
"e": 424,
"s": 374,
"text": "Fixed3D: The border of the label is a 3-D border."
},
{
"code": null,
"e": 484,
"s": 424,
"text": "FixedSingle: The border of the label is single-line border."
},
{
"code": null,
"e": 512,
"s": 484,
"text": "None: Label without border."
},
{
"code": null,
"e": 623,
"s": 512,
"text": "The default value of this property is BorderStyle.None. You can set this property using two different methods:"
},
{
"code": null,
"e": 744,
"s": 623,
"text": "1. Design-Time: It is the easiest method to set the BorderStyle property of the Label control using the following steps:"
},
{
"code": null,
"e": 860,
"s": 744,
"text": "Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp"
},
{
"code": null,
"e": 1035,
"s": 860,
"text": "Step 2: Drag the Label control from the ToolBox and drop it on the windows form. You are allowed to place a Label control anywhere on the windows form according to your need."
},
{
"code": null,
"e": 1167,
"s": 1035,
"text": "Step 3: After drag and drop you will go to the properties of the Label control to set the BorderStyle property of the Label.Output:"
},
{
"code": null,
"e": 1175,
"s": 1167,
"text": "Output:"
},
{
"code": null,
"e": 1349,
"s": 1175,
"text": "2. Run-Time: It is a little bit trickier than the above method. In this method, you can style the border of the Label control programmatically with the help of given syntax:"
},
{
"code": null,
"e": 1423,
"s": 1349,
"text": "public virtual System.Windows.Forms.BorderStyle BorderStyle { get; set; }"
},
{
"code": null,
"e": 1667,
"s": 1423,
"text": "Here, BorderStyle indicates border style values. It will throw an InvalidEnumArgumentException if the value assigned to this property does not belong to BorderStyle values. Following steps are used to set the BorderStyle property of the Label:"
},
{
"code": null,
"e": 1815,
"s": 1667,
"text": "Step 1: Create a label using the Label() constructor is provided by the Label class.// Creating label using Label class\nLabel mylab = new Label();\n"
},
{
"code": null,
"e": 1879,
"s": 1815,
"text": "// Creating label using Label class\nLabel mylab = new Label();\n"
},
{
"code": null,
"e": 2066,
"s": 1879,
"text": "Step 2: After creating Label, set the BorderStyle property of the Label provided by the Label class.// Set BorderStyle property of the label\nmylab.BorderStyle = BorderStyle.FixedSingle;\n"
},
{
"code": null,
"e": 2153,
"s": 2066,
"text": "// Set BorderStyle property of the label\nmylab.BorderStyle = BorderStyle.FixedSingle;\n"
},
{
"code": null,
"e": 3018,
"s": 2153,
"text": "Step 3: And last add this Label control to form using Add() method.// Add this label to the form\nthis.Controls.Add(mylab);\nExample:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp16 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the label Label mylab = new Label(); mylab.Text = \"GeeksforGeeks\"; mylab.Location = new Point(222, 90); mylab.Size = new Size(120, 25); mylab.BorderStyle = BorderStyle.FixedSingle; // Adding this control to the form this.Controls.Add(mylab); }}}Output:"
},
{
"code": null,
"e": 3075,
"s": 3018,
"text": "// Add this label to the form\nthis.Controls.Add(mylab);\n"
},
{
"code": null,
"e": 3084,
"s": 3075,
"text": "Example:"
},
{
"code": "using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp16 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the label Label mylab = new Label(); mylab.Text = \"GeeksforGeeks\"; mylab.Location = new Point(222, 90); mylab.Size = new Size(120, 25); mylab.BorderStyle = BorderStyle.FixedSingle; // Adding this control to the form this.Controls.Add(mylab); }}}",
"e": 3811,
"s": 3084,
"text": null
},
{
"code": null,
"e": 3819,
"s": 3811,
"text": "Output:"
},
{
"code": null,
"e": 3822,
"s": 3819,
"text": "C#"
},
{
"code": null,
"e": 3920,
"s": 3822,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3948,
"s": 3920,
"text": "C# Dictionary with examples"
},
{
"code": null,
"e": 3991,
"s": 3948,
"text": "C# | Multiple inheritance using interfaces"
},
{
"code": null,
"e": 4022,
"s": 3991,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 4037,
"s": 4022,
"text": "C# | Delegates"
},
{
"code": null,
"e": 4086,
"s": 4037,
"text": "Differences Between .NET Core and .NET Framework"
},
{
"code": null,
"e": 4102,
"s": 4086,
"text": "C# | Data Types"
},
{
"code": null,
"e": 4125,
"s": 4102,
"text": "C# | Method Overriding"
},
{
"code": null,
"e": 4143,
"s": 4125,
"text": "C# | Constructors"
},
{
"code": null,
"e": 4165,
"s": 4143,
"text": "C# | Class and Object"
}
]
|
Minimum number of increasing subsequences | 22 Jun, 2022
Given an array of integers of size N, you have to divide it into the minimum number of “strictly increasing subsequences” For example: let the sequence be {1, 3, 2, 4}, then the answer would be 2. In this case, the first increasing sequence would be {1, 3, 4} and the second would be {2}.Examples:
Input : arr[] = {1 3 2 4} Output: 2 There are two increasing subsequences {1, 3, 4} and {2}Input : arr[] = {4 3 2 1} Output : 4Input : arr[] = {1 2 3 4} Output : 1Input : arr[] = {1 6 2 4 3} Output : 3
If we focus on the example we can see that the Minimum number of increasing subsequences equals to the length of longest decreasing subsequence where each element from the longest decreasing subsequence represents an increasing subsequence, so it can be found in N*Log(N) time complexity in the same way as longest increasing subsequence by multiplying all the elements with -1. We iterator over all elements and store in a sorted array (multiset) S the last element in each one of the increasing subsequences found so far and for every element X, we pick the largest element smaller than X -using binary search- in the S and replace it with X which means that we added the current element to increasing subsequence ending with X, otherwise, if there is no element smaller than X in S we insert it in S which forms a new increasing subsequence and so on until the last element and our answer in the last will be the size of S.
CPP
// C++ program to count the Minimum number of// increasing subsequences#include <bits/stdc++.h>using namespace std; int MinimumNumIncreasingSubsequences(int arr[], int n){ multiset<int> last; // last element in each increasing subsequence // found so far for (int i = 0; i < n; i++) { // here our current element is arr[i] multiset<int>::iterator it = last.lower_bound(arr[i]); // iterator to the first element larger // than or equal to arr[i] if (it == last.begin()) // if all the elements in last larger // than or to arr[i] then insert it into last last.insert(arr[i]); else { it--; // the largest element smaller than arr[i] is the number // before *it which is it-- last.erase(it); // erase the largest element smaller than arr[i] last.insert(arr[i]); // and replace it with arr[i] } } return last.size(); // our answer is the size of last} // Driver programint main(){ int arr[] = { 8, 4, 1, 2, 9 }; int n = sizeof(arr) / sizeof(int); cout << "Minimum number of increasing subsequences are : " << MinimumNumIncreasingSubsequences(arr, n); return 0;}
Minimum number of increasing subsequences are : 3
Time complexity: O(N log(N)) Auxiliary Space : O(N) Approach 2: The idea is to find the longest decreasing subsequence
Initialize a dp array of length n.
Inverting all the elements of the array.
for each element in the array.
find the index if the current element in the dp array.
find the maximum index which is valid.
dp[i] indicate that minimum element ending at the length i subsequence.
Below is the implementation of above approach :
C++
Java
Python3
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // To search for correct position of num in array dpint search(vector<int>dp, int num){ // Initialise low,high and ans int low = 0,high = dp.size() - 1; int ans = -1; while (low <= high){ // Get mid int mid = low + ((high - low) / 2); // If mid element is >=num search for left half if (dp[mid] >= num){ ans = mid; high = mid - 1; } else low = mid + 1; } return ans;} int longestDecrasingSubsequence(vector<int>A,int N){ // Initialise Dp array vector<int>dp(N+1,INT_MAX); // All the elements are in range // of leteger minvalue // to maxvalue // dp[i] indicate the min element // of subsequence of // length i is dp[i] dp[0] = INT_MIN; // For each number search for the correct position // of number and insert the number in array for(int i = 0; i < N; i++){ // search for th position int index = search(dp, A[i]); // update the dp array if (index != -1) dp[index] = min(dp[index], A[i]); } int Len = 0; for(int i = 1; i < N; i++){ if (dp[i] != INT_MAX) Len = max(i, Len); } return Len;} // Driver codeint main(){ int n = 4; vector<int> a = { 1, 2, 3, 4 }; for(int i=0;i<n;i++) a[i] = -a[i]; cout << longestDecrasingSubsequence(a, n) << endl; return 0;} // This code is contributed by shinjanpatra
// Java program for the above approachimport java.util.*;public class Main { static int longestDecrasingSubsequence(int A[], int N) { // Initialise Dp array int dp[] = new int[N + 1]; Arrays.fill(dp, Integer.MAX_VALUE); // All the elements are in range // of Integer minvalue // to maxvalue // dp[i] indicate the min element // of subsequence of // length i is dp[i] dp[0] = Integer.MIN_VALUE; // For each number search for the correct position // of number and insert the number in array for (int i = 0; i < N; i++) { // search for th position int index = search(dp, A[i]); // update the dp array if (index != -1) dp[index] = Math.min(dp[index], A[i]); } int len = 0; for (int i = 1; i <= N; i++) { if (dp[i] != Integer.MAX_VALUE) len = Math.max(i, len); } return len; } // to search for correct position of num in array dp static int search(int dp[], int num) { // initialise low,high and ans int low = 0, high = dp.length - 1; int ans = -1; while (low <= high) { // get mid int mid = low + (high - low) / 2; // if mid element is >=num search for left half if (dp[mid] >= num) { ans = mid; high = mid - 1; } else low = mid + 1; } return ans; } // Driver Code public static void main(String args[]) { int n = 4; int a[] = { 1, 2, 3, 4 }; for (int i = 0; i < n; i++) a[i] = -a[i]; System.out.print(longestDecrasingSubsequence(a, n)); }}
# Python program for the above approachimport sys def longestDecrasingSubsequence(A,N): # Initialise Dp array dp = [sys.maxsize for i in range(N+1)] # All the elements are in range # of leteger minvalue # to maxvalue # dp[i] indicate the min element # of subsequence of # length i is dp[i] dp[0] = -sys.maxsize -1 # For each number search for the correct position # of number and insert the number in array for i in range(N): # search for th position index = search(dp, A[i]) # update the dp array if (index != -1): dp[index] = min(dp[index], A[i]) Len = 0 for i in range(1,N): if (dp[i] != sys.maxsize): Len = max(i, Len) return Len # to search for correct position of num in array dpdef search(dp, num): # initialise low,high and ans low,high = 0, len(dp) - 1 ans = -1 while (low <= high): # get mid mid = low + (high - low) // 2 # if mid element is >=num search for left half if (dp[mid] >= num): ans = mid high = mid - 1 else: low = mid + 1 return ans # Driver Coden = 4a = [ 1, 2, 3, 4 ]for i in range(n): a[i] = -a[i] print(longestDecrasingSubsequence(a, n)) # This code is contributed by shinjanpatra
1
hemanthswarna1506
shinjanpatra
cpp-multiset
LIS
Competitive Programming
Dynamic Programming
Dynamic Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Count of strings whose prefix match with the given string to a given length k
Most important type of Algorithms
The Ultimate Beginner's Guide For DSA
Find two numbers from their sum and XOR
C++: Methods of code shortening in competitive programming
Largest Sum Contiguous Subarray
Program for Fibonacci numbers
0-1 Knapsack Problem | DP-10
Longest Common Subsequence | DP-4
Subset Sum Problem | DP-25 | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n22 Jun, 2022"
},
{
"code": null,
"e": 352,
"s": 54,
"text": "Given an array of integers of size N, you have to divide it into the minimum number of “strictly increasing subsequences” For example: let the sequence be {1, 3, 2, 4}, then the answer would be 2. In this case, the first increasing sequence would be {1, 3, 4} and the second would be {2}.Examples:"
},
{
"code": null,
"e": 555,
"s": 352,
"text": " Input : arr[] = {1 3 2 4} Output: 2 There are two increasing subsequences {1, 3, 4} and {2}Input : arr[] = {4 3 2 1} Output : 4Input : arr[] = {1 2 3 4} Output : 1Input : arr[] = {1 6 2 4 3} Output : 3"
},
{
"code": null,
"e": 1482,
"s": 555,
"text": "If we focus on the example we can see that the Minimum number of increasing subsequences equals to the length of longest decreasing subsequence where each element from the longest decreasing subsequence represents an increasing subsequence, so it can be found in N*Log(N) time complexity in the same way as longest increasing subsequence by multiplying all the elements with -1. We iterator over all elements and store in a sorted array (multiset) S the last element in each one of the increasing subsequences found so far and for every element X, we pick the largest element smaller than X -using binary search- in the S and replace it with X which means that we added the current element to increasing subsequence ending with X, otherwise, if there is no element smaller than X in S we insert it in S which forms a new increasing subsequence and so on until the last element and our answer in the last will be the size of S."
},
{
"code": null,
"e": 1486,
"s": 1482,
"text": "CPP"
},
{
"code": "// C++ program to count the Minimum number of// increasing subsequences#include <bits/stdc++.h>using namespace std; int MinimumNumIncreasingSubsequences(int arr[], int n){ multiset<int> last; // last element in each increasing subsequence // found so far for (int i = 0; i < n; i++) { // here our current element is arr[i] multiset<int>::iterator it = last.lower_bound(arr[i]); // iterator to the first element larger // than or equal to arr[i] if (it == last.begin()) // if all the elements in last larger // than or to arr[i] then insert it into last last.insert(arr[i]); else { it--; // the largest element smaller than arr[i] is the number // before *it which is it-- last.erase(it); // erase the largest element smaller than arr[i] last.insert(arr[i]); // and replace it with arr[i] } } return last.size(); // our answer is the size of last} // Driver programint main(){ int arr[] = { 8, 4, 1, 2, 9 }; int n = sizeof(arr) / sizeof(int); cout << \"Minimum number of increasing subsequences are : \" << MinimumNumIncreasingSubsequences(arr, n); return 0;}",
"e": 2725,
"s": 1486,
"text": null
},
{
"code": null,
"e": 2775,
"s": 2725,
"text": "Minimum number of increasing subsequences are : 3"
},
{
"code": null,
"e": 2894,
"s": 2775,
"text": "Time complexity: O(N log(N)) Auxiliary Space : O(N) Approach 2: The idea is to find the longest decreasing subsequence"
},
{
"code": null,
"e": 2929,
"s": 2894,
"text": "Initialize a dp array of length n."
},
{
"code": null,
"e": 2970,
"s": 2929,
"text": "Inverting all the elements of the array."
},
{
"code": null,
"e": 3001,
"s": 2970,
"text": "for each element in the array."
},
{
"code": null,
"e": 3056,
"s": 3001,
"text": "find the index if the current element in the dp array."
},
{
"code": null,
"e": 3095,
"s": 3056,
"text": "find the maximum index which is valid."
},
{
"code": null,
"e": 3167,
"s": 3095,
"text": "dp[i] indicate that minimum element ending at the length i subsequence."
},
{
"code": null,
"e": 3215,
"s": 3167,
"text": "Below is the implementation of above approach :"
},
{
"code": null,
"e": 3219,
"s": 3215,
"text": "C++"
},
{
"code": null,
"e": 3224,
"s": 3219,
"text": "Java"
},
{
"code": null,
"e": 3232,
"s": 3224,
"text": "Python3"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // To search for correct position of num in array dpint search(vector<int>dp, int num){ // Initialise low,high and ans int low = 0,high = dp.size() - 1; int ans = -1; while (low <= high){ // Get mid int mid = low + ((high - low) / 2); // If mid element is >=num search for left half if (dp[mid] >= num){ ans = mid; high = mid - 1; } else low = mid + 1; } return ans;} int longestDecrasingSubsequence(vector<int>A,int N){ // Initialise Dp array vector<int>dp(N+1,INT_MAX); // All the elements are in range // of leteger minvalue // to maxvalue // dp[i] indicate the min element // of subsequence of // length i is dp[i] dp[0] = INT_MIN; // For each number search for the correct position // of number and insert the number in array for(int i = 0; i < N; i++){ // search for th position int index = search(dp, A[i]); // update the dp array if (index != -1) dp[index] = min(dp[index], A[i]); } int Len = 0; for(int i = 1; i < N; i++){ if (dp[i] != INT_MAX) Len = max(i, Len); } return Len;} // Driver codeint main(){ int n = 4; vector<int> a = { 1, 2, 3, 4 }; for(int i=0;i<n;i++) a[i] = -a[i]; cout << longestDecrasingSubsequence(a, n) << endl; return 0;} // This code is contributed by shinjanpatra",
"e": 4763,
"s": 3232,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*;public class Main { static int longestDecrasingSubsequence(int A[], int N) { // Initialise Dp array int dp[] = new int[N + 1]; Arrays.fill(dp, Integer.MAX_VALUE); // All the elements are in range // of Integer minvalue // to maxvalue // dp[i] indicate the min element // of subsequence of // length i is dp[i] dp[0] = Integer.MIN_VALUE; // For each number search for the correct position // of number and insert the number in array for (int i = 0; i < N; i++) { // search for th position int index = search(dp, A[i]); // update the dp array if (index != -1) dp[index] = Math.min(dp[index], A[i]); } int len = 0; for (int i = 1; i <= N; i++) { if (dp[i] != Integer.MAX_VALUE) len = Math.max(i, len); } return len; } // to search for correct position of num in array dp static int search(int dp[], int num) { // initialise low,high and ans int low = 0, high = dp.length - 1; int ans = -1; while (low <= high) { // get mid int mid = low + (high - low) / 2; // if mid element is >=num search for left half if (dp[mid] >= num) { ans = mid; high = mid - 1; } else low = mid + 1; } return ans; } // Driver Code public static void main(String args[]) { int n = 4; int a[] = { 1, 2, 3, 4 }; for (int i = 0; i < n; i++) a[i] = -a[i]; System.out.print(longestDecrasingSubsequence(a, n)); }}",
"e": 6602,
"s": 4763,
"text": null
},
{
"code": "# Python program for the above approachimport sys def longestDecrasingSubsequence(A,N): # Initialise Dp array dp = [sys.maxsize for i in range(N+1)] # All the elements are in range # of leteger minvalue # to maxvalue # dp[i] indicate the min element # of subsequence of # length i is dp[i] dp[0] = -sys.maxsize -1 # For each number search for the correct position # of number and insert the number in array for i in range(N): # search for th position index = search(dp, A[i]) # update the dp array if (index != -1): dp[index] = min(dp[index], A[i]) Len = 0 for i in range(1,N): if (dp[i] != sys.maxsize): Len = max(i, Len) return Len # to search for correct position of num in array dpdef search(dp, num): # initialise low,high and ans low,high = 0, len(dp) - 1 ans = -1 while (low <= high): # get mid mid = low + (high - low) // 2 # if mid element is >=num search for left half if (dp[mid] >= num): ans = mid high = mid - 1 else: low = mid + 1 return ans # Driver Coden = 4a = [ 1, 2, 3, 4 ]for i in range(n): a[i] = -a[i] print(longestDecrasingSubsequence(a, n)) # This code is contributed by shinjanpatra",
"e": 7926,
"s": 6602,
"text": null
},
{
"code": null,
"e": 7928,
"s": 7926,
"text": "1"
},
{
"code": null,
"e": 7946,
"s": 7928,
"text": "hemanthswarna1506"
},
{
"code": null,
"e": 7959,
"s": 7946,
"text": "shinjanpatra"
},
{
"code": null,
"e": 7972,
"s": 7959,
"text": "cpp-multiset"
},
{
"code": null,
"e": 7976,
"s": 7972,
"text": "LIS"
},
{
"code": null,
"e": 8000,
"s": 7976,
"text": "Competitive Programming"
},
{
"code": null,
"e": 8020,
"s": 8000,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 8040,
"s": 8020,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 8138,
"s": 8040,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8216,
"s": 8138,
"text": "Count of strings whose prefix match with the given string to a given length k"
},
{
"code": null,
"e": 8250,
"s": 8216,
"text": "Most important type of Algorithms"
},
{
"code": null,
"e": 8288,
"s": 8250,
"text": "The Ultimate Beginner's Guide For DSA"
},
{
"code": null,
"e": 8328,
"s": 8288,
"text": "Find two numbers from their sum and XOR"
},
{
"code": null,
"e": 8387,
"s": 8328,
"text": "C++: Methods of code shortening in competitive programming"
},
{
"code": null,
"e": 8419,
"s": 8387,
"text": "Largest Sum Contiguous Subarray"
},
{
"code": null,
"e": 8449,
"s": 8419,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 8478,
"s": 8449,
"text": "0-1 Knapsack Problem | DP-10"
},
{
"code": null,
"e": 8512,
"s": 8478,
"text": "Longest Common Subsequence | DP-4"
}
]
|
Given two unsorted arrays, find all pairs whose sum is x | 08 Jul, 2022
Given two unsorted arrays of distinct elements, the task is to find all pairs from both arrays whose sum is equal to X.
Examples:
Input : arr1[] = {-1, -2, 4, -6, 5, 7}
arr2[] = {6, 3, 4, 0}
x = 8
Output : 4 4
5 3
Input : arr1[] = {1, 2, 4, 5, 7}
arr2[] = {5, 6, 3, 4, 8}
x = 9
Output : 1 8
4 5
5 4
Asked in: Amazon
A Naive approach is to simply run two loops and pick elements from both arrays. One by one check that both elements sum is equal to given value x or not.
Implementation:
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find all pairs in both arrays// whose sum is equal to given value x#include <bits/stdc++.h> using namespace std; // Function to print all pairs in both arrays// whose sum is equal to given value xvoid findPairs(int arr1[], int arr2[], int n, int m, int x){ for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) if (arr1[i] + arr2[j] == x) cout << arr1[i] << " " << arr2[j] << endl;} // Driver codeint main(){ int arr1[] = { 1, 2, 3, 7, 5, 4 }; int arr2[] = { 0, 7, 4, 3, 2, 1 }; int n = sizeof(arr1) / sizeof(int); int m = sizeof(arr2) / sizeof(int); int x = 8; findPairs(arr1, arr2, n, m, x); return 0;}
// Java program to find all pairs in both arrays// whose sum is equal to given value ximport java.io.*; class GFG { // Function to print all pairs in both arrays // whose sum is equal to given value x static void findPairs(int arr1[], int arr2[], int n, int m, int x) { for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) if (arr1[i] + arr2[j] == x) System.out.println(arr1[i] + " " + arr2[j]); } // Driver code public static void main(String[] args) { int arr1[] = { 1, 2, 3, 7, 5, 4 }; int arr2[] = { 0, 7, 4, 3, 2, 1 }; int x = 8; findPairs(arr1, arr2, arr1.length, arr2.length, x); }} // This code is contributed// by sunnysingh
# Python 3 program to find all# pairs in both arrays whose# sum is equal to given value x # Function to print all pairs# in both arrays whose sum is# equal to given value xdef findPairs(arr1, arr2, n, m, x): for i in range(0, n): for j in range(0, m): if (arr1[i] + arr2[j] == x): print(arr1[i], arr2[j]) # Driver codearr1 = [1, 2, 3, 7, 5, 4]arr2 = [0, 7, 4, 3, 2, 1]n = len(arr1)m = len(arr2)x = 8findPairs(arr1, arr2, n, m, x) # This code is contributed by Smitha Dinesh Semwal
// C# program to find all// pairs in both arrays// whose sum is equal to// given value xusing System; class GFG { // Function to print all // pairs in both arrays // whose sum is equal to // given value x static void findPairs(int[] arr1, int[] arr2, int n, int m, int x) { for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) if (arr1[i] + arr2[j] == x) Console.WriteLine(arr1[i] + " " + arr2[j]); } // Driver code static void Main() { int[] arr1 = { 1, 2, 3, 7, 5, 4 }; int[] arr2 = { 0, 7, 4, 3, 2, 1 }; int x = 8; findPairs(arr1, arr2, arr1.Length, arr2.Length, x); }} // This code is contributed// by Sam007
<?php// PHP program to find all pairs// in both arrays whose sum is// equal to given value x // Function to print all pairs// in both arrays whose sum is// equal to given value xfunction findPairs($arr1, $arr2, $n, $m, $x){ for ($i = 0; $i < $n; $i++) for ($j = 0; $j < $m; $j++) if ($arr1[$i] + $arr2[$j] == $x) echo $arr1[$i] . " " . $arr2[$j] . "\n";} // Driver code$arr1 = array(1, 2, 3, 7, 5, 4);$arr2 = array(0, 7, 4, 3, 2, 1);$n = count($arr1);$m = count($arr2);$x = 8;findPairs($arr1, $arr2, $n, $m, $x); // This code is contributed// by Sam007?>
<script> // Javascript program to find all pairs in both arrays// whose sum is equal to given value x // Function to print all pairs in both arrays// whose sum is equal to given value xfunction findPairs(arr1, arr2, n, m, x){ for (let i = 0; i < n; i++) for (let j = 0; j < m; j++) if (arr1[i] + arr2[j] == x) document.write(arr1[i] + " " + arr2[j] + "<br>");} // Driver code let arr1 = [ 1, 2, 3, 7, 5, 4 ]; let arr2 = [ 0, 7, 4, 3, 2, 1 ]; let n = arr1.length; let m = arr2.length; let x = 8; findPairs(arr1, arr2, n, m, x); // This code is contributed by Surbhi Tyagi. </script>
1 7
7 1
5 3
4 4
Time Complexity : O(n^2) Auxiliary Space : O(1)
Searching Approach : As we know sorting algorithms can sort data in O (n log n) time. So we will choose a O (n log n) time algorithm like : Quick Sort or Heap Sort. For each element of second array , we will subtract it from K and search it in the first array.
Steps:
First sort the given array using a O(n log n) algorithm like Heap Sort or Quick Sort.Run a loop for each element of array-B (0 to n).Inside the loop, use a temporary variable say temp, and temp = K – B[i].Search the temp variable in the first array i.e. A, using Binary Search(log n).
First sort the given array using a O(n log n) algorithm like Heap Sort or Quick Sort.
Run a loop for each element of array-B (0 to n).
Inside the loop, use a temporary variable say temp, and temp = K – B[i].
Search the temp variable in the first array i.e. A, using Binary Search(log n).
If the element is found in A then there exists a ∈ A and b ∈ B such that a + b = K.
Implementation:
C++
Java
Python3
C#
Javascript
#include<bits/stdc++.h>using namespace std; void heapify(int a[] , int n , int i){ int rootLargest = i; int lchild = 2 * i; int rchild = (2 * i) + 1; if (lchild < n && a[lchild] > a[rootLargest]) rootLargest = lchild; if (rchild < n && a[rchild] > a[rootLargest]) rootLargest = rchild; if (rootLargest != i) { swap(a[i] , a[rootLargest]); //Recursion heapify(a , n , rootLargest); }} int binarySearch(int a[] , int l , int r , int x){ while (l <= r) { int m = l + (r - l) / 2; if (a[m] == x) return m; if (a[m] < x) l = m + 1; else r = m - 1; } return -1;} int main(){ int A[] = {1,2,1,3,4}; int B[] = {3,1,5,1,2}; int K = 8; int n = sizeof(A) / sizeof(A[0]); // Building the heap for (int i = n / 2 - 1 ; i >= 1; i--) heapify(A , n , i); for(int i=0 ; i<n ; i++) //O(n) { int temp = K - B[i]; //O(1) if(binarySearch(A , 0 , n-1 , temp)) //O(logn) { cout<<"\nFound the elements.\n"; break; } } return 0;}
import java.util.*; class GFG{ static int A[] = {1,2,1,3,4}; static void heapify( int n , int i) { int rootLargest = i; int lchild = 2 * i; int rchild = (2 * i) + 1; if (lchild < n && A[lchild] > A[rootLargest]) rootLargest = lchild; if (rchild < n && A[rchild] > A[rootLargest]) rootLargest = rchild; if (rootLargest != i) { int t = A[i]; A[i] = A[rootLargest]; A[rootLargest] = t; //Recursion heapify( n , rootLargest); } } static int binarySearch( int l , int r , int x) { while (l <= r) { int m = l + (r - l) / 2; if (A[m] == x) return m; if (A[m] < x) l = m + 1; else r = m - 1; } return -1; } public static void main(String[] args) { int B[] = {3,1,5,1,2}; int K = 8; int n = A.length; // Building the heap for (int i = n / 2 - 1 ; i >= 1; i--) heapify( n , i); for(int i = 0; i < n; i++) //O(n) { int temp = K - B[i]; //O(1) if(binarySearch(0, n - 1, temp - 1) != -1) //O(logn) { System.out.print("\nFound the elements.\n"); break; } } }} // This code is contributed by Rajput-Ji
A = [ 1, 2, 1, 3, 4 ]; def heapify(n, i): rootLargest = i; lchild = 2 * i; rchild = (2 * i) + 1; if (lchild < n and A[lchild] > A[rootLargest]): rootLargest = lchild; if (rchild < n and A[rchild] > A[rootLargest]): rootLargest = rchild; if (rootLargest != i): t = A[i]; A[i] = A[rootLargest]; A[rootLargest] = t; # Recursion heapify(n, rootLargest); def binarySearch(l, r, x): while (l <= r): m = l + (r - l) // 2; if (A[m] == x): return m; if (A[m] < x): l = m + 1; else: r = m - 1; return -1; if __name__ == '__main__': B = [ 3, 1, 5, 1, 2 ]; K = 8; n = len(A); # Building the heap for i in range(n// 2 - 1,0, -1): heapify(n, i); for i in range(n): temp = K - B[i]; if (binarySearch(0, n - 1, temp - 1) != -1): print("\nFound the elements."); break; # This code is contributed by Rajput-Ji
using System;public class GFG { static int []A = { 1, 2, 1, 3, 4 }; static void heapify(int n, int i) { int rootLargest = i; int lchild = 2 * i; int rchild = (2 * i) + 1; if (lchild < n && A[lchild] > A[rootLargest]) rootLargest = lchild; if (rchild < n && A[rchild] > A[rootLargest]) rootLargest = rchild; if (rootLargest != i) { int t = A[i]; A[i] = A[rootLargest]; A[rootLargest] = t; // Recursion heapify(n, rootLargest); } } static int binarySearch(int l, int r, int x) { while (l <= r) { int m = l + (r - l) / 2; if (A[m] == x) return m; if (A[m] < x) l = m + 1; else r = m - 1; } return -1; } public static void Main(String[] args) { int []B = { 3, 1, 5, 1, 2 }; int K = 8; int n = A.Length; // Building the heap for (int i = n / 2 - 1; i >= 1; i--) heapify(n, i); for (int i = 0; i < n; i++) // O(n) { int temp = K - B[i]; // O(1) if (binarySearch(0, n - 1, temp - 1) != -1) // O(logn) { Console.Write("\nFound the elements.\n"); break; } } }} // This code is contributed by Rajput-Ji
<script>function heapify(a,n,i){ let rootLargest = i; let lchild = 2 * i; let rchild = (2 * i) + 1; if (lchild < n && a[lchild] > a[rootLargest]) rootLargest = lchild; if (rchild < n && a[rchild] > a[rootLargest]) rootLargest = rchild; if (rootLargest != i) { swap(a[i] , a[rootLargest]); //Recursion heapify(a , n , rootLargest); }} function binarySearch(a,l,r,x){ while (l <= r) { let m = l + (r - l) / 2; if (a[m] == x) return m; if (a[m] < x) l = m + 1; else r = m - 1; } return -1;} let A = [1,2,1,3,4]; let B = [3,1,5,1,2]; let K = 8; let n = A.length; // Building the heap for (let i = n / 2 - 1 ; i >= 1; i--) heapify(A , n , i); for(let i=0 ; i<n ; i++) //O(n) { let temp = K - B[i]; //O(1) if(binarySearch(A , 0 , n-1 , temp)) //O(logn) { document.write("\nFound the elements.\n"); break; } } </script>
Found the elements.
Time Complexity: O(n logn).
O(log n + n log n)
So, Overall time complexity = O(n logn).
An Efficient solution of this problem is to hashing. Hash table is implemented using unordered_set in C++.
We store all first array elements in hash table.
For elements of second array, we subtract every element from x and check the result in hash table.
If result is present, we print the element and key in hash (which is an element of first array).
Implementation:
C++
Java
Python3
C#
Javascript
// C++ program to find all pair in both arrays// whose sum is equal to given value x#include <bits/stdc++.h>using namespace std; // Function to find all pairs in both arrays// whose sum is equal to given value xvoid findPairs(int arr1[], int arr2[], int n, int m, int x){ // Insert all elements of first array in a hash unordered_set<int> s; for (int i = 0; i < n; i++) s.insert(arr1[i]); // Subtract sum from second array elements one // by one and check it's present in array first // or not for (int j = 0; j < m; j++) if (s.find(x - arr2[j]) != s.end()) cout << x - arr2[j] << " " << arr2[j] << endl;} // Driver codeint main(){ int arr1[] = { 1, 0, -4, 7, 6, 4 }; int arr2[] = { 0, 2, 4, -3, 2, 1 }; int x = 8; int n = sizeof(arr1) / sizeof(int); int m = sizeof(arr2) / sizeof(int); findPairs(arr1, arr2, n, m, x); return 0;}
// JAVA Code for Given two unsorted arrays,// find all pairs whose sum is ximport java.util.*; class GFG { // Function to find all pairs in both arrays // whose sum is equal to given value x public static void findPairs(int arr1[], int arr2[], int n, int m, int x) { // Insert all elements of first array in a hash HashMap<Integer, Integer> s = new HashMap<Integer, Integer>(); for (int i = 0; i < n; i++) s.put(arr1[i], 0); // Subtract sum from second array elements one // by one and check it's present in array first // or not for (int j = 0; j < m; j++) if (s.containsKey(x - arr2[j])) System.out.println(x - arr2[j] + " " + arr2[j]); } /* Driver program to test above function */ public static void main(String[] args) { int arr1[] = { 1, 0, -4, 7, 6, 4 }; int arr2[] = { 0, 2, 4, -3, 2, 1 }; int x = 8; findPairs(arr1, arr2, arr1.length, arr2.length, x); }}// This code is contributed by Arnav Kr. Mandal.
# Python3 program to find all# pair in both arrays whose# sum is equal to given value x # Function to find all pairs# in both arrays whose sum is# equal to given value xdef findPairs(arr1, arr2, n, m, x): # Insert all elements of # first array in a hash s = set() for i in range (0, n): s.add(arr1[i]) # Subtract sum from second # array elements one by one # and check it's present in # array first or not for j in range(0, m): if ((x - arr2[j]) in s): print((x - arr2[j]), '', arr2[j]) # Driver codearr1 = [1, 0, -4, 7, 6, 4]arr2 = [0, 2, 4, -3, 2, 1]x = 8 n = len(arr1)m = len(arr2)findPairs(arr1, arr2, n, m, x) # This code is contributed# by ihritik
// C# Code for Given two unsorted arrays,// find all pairs whose sum is xusing System;using System.Collections.Generic; class GFG { // Function to find all pairs in // both arrays whose sum is equal // to given value x public static void findPairs(int[] arr1, int[] arr2, int n, int m, int x) { // Insert all elements of first // array in a hash Dictionary<int, int> s = new Dictionary<int, int>(); for (int i = 0; i < n; i++) { s[arr1[i]] = 0; } // Subtract sum from second array // elements one by one and check // it's present in array first // or not for (int j = 0; j < m; j++) { if (s.ContainsKey(x - arr2[j])) { Console.WriteLine(x - arr2[j] + " " + arr2[j]); } } } // Driver Code public static void Main(string[] args) { int[] arr1 = new int[] { 1, 0, -4, 7, 6, 4 }; int[] arr2 = new int[] { 0, 2, 4, -3, 2, 1 }; int x = 8; findPairs(arr1, arr2, arr1.Length, arr2.Length, x); }} // This code is contributed by Shrikant13
<script> // Javascript Code for Given two unsorted arrays,// find all pairs whose sum is x // Function to find all pairs in both arrays // whose sum is equal to given value x function findPairs(arr1, arr2, n, m, x) { // Insert all elements of first array in a hash let s = new Map(); for (let i = 0; i < n; i++) s.set(arr1[i], 0); // Subtract sum from second array elements one // by one and check it's present in array first // or not for (let j = 0; j < m; j++) if (s.has(x - arr2[j])) document.write(x - arr2[j] + " " + arr2[j] + "<br/>"); } // Driver code let arr1 = [ 1, 0, -4, 7, 6, 4 ]; let arr2 = [ 0, 2, 4, -3, 2, 1 ]; let x = 8; findPairs(arr1, arr2, arr1.length, arr2.length, x); </script>
6 2
4 4
6 2
7 1
Time Complexity: O(max(n, m)) Auxiliary Space: O(n)
This article is contributed by DANISH_RAZA . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Sam007
namankatuva
ihritik
shrikanth13
Mayuri Gupta 4
sp999
RishabhAgnihotri
surbhityagi15
imsushant12
avijitmondal1998
vaibhavrabadiya3
Rajput-Ji
hardikkoriintern
Amazon
Facebook
Arrays
Hash
Amazon
Facebook
Arrays
Hash
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Stack Data Structure (Introduction and Program)
Linear Search
What is Hashing | A Complete Tutorial
Internal Working of HashMap in Java
Hashing | Set 1 (Introduction)
Longest Consecutive Subsequence
Sort string of characters | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n08 Jul, 2022"
},
{
"code": null,
"e": 172,
"s": 52,
"text": "Given two unsorted arrays of distinct elements, the task is to find all pairs from both arrays whose sum is equal to X."
},
{
"code": null,
"e": 183,
"s": 172,
"text": "Examples: "
},
{
"code": null,
"e": 420,
"s": 183,
"text": "Input : arr1[] = {-1, -2, 4, -6, 5, 7}\n arr2[] = {6, 3, 4, 0} \n x = 8\nOutput : 4 4\n 5 3\n\nInput : arr1[] = {1, 2, 4, 5, 7} \n arr2[] = {5, 6, 3, 4, 8} \n x = 9\nOutput : 1 8\n 4 5\n 5 4"
},
{
"code": null,
"e": 437,
"s": 420,
"text": "Asked in: Amazon"
},
{
"code": null,
"e": 591,
"s": 437,
"text": "A Naive approach is to simply run two loops and pick elements from both arrays. One by one check that both elements sum is equal to given value x or not."
},
{
"code": null,
"e": 607,
"s": 591,
"text": "Implementation:"
},
{
"code": null,
"e": 616,
"s": 607,
"text": "Chapters"
},
{
"code": null,
"e": 643,
"s": 616,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 693,
"s": 643,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 716,
"s": 693,
"text": "captions off, selected"
},
{
"code": null,
"e": 724,
"s": 716,
"text": "English"
},
{
"code": null,
"e": 748,
"s": 724,
"text": "This is a modal window."
},
{
"code": null,
"e": 817,
"s": 748,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 839,
"s": 817,
"text": "End of dialog window."
},
{
"code": null,
"e": 843,
"s": 839,
"text": "C++"
},
{
"code": null,
"e": 848,
"s": 843,
"text": "Java"
},
{
"code": null,
"e": 856,
"s": 848,
"text": "Python3"
},
{
"code": null,
"e": 859,
"s": 856,
"text": "C#"
},
{
"code": null,
"e": 863,
"s": 859,
"text": "PHP"
},
{
"code": null,
"e": 874,
"s": 863,
"text": "Javascript"
},
{
"code": "// C++ program to find all pairs in both arrays// whose sum is equal to given value x#include <bits/stdc++.h> using namespace std; // Function to print all pairs in both arrays// whose sum is equal to given value xvoid findPairs(int arr1[], int arr2[], int n, int m, int x){ for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) if (arr1[i] + arr2[j] == x) cout << arr1[i] << \" \" << arr2[j] << endl;} // Driver codeint main(){ int arr1[] = { 1, 2, 3, 7, 5, 4 }; int arr2[] = { 0, 7, 4, 3, 2, 1 }; int n = sizeof(arr1) / sizeof(int); int m = sizeof(arr2) / sizeof(int); int x = 8; findPairs(arr1, arr2, n, m, x); return 0;}",
"e": 1590,
"s": 874,
"text": null
},
{
"code": "// Java program to find all pairs in both arrays// whose sum is equal to given value ximport java.io.*; class GFG { // Function to print all pairs in both arrays // whose sum is equal to given value x static void findPairs(int arr1[], int arr2[], int n, int m, int x) { for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) if (arr1[i] + arr2[j] == x) System.out.println(arr1[i] + \" \" + arr2[j]); } // Driver code public static void main(String[] args) { int arr1[] = { 1, 2, 3, 7, 5, 4 }; int arr2[] = { 0, 7, 4, 3, 2, 1 }; int x = 8; findPairs(arr1, arr2, arr1.length, arr2.length, x); }} // This code is contributed// by sunnysingh",
"e": 2399,
"s": 1590,
"text": null
},
{
"code": "# Python 3 program to find all# pairs in both arrays whose# sum is equal to given value x # Function to print all pairs# in both arrays whose sum is# equal to given value xdef findPairs(arr1, arr2, n, m, x): for i in range(0, n): for j in range(0, m): if (arr1[i] + arr2[j] == x): print(arr1[i], arr2[j]) # Driver codearr1 = [1, 2, 3, 7, 5, 4]arr2 = [0, 7, 4, 3, 2, 1]n = len(arr1)m = len(arr2)x = 8findPairs(arr1, arr2, n, m, x) # This code is contributed by Smitha Dinesh Semwal",
"e": 2917,
"s": 2399,
"text": null
},
{
"code": "// C# program to find all// pairs in both arrays// whose sum is equal to// given value xusing System; class GFG { // Function to print all // pairs in both arrays // whose sum is equal to // given value x static void findPairs(int[] arr1, int[] arr2, int n, int m, int x) { for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) if (arr1[i] + arr2[j] == x) Console.WriteLine(arr1[i] + \" \" + arr2[j]); } // Driver code static void Main() { int[] arr1 = { 1, 2, 3, 7, 5, 4 }; int[] arr2 = { 0, 7, 4, 3, 2, 1 }; int x = 8; findPairs(arr1, arr2, arr1.Length, arr2.Length, x); }} // This code is contributed// by Sam007",
"e": 3707,
"s": 2917,
"text": null
},
{
"code": "<?php// PHP program to find all pairs// in both arrays whose sum is// equal to given value x // Function to print all pairs// in both arrays whose sum is// equal to given value xfunction findPairs($arr1, $arr2, $n, $m, $x){ for ($i = 0; $i < $n; $i++) for ($j = 0; $j < $m; $j++) if ($arr1[$i] + $arr2[$j] == $x) echo $arr1[$i] . \" \" . $arr2[$j] . \"\\n\";} // Driver code$arr1 = array(1, 2, 3, 7, 5, 4);$arr2 = array(0, 7, 4, 3, 2, 1);$n = count($arr1);$m = count($arr2);$x = 8;findPairs($arr1, $arr2, $n, $m, $x); // This code is contributed// by Sam007?>",
"e": 4345,
"s": 3707,
"text": null
},
{
"code": "<script> // Javascript program to find all pairs in both arrays// whose sum is equal to given value x // Function to print all pairs in both arrays// whose sum is equal to given value xfunction findPairs(arr1, arr2, n, m, x){ for (let i = 0; i < n; i++) for (let j = 0; j < m; j++) if (arr1[i] + arr2[j] == x) document.write(arr1[i] + \" \" + arr2[j] + \"<br>\");} // Driver code let arr1 = [ 1, 2, 3, 7, 5, 4 ]; let arr2 = [ 0, 7, 4, 3, 2, 1 ]; let n = arr1.length; let m = arr2.length; let x = 8; findPairs(arr1, arr2, n, m, x); // This code is contributed by Surbhi Tyagi. </script>",
"e": 5005,
"s": 4345,
"text": null
},
{
"code": null,
"e": 5021,
"s": 5005,
"text": "1 7\n7 1\n5 3\n4 4"
},
{
"code": null,
"e": 5069,
"s": 5021,
"text": "Time Complexity : O(n^2) Auxiliary Space : O(1)"
},
{
"code": null,
"e": 5330,
"s": 5069,
"text": "Searching Approach : As we know sorting algorithms can sort data in O (n log n) time. So we will choose a O (n log n) time algorithm like : Quick Sort or Heap Sort. For each element of second array , we will subtract it from K and search it in the first array."
},
{
"code": null,
"e": 5337,
"s": 5330,
"text": "Steps:"
},
{
"code": null,
"e": 5622,
"s": 5337,
"text": "First sort the given array using a O(n log n) algorithm like Heap Sort or Quick Sort.Run a loop for each element of array-B (0 to n).Inside the loop, use a temporary variable say temp, and temp = K – B[i].Search the temp variable in the first array i.e. A, using Binary Search(log n)."
},
{
"code": null,
"e": 5708,
"s": 5622,
"text": "First sort the given array using a O(n log n) algorithm like Heap Sort or Quick Sort."
},
{
"code": null,
"e": 5757,
"s": 5708,
"text": "Run a loop for each element of array-B (0 to n)."
},
{
"code": null,
"e": 5830,
"s": 5757,
"text": "Inside the loop, use a temporary variable say temp, and temp = K – B[i]."
},
{
"code": null,
"e": 5910,
"s": 5830,
"text": "Search the temp variable in the first array i.e. A, using Binary Search(log n)."
},
{
"code": null,
"e": 5994,
"s": 5910,
"text": "If the element is found in A then there exists a ∈ A and b ∈ B such that a + b = K."
},
{
"code": null,
"e": 6010,
"s": 5994,
"text": "Implementation:"
},
{
"code": null,
"e": 6014,
"s": 6010,
"text": "C++"
},
{
"code": null,
"e": 6019,
"s": 6014,
"text": "Java"
},
{
"code": null,
"e": 6027,
"s": 6019,
"text": "Python3"
},
{
"code": null,
"e": 6030,
"s": 6027,
"text": "C#"
},
{
"code": null,
"e": 6041,
"s": 6030,
"text": "Javascript"
},
{
"code": "#include<bits/stdc++.h>using namespace std; void heapify(int a[] , int n , int i){ int rootLargest = i; int lchild = 2 * i; int rchild = (2 * i) + 1; if (lchild < n && a[lchild] > a[rootLargest]) rootLargest = lchild; if (rchild < n && a[rchild] > a[rootLargest]) rootLargest = rchild; if (rootLargest != i) { swap(a[i] , a[rootLargest]); //Recursion heapify(a , n , rootLargest); }} int binarySearch(int a[] , int l , int r , int x){ while (l <= r) { int m = l + (r - l) / 2; if (a[m] == x) return m; if (a[m] < x) l = m + 1; else r = m - 1; } return -1;} int main(){ int A[] = {1,2,1,3,4}; int B[] = {3,1,5,1,2}; int K = 8; int n = sizeof(A) / sizeof(A[0]); // Building the heap for (int i = n / 2 - 1 ; i >= 1; i--) heapify(A , n , i); for(int i=0 ; i<n ; i++) //O(n) { int temp = K - B[i]; //O(1) if(binarySearch(A , 0 , n-1 , temp)) //O(logn) { cout<<\"\\nFound the elements.\\n\"; break; } } return 0;}",
"e": 7219,
"s": 6041,
"text": null
},
{
"code": "import java.util.*; class GFG{ static int A[] = {1,2,1,3,4}; static void heapify( int n , int i) { int rootLargest = i; int lchild = 2 * i; int rchild = (2 * i) + 1; if (lchild < n && A[lchild] > A[rootLargest]) rootLargest = lchild; if (rchild < n && A[rchild] > A[rootLargest]) rootLargest = rchild; if (rootLargest != i) { int t = A[i]; A[i] = A[rootLargest]; A[rootLargest] = t; //Recursion heapify( n , rootLargest); } } static int binarySearch( int l , int r , int x) { while (l <= r) { int m = l + (r - l) / 2; if (A[m] == x) return m; if (A[m] < x) l = m + 1; else r = m - 1; } return -1; } public static void main(String[] args) { int B[] = {3,1,5,1,2}; int K = 8; int n = A.length; // Building the heap for (int i = n / 2 - 1 ; i >= 1; i--) heapify( n , i); for(int i = 0; i < n; i++) //O(n) { int temp = K - B[i]; //O(1) if(binarySearch(0, n - 1, temp - 1) != -1) //O(logn) { System.out.print(\"\\nFound the elements.\\n\"); break; } } }} // This code is contributed by Rajput-Ji",
"e": 8448,
"s": 7219,
"text": null
},
{
"code": "A = [ 1, 2, 1, 3, 4 ]; def heapify(n, i): rootLargest = i; lchild = 2 * i; rchild = (2 * i) + 1; if (lchild < n and A[lchild] > A[rootLargest]): rootLargest = lchild; if (rchild < n and A[rchild] > A[rootLargest]): rootLargest = rchild; if (rootLargest != i): t = A[i]; A[i] = A[rootLargest]; A[rootLargest] = t; # Recursion heapify(n, rootLargest); def binarySearch(l, r, x): while (l <= r): m = l + (r - l) // 2; if (A[m] == x): return m; if (A[m] < x): l = m + 1; else: r = m - 1; return -1; if __name__ == '__main__': B = [ 3, 1, 5, 1, 2 ]; K = 8; n = len(A); # Building the heap for i in range(n// 2 - 1,0, -1): heapify(n, i); for i in range(n): temp = K - B[i]; if (binarySearch(0, n - 1, temp - 1) != -1): print(\"\\nFound the elements.\"); break; # This code is contributed by Rajput-Ji",
"e": 9469,
"s": 8448,
"text": null
},
{
"code": "using System;public class GFG { static int []A = { 1, 2, 1, 3, 4 }; static void heapify(int n, int i) { int rootLargest = i; int lchild = 2 * i; int rchild = (2 * i) + 1; if (lchild < n && A[lchild] > A[rootLargest]) rootLargest = lchild; if (rchild < n && A[rchild] > A[rootLargest]) rootLargest = rchild; if (rootLargest != i) { int t = A[i]; A[i] = A[rootLargest]; A[rootLargest] = t; // Recursion heapify(n, rootLargest); } } static int binarySearch(int l, int r, int x) { while (l <= r) { int m = l + (r - l) / 2; if (A[m] == x) return m; if (A[m] < x) l = m + 1; else r = m - 1; } return -1; } public static void Main(String[] args) { int []B = { 3, 1, 5, 1, 2 }; int K = 8; int n = A.Length; // Building the heap for (int i = n / 2 - 1; i >= 1; i--) heapify(n, i); for (int i = 0; i < n; i++) // O(n) { int temp = K - B[i]; // O(1) if (binarySearch(0, n - 1, temp - 1) != -1) // O(logn) { Console.Write(\"\\nFound the elements.\\n\"); break; } } }} // This code is contributed by Rajput-Ji",
"e": 10651,
"s": 9469,
"text": null
},
{
"code": "<script>function heapify(a,n,i){ let rootLargest = i; let lchild = 2 * i; let rchild = (2 * i) + 1; if (lchild < n && a[lchild] > a[rootLargest]) rootLargest = lchild; if (rchild < n && a[rchild] > a[rootLargest]) rootLargest = rchild; if (rootLargest != i) { swap(a[i] , a[rootLargest]); //Recursion heapify(a , n , rootLargest); }} function binarySearch(a,l,r,x){ while (l <= r) { let m = l + (r - l) / 2; if (a[m] == x) return m; if (a[m] < x) l = m + 1; else r = m - 1; } return -1;} let A = [1,2,1,3,4]; let B = [3,1,5,1,2]; let K = 8; let n = A.length; // Building the heap for (let i = n / 2 - 1 ; i >= 1; i--) heapify(A , n , i); for(let i=0 ; i<n ; i++) //O(n) { let temp = K - B[i]; //O(1) if(binarySearch(A , 0 , n-1 , temp)) //O(logn) { document.write(\"\\nFound the elements.\\n\"); break; } } </script>",
"e": 11724,
"s": 10651,
"text": null
},
{
"code": null,
"e": 11744,
"s": 11724,
"text": "Found the elements."
},
{
"code": null,
"e": 11772,
"s": 11744,
"text": "Time Complexity: O(n logn)."
},
{
"code": null,
"e": 11791,
"s": 11772,
"text": "O(log n + n log n)"
},
{
"code": null,
"e": 11832,
"s": 11791,
"text": "So, Overall time complexity = O(n logn)."
},
{
"code": null,
"e": 11940,
"s": 11832,
"text": "An Efficient solution of this problem is to hashing. Hash table is implemented using unordered_set in C++. "
},
{
"code": null,
"e": 11989,
"s": 11940,
"text": "We store all first array elements in hash table."
},
{
"code": null,
"e": 12088,
"s": 11989,
"text": "For elements of second array, we subtract every element from x and check the result in hash table."
},
{
"code": null,
"e": 12185,
"s": 12088,
"text": "If result is present, we print the element and key in hash (which is an element of first array)."
},
{
"code": null,
"e": 12201,
"s": 12185,
"text": "Implementation:"
},
{
"code": null,
"e": 12205,
"s": 12201,
"text": "C++"
},
{
"code": null,
"e": 12210,
"s": 12205,
"text": "Java"
},
{
"code": null,
"e": 12218,
"s": 12210,
"text": "Python3"
},
{
"code": null,
"e": 12221,
"s": 12218,
"text": "C#"
},
{
"code": null,
"e": 12232,
"s": 12221,
"text": "Javascript"
},
{
"code": "// C++ program to find all pair in both arrays// whose sum is equal to given value x#include <bits/stdc++.h>using namespace std; // Function to find all pairs in both arrays// whose sum is equal to given value xvoid findPairs(int arr1[], int arr2[], int n, int m, int x){ // Insert all elements of first array in a hash unordered_set<int> s; for (int i = 0; i < n; i++) s.insert(arr1[i]); // Subtract sum from second array elements one // by one and check it's present in array first // or not for (int j = 0; j < m; j++) if (s.find(x - arr2[j]) != s.end()) cout << x - arr2[j] << \" \" << arr2[j] << endl;} // Driver codeint main(){ int arr1[] = { 1, 0, -4, 7, 6, 4 }; int arr2[] = { 0, 2, 4, -3, 2, 1 }; int x = 8; int n = sizeof(arr1) / sizeof(int); int m = sizeof(arr2) / sizeof(int); findPairs(arr1, arr2, n, m, x); return 0;}",
"e": 13160,
"s": 12232,
"text": null
},
{
"code": "// JAVA Code for Given two unsorted arrays,// find all pairs whose sum is ximport java.util.*; class GFG { // Function to find all pairs in both arrays // whose sum is equal to given value x public static void findPairs(int arr1[], int arr2[], int n, int m, int x) { // Insert all elements of first array in a hash HashMap<Integer, Integer> s = new HashMap<Integer, Integer>(); for (int i = 0; i < n; i++) s.put(arr1[i], 0); // Subtract sum from second array elements one // by one and check it's present in array first // or not for (int j = 0; j < m; j++) if (s.containsKey(x - arr2[j])) System.out.println(x - arr2[j] + \" \" + arr2[j]); } /* Driver program to test above function */ public static void main(String[] args) { int arr1[] = { 1, 0, -4, 7, 6, 4 }; int arr2[] = { 0, 2, 4, -3, 2, 1 }; int x = 8; findPairs(arr1, arr2, arr1.length, arr2.length, x); }}// This code is contributed by Arnav Kr. Mandal.",
"e": 14250,
"s": 13160,
"text": null
},
{
"code": "# Python3 program to find all# pair in both arrays whose# sum is equal to given value x # Function to find all pairs# in both arrays whose sum is# equal to given value xdef findPairs(arr1, arr2, n, m, x): # Insert all elements of # first array in a hash s = set() for i in range (0, n): s.add(arr1[i]) # Subtract sum from second # array elements one by one # and check it's present in # array first or not for j in range(0, m): if ((x - arr2[j]) in s): print((x - arr2[j]), '', arr2[j]) # Driver codearr1 = [1, 0, -4, 7, 6, 4]arr2 = [0, 2, 4, -3, 2, 1]x = 8 n = len(arr1)m = len(arr2)findPairs(arr1, arr2, n, m, x) # This code is contributed# by ihritik",
"e": 14958,
"s": 14250,
"text": null
},
{
"code": "// C# Code for Given two unsorted arrays,// find all pairs whose sum is xusing System;using System.Collections.Generic; class GFG { // Function to find all pairs in // both arrays whose sum is equal // to given value x public static void findPairs(int[] arr1, int[] arr2, int n, int m, int x) { // Insert all elements of first // array in a hash Dictionary<int, int> s = new Dictionary<int, int>(); for (int i = 0; i < n; i++) { s[arr1[i]] = 0; } // Subtract sum from second array // elements one by one and check // it's present in array first // or not for (int j = 0; j < m; j++) { if (s.ContainsKey(x - arr2[j])) { Console.WriteLine(x - arr2[j] + \" \" + arr2[j]); } } } // Driver Code public static void Main(string[] args) { int[] arr1 = new int[] { 1, 0, -4, 7, 6, 4 }; int[] arr2 = new int[] { 0, 2, 4, -3, 2, 1 }; int x = 8; findPairs(arr1, arr2, arr1.Length, arr2.Length, x); }} // This code is contributed by Shrikant13",
"e": 16183,
"s": 14958,
"text": null
},
{
"code": "<script> // Javascript Code for Given two unsorted arrays,// find all pairs whose sum is x // Function to find all pairs in both arrays // whose sum is equal to given value x function findPairs(arr1, arr2, n, m, x) { // Insert all elements of first array in a hash let s = new Map(); for (let i = 0; i < n; i++) s.set(arr1[i], 0); // Subtract sum from second array elements one // by one and check it's present in array first // or not for (let j = 0; j < m; j++) if (s.has(x - arr2[j])) document.write(x - arr2[j] + \" \" + arr2[j] + \"<br/>\"); } // Driver code let arr1 = [ 1, 0, -4, 7, 6, 4 ]; let arr2 = [ 0, 2, 4, -3, 2, 1 ]; let x = 8; findPairs(arr1, arr2, arr1.length, arr2.length, x); </script>",
"e": 17034,
"s": 16183,
"text": null
},
{
"code": null,
"e": 17050,
"s": 17034,
"text": "6 2\n4 4\n6 2\n7 1"
},
{
"code": null,
"e": 17102,
"s": 17050,
"text": "Time Complexity: O(max(n, m)) Auxiliary Space: O(n)"
},
{
"code": null,
"e": 17399,
"s": 17102,
"text": "This article is contributed by DANISH_RAZA . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. "
},
{
"code": null,
"e": 17406,
"s": 17399,
"text": "Sam007"
},
{
"code": null,
"e": 17418,
"s": 17406,
"text": "namankatuva"
},
{
"code": null,
"e": 17426,
"s": 17418,
"text": "ihritik"
},
{
"code": null,
"e": 17438,
"s": 17426,
"text": "shrikanth13"
},
{
"code": null,
"e": 17453,
"s": 17438,
"text": "Mayuri Gupta 4"
},
{
"code": null,
"e": 17459,
"s": 17453,
"text": "sp999"
},
{
"code": null,
"e": 17476,
"s": 17459,
"text": "RishabhAgnihotri"
},
{
"code": null,
"e": 17490,
"s": 17476,
"text": "surbhityagi15"
},
{
"code": null,
"e": 17502,
"s": 17490,
"text": "imsushant12"
},
{
"code": null,
"e": 17519,
"s": 17502,
"text": "avijitmondal1998"
},
{
"code": null,
"e": 17536,
"s": 17519,
"text": "vaibhavrabadiya3"
},
{
"code": null,
"e": 17546,
"s": 17536,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 17563,
"s": 17546,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 17570,
"s": 17563,
"text": "Amazon"
},
{
"code": null,
"e": 17579,
"s": 17570,
"text": "Facebook"
},
{
"code": null,
"e": 17586,
"s": 17579,
"text": "Arrays"
},
{
"code": null,
"e": 17591,
"s": 17586,
"text": "Hash"
},
{
"code": null,
"e": 17598,
"s": 17591,
"text": "Amazon"
},
{
"code": null,
"e": 17607,
"s": 17598,
"text": "Facebook"
},
{
"code": null,
"e": 17614,
"s": 17607,
"text": "Arrays"
},
{
"code": null,
"e": 17619,
"s": 17614,
"text": "Hash"
},
{
"code": null,
"e": 17717,
"s": 17619,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 17785,
"s": 17717,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 17829,
"s": 17785,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 17861,
"s": 17829,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 17909,
"s": 17861,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 17923,
"s": 17909,
"text": "Linear Search"
},
{
"code": null,
"e": 17961,
"s": 17923,
"text": "What is Hashing | A Complete Tutorial"
},
{
"code": null,
"e": 17997,
"s": 17961,
"text": "Internal Working of HashMap in Java"
},
{
"code": null,
"e": 18028,
"s": 17997,
"text": "Hashing | Set 1 (Introduction)"
},
{
"code": null,
"e": 18060,
"s": 18028,
"text": "Longest Consecutive Subsequence"
}
]
|
Raw String Literal in C++ | 22 May, 2022
A Literal is a constant variable whose value does not change during the lifetime of the program. Whereas, a raw string literal is a string in which the escape characters like ‘ \n, \t, or \” ‘ of C++ are not processed. Hence, a raw string literal that starts with R”( and ends in )”.
The syntax for Raw string Literal:
R "delimiter( raw_characters )delimiter" // delimiter is the end of logical entity
Here, delimiter is optional and it can be a character except the backslash{ / }, whitespaces{ }, and parentheses { () }.
These raw string literals allow a series of characters by writing precisely its contents like raw character sequence.
Example:
Ordinary String Literal
"\\\\n"
Raw String Literal
\/-- Delimiter
R"(\\n)"
/\-- Delimiter
Difference between an Ordinary String Literal and a Raw String Literal:
Example of Raw String Literal:
CPP
// C++ program to demonstrate working of raw string literal#include <iostream>using namespace std; // Driver Codeint main(){ // A Normal string string string1 = "Geeks.\nFor.\nGeeks.\n"; // A Raw string string string2 = R"(Geeks.\nFor.\nGeeks.\n)"; cout << string1 << endl; cout << string2 << endl; return 0;}
Geeks.
For.
Geeks.
Geeks.\nFor.\nGeeks.\n
This article is contributed by MAZHAR IMAM KHAN. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.
Akanksha_Rai
anshikajain26
harsh_shokeen
cpp-string
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Vector in C++ STL
Initialize a vector in C++ (7 different ways)
std::sort() in C++ STL
Bitwise Operators in C/C++
vector erase() and clear() in C++
Substring in C++
unordered_map in C++ STL
Sorting a vector in C++
2D Vector In C++ With User Defined Size
Virtual Function in C++ | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n22 May, 2022"
},
{
"code": null,
"e": 336,
"s": 52,
"text": "A Literal is a constant variable whose value does not change during the lifetime of the program. Whereas, a raw string literal is a string in which the escape characters like ‘ \\n, \\t, or \\” ‘ of C++ are not processed. Hence, a raw string literal that starts with R”( and ends in )”."
},
{
"code": null,
"e": 371,
"s": 336,
"text": "The syntax for Raw string Literal:"
},
{
"code": null,
"e": 454,
"s": 371,
"text": "R \"delimiter( raw_characters )delimiter\" // delimiter is the end of logical entity"
},
{
"code": null,
"e": 576,
"s": 454,
"text": "Here, delimiter is optional and it can be a character except the backslash{ / }, whitespaces{ }, and parentheses { () }."
},
{
"code": null,
"e": 695,
"s": 576,
"text": "These raw string literals allow a series of characters by writing precisely its contents like raw character sequence. "
},
{
"code": null,
"e": 704,
"s": 695,
"text": "Example:"
},
{
"code": null,
"e": 729,
"s": 704,
"text": "Ordinary String Literal "
},
{
"code": null,
"e": 737,
"s": 729,
"text": "\"\\\\\\\\n\""
},
{
"code": null,
"e": 757,
"s": 737,
"text": "Raw String Literal "
},
{
"code": null,
"e": 803,
"s": 757,
"text": " \\/-- Delimiter\nR\"(\\\\n)\"\n /\\-- Delimiter"
},
{
"code": null,
"e": 875,
"s": 803,
"text": "Difference between an Ordinary String Literal and a Raw String Literal:"
},
{
"code": null,
"e": 906,
"s": 875,
"text": "Example of Raw String Literal:"
},
{
"code": null,
"e": 910,
"s": 906,
"text": "CPP"
},
{
"code": "// C++ program to demonstrate working of raw string literal#include <iostream>using namespace std; // Driver Codeint main(){ // A Normal string string string1 = \"Geeks.\\nFor.\\nGeeks.\\n\"; // A Raw string string string2 = R\"(Geeks.\\nFor.\\nGeeks.\\n)\"; cout << string1 << endl; cout << string2 << endl; return 0;}",
"e": 1245,
"s": 910,
"text": null
},
{
"code": null,
"e": 1288,
"s": 1245,
"text": "Geeks.\nFor.\nGeeks.\n\nGeeks.\\nFor.\\nGeeks.\\n"
},
{
"code": null,
"e": 1717,
"s": 1288,
"text": "This article is contributed by MAZHAR IMAM KHAN. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 1730,
"s": 1717,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 1744,
"s": 1730,
"text": "anshikajain26"
},
{
"code": null,
"e": 1758,
"s": 1744,
"text": "harsh_shokeen"
},
{
"code": null,
"e": 1769,
"s": 1758,
"text": "cpp-string"
},
{
"code": null,
"e": 1773,
"s": 1769,
"text": "C++"
},
{
"code": null,
"e": 1777,
"s": 1773,
"text": "CPP"
},
{
"code": null,
"e": 1875,
"s": 1777,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1893,
"s": 1875,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 1939,
"s": 1893,
"text": "Initialize a vector in C++ (7 different ways)"
},
{
"code": null,
"e": 1962,
"s": 1939,
"text": "std::sort() in C++ STL"
},
{
"code": null,
"e": 1989,
"s": 1962,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 2023,
"s": 1989,
"text": "vector erase() and clear() in C++"
},
{
"code": null,
"e": 2040,
"s": 2023,
"text": "Substring in C++"
},
{
"code": null,
"e": 2065,
"s": 2040,
"text": "unordered_map in C++ STL"
},
{
"code": null,
"e": 2089,
"s": 2065,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 2129,
"s": 2089,
"text": "2D Vector In C++ With User Defined Size"
}
]
|
How to align navbar items to the right in Bootstrap 4 ? | 02 Mar, 2020
The .ml-auto class in Bootstrap can be used to align navbar items to the right. The .ml-auto class automatically aligns elements to the right. In this article, we will align the navbar to the right in two different ways, below both the approaches are discussed with proper example.
Example 1: In the first example, we use the .ml-auto class of Bootstrap 4 to align navbar items to the right. The .ml-auto class automatically gives a left margin and shifts navbar items to the right.
Program:<!DOCTYPE html><html> <head> <!-- Including the bootstrap CDN --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"> </script></head> <body> <!-- Creating a navigation bar using the .navbar class of bootstrap --> <nav class="navbar navbar-expand-sm bg-light"> <ul class="navbar-nav ml-auto"> <li class="nav-item"> <a class="nav-link" href="#"> About </a> </li> <li class="nav-item"> <a class="nav-link" href="#"> Contacts </a> </li> <li class="nav-item"> <a class="nav-link" href="#"> Settings </a> </li> </ul> </nav></body> </html>
<!DOCTYPE html><html> <head> <!-- Including the bootstrap CDN --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"> </script></head> <body> <!-- Creating a navigation bar using the .navbar class of bootstrap --> <nav class="navbar navbar-expand-sm bg-light"> <ul class="navbar-nav ml-auto"> <li class="nav-item"> <a class="nav-link" href="#"> About </a> </li> <li class="nav-item"> <a class="nav-link" href="#"> Contacts </a> </li> <li class="nav-item"> <a class="nav-link" href="#"> Settings </a> </li> </ul> </nav></body> </html>
Output:
Example 2: In this example, we do not use any pre-defined Bootstrap 4 class to align the items. In this example, we create a navbar and then using CSS gives the left margin as an auto which shifts the navbar items to the right.
Program:<!DOCTYPE html><html> <head> <!-- Including the bootstrap CDN --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"> </script> <style> .navbar-nav { margin-left: auto; } </style></head> <body> <!-- Creating a navigation bar using the .navbar class of bootstrap --> <nav class="navbar navbar-expand-sm bg-light"> <ul class="navbar-nav"> <li class="nav-item"> <a class="nav-link" href="#"> About </a> </li> <li class="nav-item"> <a class="nav-link" href="#"> Contacts </a> </li> <li class="nav-item"> <a class="nav-link" href="#"> Settings </a> </li> </ul> </nav></body> </html>
<!DOCTYPE html><html> <head> <!-- Including the bootstrap CDN --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"> </script> <style> .navbar-nav { margin-left: auto; } </style></head> <body> <!-- Creating a navigation bar using the .navbar class of bootstrap --> <nav class="navbar navbar-expand-sm bg-light"> <ul class="navbar-nav"> <li class="nav-item"> <a class="nav-link" href="#"> About </a> </li> <li class="nav-item"> <a class="nav-link" href="#"> Contacts </a> </li> <li class="nav-item"> <a class="nav-link" href="#"> Settings </a> </li> </ul> </nav></body> </html>
Output:
Bootstrap-4
Picked
Bootstrap
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Show Images on Click using HTML ?
How to set Bootstrap Timepicker using datetimepicker library ?
How to Use Bootstrap with React?
How to make Bootstrap table with sticky table head?
How to set vertical alignment in Bootstrap ?
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ? | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n02 Mar, 2020"
},
{
"code": null,
"e": 335,
"s": 53,
"text": "The .ml-auto class in Bootstrap can be used to align navbar items to the right. The .ml-auto class automatically aligns elements to the right. In this article, we will align the navbar to the right in two different ways, below both the approaches are discussed with proper example."
},
{
"code": null,
"e": 536,
"s": 335,
"text": "Example 1: In the first example, we use the .ml-auto class of Bootstrap 4 to align navbar items to the right. The .ml-auto class automatically gives a left margin and shifts navbar items to the right."
},
{
"code": null,
"e": 1670,
"s": 536,
"text": "Program:<!DOCTYPE html><html> <head> <!-- Including the bootstrap CDN --> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js\"> </script></head> <body> <!-- Creating a navigation bar using the .navbar class of bootstrap --> <nav class=\"navbar navbar-expand-sm bg-light\"> <ul class=\"navbar-nav ml-auto\"> <li class=\"nav-item\"> <a class=\"nav-link\" href=\"#\"> About </a> </li> <li class=\"nav-item\"> <a class=\"nav-link\" href=\"#\"> Contacts </a> </li> <li class=\"nav-item\"> <a class=\"nav-link\" href=\"#\"> Settings </a> </li> </ul> </nav></body> </html>"
},
{
"code": "<!DOCTYPE html><html> <head> <!-- Including the bootstrap CDN --> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js\"> </script></head> <body> <!-- Creating a navigation bar using the .navbar class of bootstrap --> <nav class=\"navbar navbar-expand-sm bg-light\"> <ul class=\"navbar-nav ml-auto\"> <li class=\"nav-item\"> <a class=\"nav-link\" href=\"#\"> About </a> </li> <li class=\"nav-item\"> <a class=\"nav-link\" href=\"#\"> Contacts </a> </li> <li class=\"nav-item\"> <a class=\"nav-link\" href=\"#\"> Settings </a> </li> </ul> </nav></body> </html>",
"e": 2796,
"s": 1670,
"text": null
},
{
"code": null,
"e": 2804,
"s": 2796,
"text": "Output:"
},
{
"code": null,
"e": 3032,
"s": 2804,
"text": "Example 2: In this example, we do not use any pre-defined Bootstrap 4 class to align the items. In this example, we create a navbar and then using CSS gives the left margin as an auto which shifts the navbar items to the right."
},
{
"code": null,
"e": 4241,
"s": 3032,
"text": "Program:<!DOCTYPE html><html> <head> <!-- Including the bootstrap CDN --> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js\"> </script> <style> .navbar-nav { margin-left: auto; } </style></head> <body> <!-- Creating a navigation bar using the .navbar class of bootstrap --> <nav class=\"navbar navbar-expand-sm bg-light\"> <ul class=\"navbar-nav\"> <li class=\"nav-item\"> <a class=\"nav-link\" href=\"#\"> About </a> </li> <li class=\"nav-item\"> <a class=\"nav-link\" href=\"#\"> Contacts </a> </li> <li class=\"nav-item\"> <a class=\"nav-link\" href=\"#\"> Settings </a> </li> </ul> </nav></body> </html>"
},
{
"code": "<!DOCTYPE html><html> <head> <!-- Including the bootstrap CDN --> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js\"> </script> <style> .navbar-nav { margin-left: auto; } </style></head> <body> <!-- Creating a navigation bar using the .navbar class of bootstrap --> <nav class=\"navbar navbar-expand-sm bg-light\"> <ul class=\"navbar-nav\"> <li class=\"nav-item\"> <a class=\"nav-link\" href=\"#\"> About </a> </li> <li class=\"nav-item\"> <a class=\"nav-link\" href=\"#\"> Contacts </a> </li> <li class=\"nav-item\"> <a class=\"nav-link\" href=\"#\"> Settings </a> </li> </ul> </nav></body> </html>",
"e": 5442,
"s": 4241,
"text": null
},
{
"code": null,
"e": 5450,
"s": 5442,
"text": "Output:"
},
{
"code": null,
"e": 5462,
"s": 5450,
"text": "Bootstrap-4"
},
{
"code": null,
"e": 5469,
"s": 5462,
"text": "Picked"
},
{
"code": null,
"e": 5479,
"s": 5469,
"text": "Bootstrap"
},
{
"code": null,
"e": 5496,
"s": 5479,
"text": "Web Technologies"
},
{
"code": null,
"e": 5523,
"s": 5496,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 5621,
"s": 5523,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5662,
"s": 5621,
"text": "How to Show Images on Click using HTML ?"
},
{
"code": null,
"e": 5725,
"s": 5662,
"text": "How to set Bootstrap Timepicker using datetimepicker library ?"
},
{
"code": null,
"e": 5758,
"s": 5725,
"text": "How to Use Bootstrap with React?"
},
{
"code": null,
"e": 5810,
"s": 5758,
"text": "How to make Bootstrap table with sticky table head?"
},
{
"code": null,
"e": 5855,
"s": 5810,
"text": "How to set vertical alignment in Bootstrap ?"
},
{
"code": null,
"e": 5888,
"s": 5855,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 5950,
"s": 5888,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 6011,
"s": 5950,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 6061,
"s": 6011,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
]
|
Detecting negative cycle using Floyd Warshall | 24 Nov, 2021
We are given a directed graph. We need compute whether the graph has negative cycle or not. A negative cycle is one in which the overall sum of the cycle comes negative.
Negative weights are found in various applications of graphs. For example, instead of paying cost for a path, we may get some advantage if we follow the path.Examples:
Input : 4 4
0 1 1
1 2 -1
2 3 -1
3 0 -1
Output : Yes
The graph contains a negative cycle.
We have discussed Bellman Ford Algorithm based solution for this problem.In this post, Floyd Warshall Algorithm based solution is discussed that works for both connected and disconnected graphs.Distance of any node from itself is always zero. But in some cases, as in this example, when we traverse further from 4 to 1, the distance comes out to be -2, i.e. distance of 1 from 1 will become -2. This is our catch, we just have to check the nodes distance from itself and if it comes out to be negative, we will detect the required negative cycle.
C++
Java
Python3
C#
Javascript
// C++ Program to check if there is a negative weight// cycle using Floyd Warshall Algorithm#include<bits/stdc++.h>using namespace std; // Number of vertices in the graph#define V 4 /* Define Infinite as a large enough value. This value will be used for vertices not connected to each other */#define INF 99999 // A function to print the solution matrixvoid printSolution(int dist[][V]); // Returns true if graph has negative weight cycle// else false.bool negCyclefloydWarshall(int graph[][V]){ /* dist[][] will be the output matrix that will finally have the shortest distances between every pair of vertices */ int dist[V][V], i, j, k; /* Initialize the solution matrix same as input graph matrix. Or we can say the initial values of shortest distances are based on shortest paths considering no intermediate vertex. */ for (i = 0; i < V; i++) for (j = 0; j < V; j++) dist[i][j] = graph[i][j]; /* Add all vertices one by one to the set of intermediate vertices. ---> Before start of a iteration, we have shortest distances between all pairs of vertices such that the shortest distances consider only the vertices in set {0, 1, 2, .. k-1} as intermediate vertices. ----> After the end of a iteration, vertex no. k is added to the set of intermediate vertices and the set becomes {0, 1, 2, .. k} */ for (k = 0; k < V; k++) { // Pick all vertices as source one by one for (i = 0; i < V; i++) { // Pick all vertices as destination for the // above picked source for (j = 0; j < V; j++) { // If vertex k is on the shortest path from // i to j, then update the value of dist[i][j] if (dist[i][k] + dist[k][j] < dist[i][j]) dist[i][j] = dist[i][k] + dist[k][j]; } } } // If distance of any vertex from itself // becomes negative, then there is a negative // weight cycle. for (int i = 0; i < V; i++) if (dist[i][i] < 0) return true; return false; } // driver programint main(){ /* Let us create the following weighted graph 1 (0)----------->(1) /|\ | | | -1 | | -1 | \|/ (3)<-----------(2) -1 */ int graph[V][V] = { {0 , 1 , INF , INF}, {INF , 0 , -1 , INF}, {INF , INF , 0 , -1}, {-1 , INF , INF , 0}}; if (negCyclefloydWarshall(graph)) cout << "Yes"; else cout << "No"; return 0;}
// Java Program to check if there is a negative weight// cycle using Floyd Warshall Algorithmclass GFG{ // Number of vertices in the graph static final int V = 4; /* Define Infinite as a large enough value. This value will be used for vertices not connected to each other */ static final int INF = 99999; // Returns true if graph has negative weight cycle // else false. static boolean negCyclefloydWarshall(int graph[][]) { /* dist[][] will be the output matrix that will finally have the shortest distances between every pair of vertices */ int dist[][] = new int[V][V], i, j, k; /* Initialize the solution matrix same as input graph matrix. Or we can say the initial values of shortest distances are based on shortest paths considering no intermediate vertex. */ for (i = 0; i < V; i++) for (j = 0; j < V; j++) dist[i][j] = graph[i][j]; /* Add all vertices one by one to the set of intermediate vertices. ---> Before start of a iteration, we have shortest distances between all pairs of vertices such that the shortest distances consider only the vertices in set {0, 1, 2, .. k-1} as intermediate vertices. ----> After the end of a iteration, vertex no. k is added to the set of intermediate vertices and the set becomes {0, 1, 2, .. k} */ for (k = 0; k < V; k++) { // Pick all vertices as source one by one for (i = 0; i < V; i++) { // Pick all vertices as destination for the // above picked source for (j = 0; j < V; j++) { // If vertex k is on the shortest path from // i to j, then update the value of dist[i][j] if (dist[i][k] + dist[k][j] < dist[i][j]) dist[i][j] = dist[i][k] + dist[k][j]; } } } // If distance of any vertex from itself // becomes negative, then there is a negative // weight cycle. for (i = 0; i < V; i++) if (dist[i][i] < 0) return true; return false; } // Driver code public static void main (String[] args) { /* Let us create the following weighted graph 1 (0)----------->(1) /|\ | | | -1 | | -1 | \|/ (3)<-----------(2) -1 */ int graph[][] = { {0, 1, INF, INF}, {INF, 0, -1, INF}, {INF, INF, 0, -1}, {-1, INF, INF, 0}}; if (negCyclefloydWarshall(graph)) System.out.print("Yes"); else System.out.print("No"); }} // This code is contributed by Anant Agarwal.
# Python Program to check# if there is a# negative weight# cycle using Floyd# Warshall Algorithm # Number of vertices# in the graphV = 4 # Define Infinite as a# large enough value. This # value will be used #for vertices not connected # to each other INF = 99999 # Returns true if graph has# negative weight cycle# else false.def negCyclefloydWarshall(graph): # dist[][] will be the # output matrix that will # finally have the shortest # distances between every # pair of vertices dist=[[0 for i in range(V+1)]for j in range(V+1)] # Initialize the solution # matrix same as input # graph matrix. Or we can # say the initial values # of shortest distances # are based on shortest # paths considering no # intermediate vertex. for i in range(V): for j in range(V): dist[i][j] = graph[i][j] ''' Add all vertices one by one to the set of intermediate vertices. ---> Before start of a iteration, we have shortest distances between all pairs of vertices such that the shortest distances consider only the vertices in set {0, 1, 2, .. k-1} as intermediate vertices. ----> After the end of a iteration, vertex no. k is added to the set of intermediate vertices and the set becomes {0, 1, 2, .. k} ''' for k in range(V): # Pick all vertices # as source one by one for i in range(V): # Pick all vertices as # destination for the # above picked source for j in range(V): # If vertex k is on # the shortest path from # i to j, then update # the value of dist[i][j] if (dist[i][k] + dist[k][j] < dist[i][j]): dist[i][j] = dist[i][k] + dist[k][j] # If distance of any # vertex from itself # becomes negative, then # there is a negative # weight cycle. for i in range(V): if (dist[i][i] < 0): return True return False # Driver code ''' Let us create the following weighted graph 1 (0)----------->(1) /|\ | | | -1 | | -1 | \|/ (3)<-----------(2) -1 ''' graph = [ [0, 1, INF, INF], [INF, 0, -1, INF], [INF, INF, 0, -1], [-1, INF, INF, 0]] if (negCyclefloydWarshall(graph)): print("Yes")else: print("No") # This code is contributed# by Anant Agarwal.
// C# Program to check if there// is a negative weight cycle// using Floyd Warshall Algorithm using System; namespace Cycle{public class GFG{ // Number of vertices in the graph static int V = 4; /* Define Infinite as a large enough value. This value will be used for vertices not connected to each other */ static int INF = 99999; // Returns true if graph has negative weight cycle // else false. static bool negCyclefloydWarshall(int [,]graph) { /* dist[][] will be the output matrix that will finally have the shortest distances between every pair of vertices */ int [,]dist = new int[V,V]; int i, j, k; /* Initialize the solution matrix same as input graph matrix. Or we can say the initial values of shortest distances are based on shortest paths considering no intermediate vertex. */ for (i = 0; i < V; i++) for (j = 0; j < V; j++) dist[i,j] = graph[i,j]; /* Add all vertices one by one to the set of intermediate vertices. ---> Before start of a iteration, we have shortest distances between all pairs of vertices such that the shortest distances consider only the vertices in set {0, 1, 2, .. k-1} as intermediate vertices. ----> After the end of a iteration, vertex no. k is added to the set of intermediate vertices and the set becomes {0, 1, 2, .. k} */ for (k = 0; k < V; k++) { // Pick all vertices as source one by one for (i = 0; i < V; i++) { // Pick all vertices as destination for the // above picked source for (j = 0; j < V; j++) { // If vertex k is on the shortest path from // i to j, then update the value of dist[i][j] if (dist[i,k] + dist[k,j] < dist[i,j]) dist[i,j] = dist[i,k] + dist[k,j]; } } } // If distance of any vertex from itself // becomes negative, then there is a negative // weight cycle. for (i = 0; i < V; i++) if (dist[i,i] < 0) return true; return false; } // Driver code public static void Main() { /* Let us create the following weighted graph 1 (0)----------->(1) /|\ | | | -1 | | -1 | \|/ (3)<-----------(2) -1 */ int [,]graph = { {0, 1, INF, INF}, {INF, 0, -1, INF}, {INF, INF, 0, -1}, {-1, INF, INF, 0}}; if (negCyclefloydWarshall(graph)) Console.Write("Yes"); else Console.Write("No"); }} } // This code is contributed by Sam007.
<script> // JavaScript Program to check if there// is a negative weight cycle// using Floyd Warshall Algorithm// Number of vertices in the graphvar V = 4; /* Define Infinite as a large enough value. This value will be used for vertices not connected to each other */var INF = 99999; // Returns true if graph has negative weight cycle// else false.function negCyclefloydWarshall(graph){ /* dist[][] will be the output matrix that will finally have the shortest distances between every pair of vertices */ var dist = Array.from(Array(V), ()=>Array(V)); var i, j, k; /* Initialize the solution matrix same as input graph matrix. Or we can say the initial values of shortest distances are based on shortest paths considering no intermediate vertex. */ for (i = 0; i < V; i++) for (j = 0; j < V; j++) dist[i][j] = graph[i][j]; /* Add all vertices one by one to the set of intermediate vertices. ---> Before start of a iteration, we have shortest distances between all pairs of vertices such that the shortest distances consider only the vertices in set {0, 1, 2, .. k-1} as intermediate vertices. ----> After the end of a iteration, vertex no. k is added to the set of intermediate vertices and the set becomes {0, 1, 2, .. k} */ for (k = 0; k < V; k++) { // Pick all vertices as source one by one for (i = 0; i < V; i++) { // Pick all vertices as destination for the // above picked source for (j = 0; j < V; j++) { // If vertex k is on the shortest path from // i to j, then update the value of dist[i][j] if (dist[i][k] + dist[k][j] < dist[i][j]) dist[i][j] = dist[i][k] + dist[k][j]; } } } // If distance of any vertex from itself // becomes negative, then there is a negative // weight cycle. for (i = 0; i < V; i++) if (dist[i][i] < 0) return true; return false; } // Driver code /* Let us create the following weighted graph 1 (0)----------->(1) /|\ | | |-1 | | -1 | \|/ (3)<-----------(2) -1 */ var graph = [ [0, 1, INF, INF], [INF, 0, -1, INF], [INF, INF, 0, -1], [-1, INF, INF, 0]]; if (negCyclefloydWarshall(graph)) document.write("Yes");else document.write("No"); </script>
Output:
Yes
This article is contributed by Shivani Mittal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
itsok
surinderdawra388
graph-cycle
Graph
Graph
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Dijkstra's shortest path algorithm | Greedy Algo-7
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Detect Cycle in a Directed Graph
Find if there is a path between two vertices in a directed graph
Introduction to Data Structures
What is Data Structure: Types, Classifications and Applications
Bellman–Ford Algorithm | DP-23
Find if there is a path between two vertices in an undirected graph
Minimum number of swaps required to sort an array
Minimum steps to reach target by a Knight | Set 1 | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n24 Nov, 2021"
},
{
"code": null,
"e": 222,
"s": 52,
"text": "We are given a directed graph. We need compute whether the graph has negative cycle or not. A negative cycle is one in which the overall sum of the cycle comes negative."
},
{
"code": null,
"e": 391,
"s": 222,
"text": "Negative weights are found in various applications of graphs. For example, instead of paying cost for a path, we may get some advantage if we follow the path.Examples: "
},
{
"code": null,
"e": 513,
"s": 391,
"text": "Input : 4 4\n 0 1 1\n 1 2 -1\n 2 3 -1\n 3 0 -1\n\nOutput : Yes\nThe graph contains a negative cycle."
},
{
"code": null,
"e": 1063,
"s": 515,
"text": "We have discussed Bellman Ford Algorithm based solution for this problem.In this post, Floyd Warshall Algorithm based solution is discussed that works for both connected and disconnected graphs.Distance of any node from itself is always zero. But in some cases, as in this example, when we traverse further from 4 to 1, the distance comes out to be -2, i.e. distance of 1 from 1 will become -2. This is our catch, we just have to check the nodes distance from itself and if it comes out to be negative, we will detect the required negative cycle. "
},
{
"code": null,
"e": 1067,
"s": 1063,
"text": "C++"
},
{
"code": null,
"e": 1072,
"s": 1067,
"text": "Java"
},
{
"code": null,
"e": 1080,
"s": 1072,
"text": "Python3"
},
{
"code": null,
"e": 1083,
"s": 1080,
"text": "C#"
},
{
"code": null,
"e": 1094,
"s": 1083,
"text": "Javascript"
},
{
"code": "// C++ Program to check if there is a negative weight// cycle using Floyd Warshall Algorithm#include<bits/stdc++.h>using namespace std; // Number of vertices in the graph#define V 4 /* Define Infinite as a large enough value. This value will be used for vertices not connected to each other */#define INF 99999 // A function to print the solution matrixvoid printSolution(int dist[][V]); // Returns true if graph has negative weight cycle// else false.bool negCyclefloydWarshall(int graph[][V]){ /* dist[][] will be the output matrix that will finally have the shortest distances between every pair of vertices */ int dist[V][V], i, j, k; /* Initialize the solution matrix same as input graph matrix. Or we can say the initial values of shortest distances are based on shortest paths considering no intermediate vertex. */ for (i = 0; i < V; i++) for (j = 0; j < V; j++) dist[i][j] = graph[i][j]; /* Add all vertices one by one to the set of intermediate vertices. ---> Before start of a iteration, we have shortest distances between all pairs of vertices such that the shortest distances consider only the vertices in set {0, 1, 2, .. k-1} as intermediate vertices. ----> After the end of a iteration, vertex no. k is added to the set of intermediate vertices and the set becomes {0, 1, 2, .. k} */ for (k = 0; k < V; k++) { // Pick all vertices as source one by one for (i = 0; i < V; i++) { // Pick all vertices as destination for the // above picked source for (j = 0; j < V; j++) { // If vertex k is on the shortest path from // i to j, then update the value of dist[i][j] if (dist[i][k] + dist[k][j] < dist[i][j]) dist[i][j] = dist[i][k] + dist[k][j]; } } } // If distance of any vertex from itself // becomes negative, then there is a negative // weight cycle. for (int i = 0; i < V; i++) if (dist[i][i] < 0) return true; return false; } // driver programint main(){ /* Let us create the following weighted graph 1 (0)----------->(1) /|\\ | | | -1 | | -1 | \\|/ (3)<-----------(2) -1 */ int graph[V][V] = { {0 , 1 , INF , INF}, {INF , 0 , -1 , INF}, {INF , INF , 0 , -1}, {-1 , INF , INF , 0}}; if (negCyclefloydWarshall(graph)) cout << \"Yes\"; else cout << \"No\"; return 0;}",
"e": 3836,
"s": 1094,
"text": null
},
{
"code": "// Java Program to check if there is a negative weight// cycle using Floyd Warshall Algorithmclass GFG{ // Number of vertices in the graph static final int V = 4; /* Define Infinite as a large enough value. This value will be used for vertices not connected to each other */ static final int INF = 99999; // Returns true if graph has negative weight cycle // else false. static boolean negCyclefloydWarshall(int graph[][]) { /* dist[][] will be the output matrix that will finally have the shortest distances between every pair of vertices */ int dist[][] = new int[V][V], i, j, k; /* Initialize the solution matrix same as input graph matrix. Or we can say the initial values of shortest distances are based on shortest paths considering no intermediate vertex. */ for (i = 0; i < V; i++) for (j = 0; j < V; j++) dist[i][j] = graph[i][j]; /* Add all vertices one by one to the set of intermediate vertices. ---> Before start of a iteration, we have shortest distances between all pairs of vertices such that the shortest distances consider only the vertices in set {0, 1, 2, .. k-1} as intermediate vertices. ----> After the end of a iteration, vertex no. k is added to the set of intermediate vertices and the set becomes {0, 1, 2, .. k} */ for (k = 0; k < V; k++) { // Pick all vertices as source one by one for (i = 0; i < V; i++) { // Pick all vertices as destination for the // above picked source for (j = 0; j < V; j++) { // If vertex k is on the shortest path from // i to j, then update the value of dist[i][j] if (dist[i][k] + dist[k][j] < dist[i][j]) dist[i][j] = dist[i][k] + dist[k][j]; } } } // If distance of any vertex from itself // becomes negative, then there is a negative // weight cycle. for (i = 0; i < V; i++) if (dist[i][i] < 0) return true; return false; } // Driver code public static void main (String[] args) { /* Let us create the following weighted graph 1 (0)----------->(1) /|\\ | | | -1 | | -1 | \\|/ (3)<-----------(2) -1 */ int graph[][] = { {0, 1, INF, INF}, {INF, 0, -1, INF}, {INF, INF, 0, -1}, {-1, INF, INF, 0}}; if (negCyclefloydWarshall(graph)) System.out.print(\"Yes\"); else System.out.print(\"No\"); }} // This code is contributed by Anant Agarwal.",
"e": 6941,
"s": 3836,
"text": null
},
{
"code": "# Python Program to check# if there is a# negative weight# cycle using Floyd# Warshall Algorithm # Number of vertices# in the graphV = 4 # Define Infinite as a# large enough value. This # value will be used #for vertices not connected # to each other INF = 99999 # Returns true if graph has# negative weight cycle# else false.def negCyclefloydWarshall(graph): # dist[][] will be the # output matrix that will # finally have the shortest # distances between every # pair of vertices dist=[[0 for i in range(V+1)]for j in range(V+1)] # Initialize the solution # matrix same as input # graph matrix. Or we can # say the initial values # of shortest distances # are based on shortest # paths considering no # intermediate vertex. for i in range(V): for j in range(V): dist[i][j] = graph[i][j] ''' Add all vertices one by one to the set of intermediate vertices. ---> Before start of a iteration, we have shortest distances between all pairs of vertices such that the shortest distances consider only the vertices in set {0, 1, 2, .. k-1} as intermediate vertices. ----> After the end of a iteration, vertex no. k is added to the set of intermediate vertices and the set becomes {0, 1, 2, .. k} ''' for k in range(V): # Pick all vertices # as source one by one for i in range(V): # Pick all vertices as # destination for the # above picked source for j in range(V): # If vertex k is on # the shortest path from # i to j, then update # the value of dist[i][j] if (dist[i][k] + dist[k][j] < dist[i][j]): dist[i][j] = dist[i][k] + dist[k][j] # If distance of any # vertex from itself # becomes negative, then # there is a negative # weight cycle. for i in range(V): if (dist[i][i] < 0): return True return False # Driver code ''' Let us create the following weighted graph 1 (0)----------->(1) /|\\ | | | -1 | | -1 | \\|/ (3)<-----------(2) -1 ''' graph = [ [0, 1, INF, INF], [INF, 0, -1, INF], [INF, INF, 0, -1], [-1, INF, INF, 0]] if (negCyclefloydWarshall(graph)): print(\"Yes\")else: print(\"No\") # This code is contributed# by Anant Agarwal.",
"e": 9615,
"s": 6941,
"text": null
},
{
"code": "// C# Program to check if there// is a negative weight cycle// using Floyd Warshall Algorithm using System; namespace Cycle{public class GFG{ // Number of vertices in the graph static int V = 4; /* Define Infinite as a large enough value. This value will be used for vertices not connected to each other */ static int INF = 99999; // Returns true if graph has negative weight cycle // else false. static bool negCyclefloydWarshall(int [,]graph) { /* dist[][] will be the output matrix that will finally have the shortest distances between every pair of vertices */ int [,]dist = new int[V,V]; int i, j, k; /* Initialize the solution matrix same as input graph matrix. Or we can say the initial values of shortest distances are based on shortest paths considering no intermediate vertex. */ for (i = 0; i < V; i++) for (j = 0; j < V; j++) dist[i,j] = graph[i,j]; /* Add all vertices one by one to the set of intermediate vertices. ---> Before start of a iteration, we have shortest distances between all pairs of vertices such that the shortest distances consider only the vertices in set {0, 1, 2, .. k-1} as intermediate vertices. ----> After the end of a iteration, vertex no. k is added to the set of intermediate vertices and the set becomes {0, 1, 2, .. k} */ for (k = 0; k < V; k++) { // Pick all vertices as source one by one for (i = 0; i < V; i++) { // Pick all vertices as destination for the // above picked source for (j = 0; j < V; j++) { // If vertex k is on the shortest path from // i to j, then update the value of dist[i][j] if (dist[i,k] + dist[k,j] < dist[i,j]) dist[i,j] = dist[i,k] + dist[k,j]; } } } // If distance of any vertex from itself // becomes negative, then there is a negative // weight cycle. for (i = 0; i < V; i++) if (dist[i,i] < 0) return true; return false; } // Driver code public static void Main() { /* Let us create the following weighted graph 1 (0)----------->(1) /|\\ | | | -1 | | -1 | \\|/ (3)<-----------(2) -1 */ int [,]graph = { {0, 1, INF, INF}, {INF, 0, -1, INF}, {INF, INF, 0, -1}, {-1, INF, INF, 0}}; if (negCyclefloydWarshall(graph)) Console.Write(\"Yes\"); else Console.Write(\"No\"); }} } // This code is contributed by Sam007.",
"e": 12710,
"s": 9615,
"text": null
},
{
"code": "<script> // JavaScript Program to check if there// is a negative weight cycle// using Floyd Warshall Algorithm// Number of vertices in the graphvar V = 4; /* Define Infinite as a large enough value. This value will be used for vertices not connected to each other */var INF = 99999; // Returns true if graph has negative weight cycle// else false.function negCyclefloydWarshall(graph){ /* dist[][] will be the output matrix that will finally have the shortest distances between every pair of vertices */ var dist = Array.from(Array(V), ()=>Array(V)); var i, j, k; /* Initialize the solution matrix same as input graph matrix. Or we can say the initial values of shortest distances are based on shortest paths considering no intermediate vertex. */ for (i = 0; i < V; i++) for (j = 0; j < V; j++) dist[i][j] = graph[i][j]; /* Add all vertices one by one to the set of intermediate vertices. ---> Before start of a iteration, we have shortest distances between all pairs of vertices such that the shortest distances consider only the vertices in set {0, 1, 2, .. k-1} as intermediate vertices. ----> After the end of a iteration, vertex no. k is added to the set of intermediate vertices and the set becomes {0, 1, 2, .. k} */ for (k = 0; k < V; k++) { // Pick all vertices as source one by one for (i = 0; i < V; i++) { // Pick all vertices as destination for the // above picked source for (j = 0; j < V; j++) { // If vertex k is on the shortest path from // i to j, then update the value of dist[i][j] if (dist[i][k] + dist[k][j] < dist[i][j]) dist[i][j] = dist[i][k] + dist[k][j]; } } } // If distance of any vertex from itself // becomes negative, then there is a negative // weight cycle. for (i = 0; i < V; i++) if (dist[i][i] < 0) return true; return false; } // Driver code /* Let us create the following weighted graph 1 (0)----------->(1) /|\\ | | |-1 | | -1 | \\|/ (3)<-----------(2) -1 */ var graph = [ [0, 1, INF, INF], [INF, 0, -1, INF], [INF, INF, 0, -1], [-1, INF, INF, 0]]; if (negCyclefloydWarshall(graph)) document.write(\"Yes\");else document.write(\"No\"); </script>",
"e": 15300,
"s": 12710,
"text": null
},
{
"code": null,
"e": 15310,
"s": 15300,
"text": "Output: "
},
{
"code": null,
"e": 15314,
"s": 15310,
"text": "Yes"
},
{
"code": null,
"e": 15737,
"s": 15314,
"text": "This article is contributed by Shivani Mittal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 15743,
"s": 15737,
"text": "itsok"
},
{
"code": null,
"e": 15760,
"s": 15743,
"text": "surinderdawra388"
},
{
"code": null,
"e": 15772,
"s": 15760,
"text": "graph-cycle"
},
{
"code": null,
"e": 15778,
"s": 15772,
"text": "Graph"
},
{
"code": null,
"e": 15784,
"s": 15778,
"text": "Graph"
},
{
"code": null,
"e": 15882,
"s": 15784,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 15933,
"s": 15882,
"text": "Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 15991,
"s": 15933,
"text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2"
},
{
"code": null,
"e": 16024,
"s": 15991,
"text": "Detect Cycle in a Directed Graph"
},
{
"code": null,
"e": 16089,
"s": 16024,
"text": "Find if there is a path between two vertices in a directed graph"
},
{
"code": null,
"e": 16121,
"s": 16089,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 16185,
"s": 16121,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 16216,
"s": 16185,
"text": "Bellman–Ford Algorithm | DP-23"
},
{
"code": null,
"e": 16284,
"s": 16216,
"text": "Find if there is a path between two vertices in an undirected graph"
},
{
"code": null,
"e": 16334,
"s": 16284,
"text": "Minimum number of swaps required to sort an array"
}
]
|
Minimum cost to sort strings using reversal operations of different costs - GeeksforGeeks | 07 Mar, 2022
Given an array of strings and costs of reversing all strings, we need to sort the array. We cannot move strings in array, only string reversal is allowed. We need to reverse some of the strings in such a way that all strings make a lexicographic order and cost is also minimized. If it is not possible to sort strings in any way, output not possible. Examples:
Input : arr[] = {“aa”, “ba”, “ac”},
reverseCost[] = {1, 3, 1}
Output : Minimum cost of sorting = 1
Explanation : We can make above string array sorted
by reversing one of 2nd or 3rd string, but reversing
2nd string cost 3, so we will reverse 3rd string to
make string array sorted with a cost 1 which is
minimum.
We can solve this problem using dynamic programming. We make a 2D array for storing the minimum cost of sorting.
dp[i][j] represents the minimum cost to make first i
strings sorted.
j = 1 means i'th string is reversed.
j = 0 means i'th string is not reversed.
Value of dp[i][j] is computed using dp[i-1][1] and
dp[i-1][0].
Computation of dp[i][0]
If arr[i] is greater than str[i-1], we update dp[i][0]
by dp[i-1][0]
If arr[i] is greater than reversal of previous string
we update dp[i][0] by dp[i-1][1]
Same procedure is applied to compute dp[i][1], we
reverse str[i] before applying the procedure.
At the end we will choose minimum of dp[N-1][0] and
dp[N-1][1] as our final answer if both of them not
updated yet even once, we will flag that sorting is
not possible.
Below is the implementation of above idea.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to get minimum cost to sort// strings by reversal operation#include <bits/stdc++.h>using namespace std; // Returns minimum cost for sorting arr[]// using reverse operation. This function// returns -1 if it is not possible to sort.int minCost(string arr[], int cost[], int N){ // dp[i][j] represents the minimum cost to // make first i strings sorted. // j = 1 means i'th string is reversed. // j = 0 means i'th string is not reversed. int dp[N][2]; // initializing dp array for first string dp[0][0] = 0; dp[0][1] = cost[0]; // getting array of reversed strings string revStr[N]; for (int i = 0; i < N; i++) { revStr[i] = arr[i]; reverse(revStr[i].begin(), revStr[i].end()); } string curStr; int curCost; // looping for all strings for (int i = 1; i < N; i++) { // Looping twice, once for string and once // for reversed string for (int j = 0; j < 2; j++) { dp[i][j] = INT_MAX; // getting current string and current // cost according to j curStr = (j == 0) ? arr[i] : revStr[i]; curCost = (j == 0) ? 0 : cost[i]; // Update dp value only if current string // is lexicographically larger if (curStr >= arr[i - 1]) dp[i][j] = min(dp[i][j], dp[i-1][0] + curCost); if (curStr >= revStr[i - 1]) dp[i][j] = min(dp[i][j], dp[i-1][1] + curCost); } } // getting minimum from both entries of last index int res = min(dp[N-1][0], dp[N-1][1]); return (res == INT_MAX)? -1 : res;} // Driver code to test above methodsint main(){ string arr[] = {"aa", "ba", "ac"}; int cost[] = {1, 3, 1}; int N = sizeof(arr) / sizeof(arr[0]); int res = minCost(arr, cost, N); if (res == -1) cout << "Sorting not possible\n"; else cout << "Minimum cost to sort strings is " << res;}
// Java program to get minimum cost to sort// strings by reversal operationimport java.util.*; class GFG{ // Returns minimum cost for sorting arr[]// using reverse operation. This function// returns -1 if it is not possible to sort.static int minCost(String arr[], int cost[], int N){ // dp[i][j] represents the minimum cost to // make first i strings sorted. // j = 1 means i'th string is reversed. // j = 0 means i'th string is not reversed. int [][]dp = new int[N][2]; // initializing dp array for first string dp[0][0] = 0; dp[0][1] = cost[0]; // getting array of reversed strings String []revStr = new String[N]; for (int i = 0; i < N; i++) { revStr[i] = arr[i]; revStr[i] = reverse(revStr[i], 0, revStr[i].length() - 1); } String curStr = ""; int curCost; // looping for all strings for (int i = 1; i < N; i++) { // Looping twice, once for string and once // for reversed string for (int j = 0; j < 2; j++) { dp[i][j] = Integer.MAX_VALUE; // getting current string and current // cost according to j curStr = (j == 0) ? arr[i] : revStr[i]; curCost = (j == 0) ? 0 : cost[i]; // Update dp value only if current string // is lexicographically larger if (curStr.compareTo(arr[i - 1]) >= 0) dp[i][j] = Math.min(dp[i][j], dp[i - 1][0] + curCost); if (curStr.compareTo(revStr[i - 1]) >= 0) dp[i][j] = Math.min(dp[i][j], dp[i - 1][1] + curCost); } } // getting minimum from both entries of last index int res = Math.min(dp[N - 1][0], dp[N - 1][1]); return (res == Integer.MAX_VALUE)? -1 : res;} static String reverse(String s, int start, int end){ // Temporary variable to store character char temp; char []str = s.toCharArray(); while (start <= end) { // Swapping the first and last character temp = str[start]; str[start] = str[end]; str[end] = temp; start++; end--; } return String.valueOf(str);} // Driver Codepublic static void main(String[] args){ String arr[] = {"aa", "ba", "ac"}; int cost[] = {1, 3, 1}; int N = arr.length; int res = minCost(arr, cost, N); if (res == -1) System.out.println("Sorting not possible\n"); else System.out.println("Minimum cost to " + "sort strings is " + res); }} // This code is contributed by Rajput-Ji
# Python program to get minimum cost to sort# strings by reversal operation # Returns minimum cost for sorting arr[]# using reverse operation. This function# returns -1 if it is not possible to sort.def ReverseStringMin(arr, reverseCost, n): # dp[i][j] represents the minimum cost to # make first i strings sorted. # j = 1 means i'th string is reversed. # j = 0 means i'th string is not reversed. dp = [[float("Inf")] * 2 for i in range(n)] # initializing dp array for first string dp[0][0] = 0 dp[0][1] = reverseCost[0] # getting array of reversed strings rev_arr = [i[::-1] for i in arr] # looping for all strings for i in range(1, n): # Looping twice, once for string and once # for reversed string for j in range(2): # getting current string and current # cost according to j curStr = arr[i] if j==0 else rev_arr[i] curCost = 0 if j==0 else reverseCost[i] # Update dp value only if current string # is lexicographically larger if (curStr >= arr[i - 1]): dp[i][j] = min(dp[i][j], dp[i-1][0] + curCost) if (curStr >= rev_arr[i - 1]): dp[i][j] = min(dp[i][j], dp[i-1][1] + curCost) # getting minimum from both entries of last index res = min(dp[n-1][0], dp[n-1][1]) return res if res != float("Inf") else -1 # Driver codedef main(): arr = ["aa", "ba", "ac"] reverseCost = [1, 3, 1] n = len(arr) dp = [float("Inf")] * n res = ReverseStringMin(arr, reverseCost,n) if res != -1 : print ("Minimum cost to sort sorting is" , res) else : print ("Sorting not possible") if __name__ == '__main__': main() #This code is contributed by Neelam Yadav
// C# program to get minimum cost to sort// strings by reversal operationusing System; class GFG{ // Returns minimum cost for sorting arr[]// using reverse operation. This function// returns -1 if it is not possible to sort.static int minCost(String []arr, int []cost, int N){ // dp[i,j] represents the minimum cost to // make first i strings sorted. // j = 1 means i'th string is reversed. // j = 0 means i'th string is not reversed. int [,]dp = new int[N, 2]; // initializing dp array for first string dp[0, 0] = 0; dp[0, 1] = cost[0]; // getting array of reversed strings String []revStr = new String[N]; for (int i = 0; i < N; i++) { revStr[i] = arr[i]; revStr[i] = reverse(revStr[i], 0, revStr[i].Length - 1); } String curStr = ""; int curCost; // looping for all strings for (int i = 1; i < N; i++) { // Looping twice, once for string and once // for reversed string for (int j = 0; j < 2; j++) { dp[i, j] = int.MaxValue; // getting current string and current // cost according to j curStr = (j == 0) ? arr[i] : revStr[i]; curCost = (j == 0) ? 0 : cost[i]; // Update dp value only if current string // is lexicographically larger if (curStr.CompareTo(arr[i - 1]) >= 0) dp[i, j] = Math.Min(dp[i, j], dp[i - 1, 0] + curCost); if (curStr.CompareTo(revStr[i - 1]) >= 0) dp[i, j] = Math.Min(dp[i, j], dp[i - 1, 1] + curCost); } } // getting minimum from both entries of last index int res = Math.Min(dp[N - 1, 0], dp[N - 1, 1]); return (res == int.MaxValue) ? -1 : res;} static String reverse(String s, int start, int end){ // Temporary variable to store character char temp; char []str = s.ToCharArray(); while (start <= end) { // Swapping the first and last character temp = str[start]; str[start] = str[end]; str[end] = temp; start++; end--; } return String.Join("", str);} // Driver Codepublic static void Main(String[] args){ String []arr = {"aa", "ba", "ac"}; int []cost = {1, 3, 1}; int N = arr.Length; int res = minCost(arr, cost, N); if (res == -1) Console.WriteLine("Sorting not possible\n"); else Console.WriteLine("Minimum cost to " + "sort strings is " + res); }} // This code is contributed by Princi Singh
<?php// PHP program to get minimum cost to sort// strings by reversal operation // Returns minimum cost for sorting arr[]// using reverse operation. This function// returns -1 if it is not possible to sort.function minCost(&$arr, &$cost, $N){ // dp[i][j] represents the minimum cost // to make first i strings sorted. // j = 1 means i'th string is reversed. // j = 0 means i'th string is not reversed. $dp = array_fill(0, $N, array_fill(0, 2, NULL)); // initializing dp array for // first string $dp[0][0] = 0; $dp[0][1] = $cost[0]; // getting array of reversed strings $revStr = array_fill(false, $N, NULL); for ($i = 0; $i < $N; $i++) { $revStr[$i] = $arr[$i]; $revStr[$i] = strrev($revStr[$i]); } $curStr = ""; // looping for all strings for ($i = 1; $i < $N; $i++) { // Looping twice, once for string // and once for reversed string for ($j = 0; $j < 2; $j++) { $dp[$i][$j] = PHP_INT_MAX; // getting current string and // current cost according to j if($j == 0) $curStr = $arr[$i]; else $curStr = $revStr[$i]; if($j == 0) $curCost = 0 ; else $curCost = $cost[$i]; // Update dp value only if current string // is lexicographically larger if ($curStr >= $arr[$i - 1]) $dp[$i][$j] = min($dp[$i][$j], $dp[$i - 1][0] + $curCost); if ($curStr >= $revStr[$i - 1]) $dp[$i][$j] = min($dp[$i][$j], $dp[$i - 1][1] + $curCost); } } // getting minimum from both entries // of last index $res = min($dp[$N - 1][0], $dp[$N - 1][1]); if($res == PHP_INT_MAX) return -1 ; else return $res;} // Driver Code$arr = array("aa", "ba", "ac");$cost = array(1, 3, 1);$N = sizeof($arr);$res = minCost($arr, $cost, $N);if ($res == -1) echo "Sorting not possible\n";else echo "Minimum cost to sort strings is " . $res; // This code is contributed by ita_c?>
<script> // Javascript program to get minimum cost to sort// strings by reversal operation // Returns minimum cost for sorting arr[] // using reverse operation. This function // returns -1 if it is not possible to sort. function minCost(arr,cost,N) { // dp[i][j] represents the minimum cost to // make first i strings sorted. // j = 1 means i'th string is reversed. // j = 0 means i'th string is not reversed. let dp=new Array(N); for(let i=0;i<N;i++) { dp[i]=new Array(2); for(let j=0;j<2;j++) { dp[i][j]=0; } } // initializing dp array for first string dp[0][0] = 0; dp[0][1] = cost[0]; // getting array of reversed strings let revStr = new Array(N); for(let i=0;i<N;i++) { revStr[i]=""; } for (let i = 0; i < N; i++) { revStr[i] = arr[i]; revStr[i] = reverse(revStr[i], 0, revStr[i].length - 1); } let curStr = ""; let curCost; // looping for all strings for (let i = 1; i < N; i++) { // Looping twice, once for string and once // for reversed string for (let j = 0; j < 2; j++) { dp[i][j] = Number.MAX_VALUE; // getting current string and current // cost according to j curStr = (j == 0) ? arr[i] : revStr[i]; curCost = (j == 0) ? 0 : cost[i]; // Update dp value only if current string // is lexicographically larger if (curStr>=arr[i - 1]) dp[i][j] = Math.min(dp[i][j], dp[i - 1][0] + curCost); if (curStr>=revStr[i - 1]) dp[i][j] = Math.min(dp[i][j], dp[i - 1][1] + curCost); } } // getting minimum from both entries of last index let res = Math.min(dp[N - 1][0], dp[N - 1][1]); return (res == Number.MAX_VALUE)? -1 : res; } function reverse(s,start,end) { // Temporary variable to store character let temp; let str=s.split(""); while (start <= end) { // Swapping the first and last character temp = str[start]; str[start] = str[end]; str[end] = temp; start++; end--; } return str.toString(); } // Driver Code let arr=["aa", "ba", "ac"]; let cost=[1, 3, 1]; let N = arr.length; let res = minCost(arr, cost, N); if (res == -1) document.write("Sorting not possible\n"); else document.write("Minimum cost to " + "sort strings is " + res); // This code is contributed by avanitrachhadiya2155 </script>
Output:
Minimum cost to sort strings is 1
Time Complexity: O(N)
Auxiliary Space: O(N)This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
ukasp
Rajput-Ji
princi singh
avanitrachhadiya2155
amartyaghoshgfg
rohitsingh07052
Dynamic Programming
Strings
Strings
Dynamic Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum size square sub-matrix with all 1s
Optimal Substructure Property in Dynamic Programming | DP-2
Min Cost Path | DP-6
Optimal Binary Search Tree | DP-24
Box Stacking Problem | DP-22
Write a program to reverse an array or string
Reverse a string in Java
Write a program to print all permutations of a given string
C++ Data Types
Check for Balanced Brackets in an expression (well-formedness) using Stack | [
{
"code": null,
"e": 25941,
"s": 25913,
"text": "\n07 Mar, 2022"
},
{
"code": null,
"e": 26304,
"s": 25941,
"text": "Given an array of strings and costs of reversing all strings, we need to sort the array. We cannot move strings in array, only string reversal is allowed. We need to reverse some of the strings in such a way that all strings make a lexicographic order and cost is also minimized. If it is not possible to sort strings in any way, output not possible. Examples: "
},
{
"code": null,
"e": 26630,
"s": 26304,
"text": "Input : arr[] = {“aa”, “ba”, “ac”}, \n reverseCost[] = {1, 3, 1}\nOutput : Minimum cost of sorting = 1\nExplanation : We can make above string array sorted \nby reversing one of 2nd or 3rd string, but reversing\n2nd string cost 3, so we will reverse 3rd string to \nmake string array sorted with a cost 1 which is \nminimum."
},
{
"code": null,
"e": 26746,
"s": 26632,
"text": "We can solve this problem using dynamic programming. We make a 2D array for storing the minimum cost of sorting. "
},
{
"code": null,
"e": 27415,
"s": 26746,
"text": "dp[i][j] represents the minimum cost to make first i\nstrings sorted.\n j = 1 means i'th string is reversed.\n j = 0 means i'th string is not reversed.\n\nValue of dp[i][j] is computed using dp[i-1][1] and \ndp[i-1][0].\n\nComputation of dp[i][0]\nIf arr[i] is greater than str[i-1], we update dp[i][0] \nby dp[i-1][0] \nIf arr[i] is greater than reversal of previous string \nwe update dp[i][0] by dp[i-1][1] \n\nSame procedure is applied to compute dp[i][1], we \nreverse str[i] before applying the procedure.\n\nAt the end we will choose minimum of dp[N-1][0] and \ndp[N-1][1] as our final answer if both of them not \nupdated yet even once, we will flag that sorting is\nnot possible."
},
{
"code": null,
"e": 27461,
"s": 27415,
"text": "Below is the implementation of above idea. "
},
{
"code": null,
"e": 27465,
"s": 27461,
"text": "C++"
},
{
"code": null,
"e": 27470,
"s": 27465,
"text": "Java"
},
{
"code": null,
"e": 27478,
"s": 27470,
"text": "Python3"
},
{
"code": null,
"e": 27481,
"s": 27478,
"text": "C#"
},
{
"code": null,
"e": 27485,
"s": 27481,
"text": "PHP"
},
{
"code": null,
"e": 27496,
"s": 27485,
"text": "Javascript"
},
{
"code": "// C++ program to get minimum cost to sort// strings by reversal operation#include <bits/stdc++.h>using namespace std; // Returns minimum cost for sorting arr[]// using reverse operation. This function// returns -1 if it is not possible to sort.int minCost(string arr[], int cost[], int N){ // dp[i][j] represents the minimum cost to // make first i strings sorted. // j = 1 means i'th string is reversed. // j = 0 means i'th string is not reversed. int dp[N][2]; // initializing dp array for first string dp[0][0] = 0; dp[0][1] = cost[0]; // getting array of reversed strings string revStr[N]; for (int i = 0; i < N; i++) { revStr[i] = arr[i]; reverse(revStr[i].begin(), revStr[i].end()); } string curStr; int curCost; // looping for all strings for (int i = 1; i < N; i++) { // Looping twice, once for string and once // for reversed string for (int j = 0; j < 2; j++) { dp[i][j] = INT_MAX; // getting current string and current // cost according to j curStr = (j == 0) ? arr[i] : revStr[i]; curCost = (j == 0) ? 0 : cost[i]; // Update dp value only if current string // is lexicographically larger if (curStr >= arr[i - 1]) dp[i][j] = min(dp[i][j], dp[i-1][0] + curCost); if (curStr >= revStr[i - 1]) dp[i][j] = min(dp[i][j], dp[i-1][1] + curCost); } } // getting minimum from both entries of last index int res = min(dp[N-1][0], dp[N-1][1]); return (res == INT_MAX)? -1 : res;} // Driver code to test above methodsint main(){ string arr[] = {\"aa\", \"ba\", \"ac\"}; int cost[] = {1, 3, 1}; int N = sizeof(arr) / sizeof(arr[0]); int res = minCost(arr, cost, N); if (res == -1) cout << \"Sorting not possible\\n\"; else cout << \"Minimum cost to sort strings is \" << res;}",
"e": 29458,
"s": 27496,
"text": null
},
{
"code": "// Java program to get minimum cost to sort// strings by reversal operationimport java.util.*; class GFG{ // Returns minimum cost for sorting arr[]// using reverse operation. This function// returns -1 if it is not possible to sort.static int minCost(String arr[], int cost[], int N){ // dp[i][j] represents the minimum cost to // make first i strings sorted. // j = 1 means i'th string is reversed. // j = 0 means i'th string is not reversed. int [][]dp = new int[N][2]; // initializing dp array for first string dp[0][0] = 0; dp[0][1] = cost[0]; // getting array of reversed strings String []revStr = new String[N]; for (int i = 0; i < N; i++) { revStr[i] = arr[i]; revStr[i] = reverse(revStr[i], 0, revStr[i].length() - 1); } String curStr = \"\"; int curCost; // looping for all strings for (int i = 1; i < N; i++) { // Looping twice, once for string and once // for reversed string for (int j = 0; j < 2; j++) { dp[i][j] = Integer.MAX_VALUE; // getting current string and current // cost according to j curStr = (j == 0) ? arr[i] : revStr[i]; curCost = (j == 0) ? 0 : cost[i]; // Update dp value only if current string // is lexicographically larger if (curStr.compareTo(arr[i - 1]) >= 0) dp[i][j] = Math.min(dp[i][j], dp[i - 1][0] + curCost); if (curStr.compareTo(revStr[i - 1]) >= 0) dp[i][j] = Math.min(dp[i][j], dp[i - 1][1] + curCost); } } // getting minimum from both entries of last index int res = Math.min(dp[N - 1][0], dp[N - 1][1]); return (res == Integer.MAX_VALUE)? -1 : res;} static String reverse(String s, int start, int end){ // Temporary variable to store character char temp; char []str = s.toCharArray(); while (start <= end) { // Swapping the first and last character temp = str[start]; str[start] = str[end]; str[end] = temp; start++; end--; } return String.valueOf(str);} // Driver Codepublic static void main(String[] args){ String arr[] = {\"aa\", \"ba\", \"ac\"}; int cost[] = {1, 3, 1}; int N = arr.length; int res = minCost(arr, cost, N); if (res == -1) System.out.println(\"Sorting not possible\\n\"); else System.out.println(\"Minimum cost to \" + \"sort strings is \" + res); }} // This code is contributed by Rajput-Ji",
"e": 32083,
"s": 29458,
"text": null
},
{
"code": "# Python program to get minimum cost to sort# strings by reversal operation # Returns minimum cost for sorting arr[]# using reverse operation. This function# returns -1 if it is not possible to sort.def ReverseStringMin(arr, reverseCost, n): # dp[i][j] represents the minimum cost to # make first i strings sorted. # j = 1 means i'th string is reversed. # j = 0 means i'th string is not reversed. dp = [[float(\"Inf\")] * 2 for i in range(n)] # initializing dp array for first string dp[0][0] = 0 dp[0][1] = reverseCost[0] # getting array of reversed strings rev_arr = [i[::-1] for i in arr] # looping for all strings for i in range(1, n): # Looping twice, once for string and once # for reversed string for j in range(2): # getting current string and current # cost according to j curStr = arr[i] if j==0 else rev_arr[i] curCost = 0 if j==0 else reverseCost[i] # Update dp value only if current string # is lexicographically larger if (curStr >= arr[i - 1]): dp[i][j] = min(dp[i][j], dp[i-1][0] + curCost) if (curStr >= rev_arr[i - 1]): dp[i][j] = min(dp[i][j], dp[i-1][1] + curCost) # getting minimum from both entries of last index res = min(dp[n-1][0], dp[n-1][1]) return res if res != float(\"Inf\") else -1 # Driver codedef main(): arr = [\"aa\", \"ba\", \"ac\"] reverseCost = [1, 3, 1] n = len(arr) dp = [float(\"Inf\")] * n res = ReverseStringMin(arr, reverseCost,n) if res != -1 : print (\"Minimum cost to sort sorting is\" , res) else : print (\"Sorting not possible\") if __name__ == '__main__': main() #This code is contributed by Neelam Yadav",
"e": 33879,
"s": 32083,
"text": null
},
{
"code": "// C# program to get minimum cost to sort// strings by reversal operationusing System; class GFG{ // Returns minimum cost for sorting arr[]// using reverse operation. This function// returns -1 if it is not possible to sort.static int minCost(String []arr, int []cost, int N){ // dp[i,j] represents the minimum cost to // make first i strings sorted. // j = 1 means i'th string is reversed. // j = 0 means i'th string is not reversed. int [,]dp = new int[N, 2]; // initializing dp array for first string dp[0, 0] = 0; dp[0, 1] = cost[0]; // getting array of reversed strings String []revStr = new String[N]; for (int i = 0; i < N; i++) { revStr[i] = arr[i]; revStr[i] = reverse(revStr[i], 0, revStr[i].Length - 1); } String curStr = \"\"; int curCost; // looping for all strings for (int i = 1; i < N; i++) { // Looping twice, once for string and once // for reversed string for (int j = 0; j < 2; j++) { dp[i, j] = int.MaxValue; // getting current string and current // cost according to j curStr = (j == 0) ? arr[i] : revStr[i]; curCost = (j == 0) ? 0 : cost[i]; // Update dp value only if current string // is lexicographically larger if (curStr.CompareTo(arr[i - 1]) >= 0) dp[i, j] = Math.Min(dp[i, j], dp[i - 1, 0] + curCost); if (curStr.CompareTo(revStr[i - 1]) >= 0) dp[i, j] = Math.Min(dp[i, j], dp[i - 1, 1] + curCost); } } // getting minimum from both entries of last index int res = Math.Min(dp[N - 1, 0], dp[N - 1, 1]); return (res == int.MaxValue) ? -1 : res;} static String reverse(String s, int start, int end){ // Temporary variable to store character char temp; char []str = s.ToCharArray(); while (start <= end) { // Swapping the first and last character temp = str[start]; str[start] = str[end]; str[end] = temp; start++; end--; } return String.Join(\"\", str);} // Driver Codepublic static void Main(String[] args){ String []arr = {\"aa\", \"ba\", \"ac\"}; int []cost = {1, 3, 1}; int N = arr.Length; int res = minCost(arr, cost, N); if (res == -1) Console.WriteLine(\"Sorting not possible\\n\"); else Console.WriteLine(\"Minimum cost to \" + \"sort strings is \" + res); }} // This code is contributed by Princi Singh",
"e": 36524,
"s": 33879,
"text": null
},
{
"code": "<?php// PHP program to get minimum cost to sort// strings by reversal operation // Returns minimum cost for sorting arr[]// using reverse operation. This function// returns -1 if it is not possible to sort.function minCost(&$arr, &$cost, $N){ // dp[i][j] represents the minimum cost // to make first i strings sorted. // j = 1 means i'th string is reversed. // j = 0 means i'th string is not reversed. $dp = array_fill(0, $N, array_fill(0, 2, NULL)); // initializing dp array for // first string $dp[0][0] = 0; $dp[0][1] = $cost[0]; // getting array of reversed strings $revStr = array_fill(false, $N, NULL); for ($i = 0; $i < $N; $i++) { $revStr[$i] = $arr[$i]; $revStr[$i] = strrev($revStr[$i]); } $curStr = \"\"; // looping for all strings for ($i = 1; $i < $N; $i++) { // Looping twice, once for string // and once for reversed string for ($j = 0; $j < 2; $j++) { $dp[$i][$j] = PHP_INT_MAX; // getting current string and // current cost according to j if($j == 0) $curStr = $arr[$i]; else $curStr = $revStr[$i]; if($j == 0) $curCost = 0 ; else $curCost = $cost[$i]; // Update dp value only if current string // is lexicographically larger if ($curStr >= $arr[$i - 1]) $dp[$i][$j] = min($dp[$i][$j], $dp[$i - 1][0] + $curCost); if ($curStr >= $revStr[$i - 1]) $dp[$i][$j] = min($dp[$i][$j], $dp[$i - 1][1] + $curCost); } } // getting minimum from both entries // of last index $res = min($dp[$N - 1][0], $dp[$N - 1][1]); if($res == PHP_INT_MAX) return -1 ; else return $res;} // Driver Code$arr = array(\"aa\", \"ba\", \"ac\");$cost = array(1, 3, 1);$N = sizeof($arr);$res = minCost($arr, $cost, $N);if ($res == -1) echo \"Sorting not possible\\n\";else echo \"Minimum cost to sort strings is \" . $res; // This code is contributed by ita_c?>",
"e": 38775,
"s": 36524,
"text": null
},
{
"code": "<script> // Javascript program to get minimum cost to sort// strings by reversal operation // Returns minimum cost for sorting arr[] // using reverse operation. This function // returns -1 if it is not possible to sort. function minCost(arr,cost,N) { // dp[i][j] represents the minimum cost to // make first i strings sorted. // j = 1 means i'th string is reversed. // j = 0 means i'th string is not reversed. let dp=new Array(N); for(let i=0;i<N;i++) { dp[i]=new Array(2); for(let j=0;j<2;j++) { dp[i][j]=0; } } // initializing dp array for first string dp[0][0] = 0; dp[0][1] = cost[0]; // getting array of reversed strings let revStr = new Array(N); for(let i=0;i<N;i++) { revStr[i]=\"\"; } for (let i = 0; i < N; i++) { revStr[i] = arr[i]; revStr[i] = reverse(revStr[i], 0, revStr[i].length - 1); } let curStr = \"\"; let curCost; // looping for all strings for (let i = 1; i < N; i++) { // Looping twice, once for string and once // for reversed string for (let j = 0; j < 2; j++) { dp[i][j] = Number.MAX_VALUE; // getting current string and current // cost according to j curStr = (j == 0) ? arr[i] : revStr[i]; curCost = (j == 0) ? 0 : cost[i]; // Update dp value only if current string // is lexicographically larger if (curStr>=arr[i - 1]) dp[i][j] = Math.min(dp[i][j], dp[i - 1][0] + curCost); if (curStr>=revStr[i - 1]) dp[i][j] = Math.min(dp[i][j], dp[i - 1][1] + curCost); } } // getting minimum from both entries of last index let res = Math.min(dp[N - 1][0], dp[N - 1][1]); return (res == Number.MAX_VALUE)? -1 : res; } function reverse(s,start,end) { // Temporary variable to store character let temp; let str=s.split(\"\"); while (start <= end) { // Swapping the first and last character temp = str[start]; str[start] = str[end]; str[end] = temp; start++; end--; } return str.toString(); } // Driver Code let arr=[\"aa\", \"ba\", \"ac\"]; let cost=[1, 3, 1]; let N = arr.length; let res = minCost(arr, cost, N); if (res == -1) document.write(\"Sorting not possible\\n\"); else document.write(\"Minimum cost to \" + \"sort strings is \" + res); // This code is contributed by avanitrachhadiya2155 </script>",
"e": 41844,
"s": 38775,
"text": null
},
{
"code": null,
"e": 41853,
"s": 41844,
"text": "Output: "
},
{
"code": null,
"e": 41887,
"s": 41853,
"text": "Minimum cost to sort strings is 1"
},
{
"code": null,
"e": 41909,
"s": 41887,
"text": "Time Complexity: O(N)"
},
{
"code": null,
"e": 42354,
"s": 41909,
"text": "Auxiliary Space: O(N)This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 42360,
"s": 42354,
"text": "ukasp"
},
{
"code": null,
"e": 42370,
"s": 42360,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 42383,
"s": 42370,
"text": "princi singh"
},
{
"code": null,
"e": 42404,
"s": 42383,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 42420,
"s": 42404,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 42436,
"s": 42420,
"text": "rohitsingh07052"
},
{
"code": null,
"e": 42456,
"s": 42436,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 42464,
"s": 42456,
"text": "Strings"
},
{
"code": null,
"e": 42472,
"s": 42464,
"text": "Strings"
},
{
"code": null,
"e": 42492,
"s": 42472,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 42590,
"s": 42492,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 42633,
"s": 42590,
"text": "Maximum size square sub-matrix with all 1s"
},
{
"code": null,
"e": 42693,
"s": 42633,
"text": "Optimal Substructure Property in Dynamic Programming | DP-2"
},
{
"code": null,
"e": 42714,
"s": 42693,
"text": "Min Cost Path | DP-6"
},
{
"code": null,
"e": 42749,
"s": 42714,
"text": "Optimal Binary Search Tree | DP-24"
},
{
"code": null,
"e": 42778,
"s": 42749,
"text": "Box Stacking Problem | DP-22"
},
{
"code": null,
"e": 42824,
"s": 42778,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 42849,
"s": 42824,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 42909,
"s": 42849,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 42924,
"s": 42909,
"text": "C++ Data Types"
}
]
|
How to Delete a Pivot Table in Excel? - GeeksforGeeks | 15 May, 2021
A pivot table is a tool in Excel that allows you to quickly summarize data in the spreadsheet. When it comes to deleting a Pivot Table, there are a few different ways you can do this.
The method you choose will depend on how you want to delete the Pivot Table.
Steps to delete the Pivot table and the Resulting Data-
Select any cell in the Pivot Table
Select the ‘Analyze’ tab.
Click on the ‘Select’ option in the Actions group.
Choose Entire Pivot table
Hit the Delete key.
If we want to delete the entire pivot table but retain the resulting data, the procedure is more or less the same
Steps to delete the Pivot table but Keep the Resulting Data:
Select any cell in the Pivot Table
Choose the ‘Analyze’ tab in the ribbon.
In the Actions group, choose the ‘Select’ option.
Select the Entire Pivot table.
Right-click on any cell of the selected Pivot Table.
Click on Copy. This will copy the data of the entire Pivot Table.
Click the Home tab. Click on the Paste option. In the Paste Values section, click on the first icon.
The above steps would delete the Pivot Table but still keep the resulting data.
Below are the steps to keep the Pivot table and remove the resulting data only:
Select any cell in the Pivot Table
Choose the ‘Analyze’ tab in the ribbon.
Select the ‘Clear’ option in the actions group. Choose the ‘Clear All’ option.
We have learned the easy way of removing or deleting the pivot table in Excel. But deleting many pivot tables in a workbook is not that easy. So we need VBA code to delete pivot tables in one go
Below is VBA code:
Sub DeleteAllPivotTables()
Dim Ws As Worksheet, Pt As PivotTable
On Error Resume Next
For Each Ws In ActiveWorkbook.Worksheets
For Each Pt In Ws.PivotTables
Ws.Range(Pt.TableRange2.Address).Delete Shift:=xlUp
Next Pt
Next Ws
End Sub
This code needs to be placed in the regular module in the VB Editor
Below are the steps to put this code in the module:
Open an Excel sheet.
Use the shortcut ALT + F11(it will open the VBA Editor window).
In this VBA Editor window, on the left, there is a project explorer. Right-click on any object in the sheet where you want this code to work.
Hover the cursor on Insert. Click on Module. This will insert a new module for the current worksheet.
In the module window, write VBA code, as the code will run it will remove all pivot tables.
Things to Remember
We can remove the Excel pivot table and pivot worksheet as well.
Once the Excel pivot table is removed by using VBA code we cannot undo the action, so it is safe to have a backup copy.
Once the Excel pivot table is removed any changes in the database will not reflect on the removed field.
Picked
Excel
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Use Solver in Excel?
How to Find the Last Used Row and Column in Excel VBA?
How to Get Length of Array in Excel VBA?
Using CHOOSE Function along with VLOOKUP in Excel
Macros in Excel
Introduction to Excel Spreadsheet
How to Extract the Last Word From a Cell in Excel?
How to Show Percentages in Stacked Column Chart in Excel?
How to Remove Duplicates From Array Using VBA in Excel?
How to Sum Values Based on Criteria in Another Column in Excel? | [
{
"code": null,
"e": 26289,
"s": 26261,
"text": "\n15 May, 2021"
},
{
"code": null,
"e": 26473,
"s": 26289,
"text": "A pivot table is a tool in Excel that allows you to quickly summarize data in the spreadsheet. When it comes to deleting a Pivot Table, there are a few different ways you can do this."
},
{
"code": null,
"e": 26550,
"s": 26473,
"text": "The method you choose will depend on how you want to delete the Pivot Table."
},
{
"code": null,
"e": 26606,
"s": 26550,
"text": "Steps to delete the Pivot table and the Resulting Data-"
},
{
"code": null,
"e": 26641,
"s": 26606,
"text": "Select any cell in the Pivot Table"
},
{
"code": null,
"e": 26667,
"s": 26641,
"text": "Select the ‘Analyze’ tab."
},
{
"code": null,
"e": 26718,
"s": 26667,
"text": "Click on the ‘Select’ option in the Actions group."
},
{
"code": null,
"e": 26744,
"s": 26718,
"text": "Choose Entire Pivot table"
},
{
"code": null,
"e": 26764,
"s": 26744,
"text": "Hit the Delete key."
},
{
"code": null,
"e": 26878,
"s": 26764,
"text": "If we want to delete the entire pivot table but retain the resulting data, the procedure is more or less the same"
},
{
"code": null,
"e": 26939,
"s": 26878,
"text": "Steps to delete the Pivot table but Keep the Resulting Data:"
},
{
"code": null,
"e": 26974,
"s": 26939,
"text": "Select any cell in the Pivot Table"
},
{
"code": null,
"e": 27014,
"s": 26974,
"text": "Choose the ‘Analyze’ tab in the ribbon."
},
{
"code": null,
"e": 27064,
"s": 27014,
"text": "In the Actions group, choose the ‘Select’ option."
},
{
"code": null,
"e": 27095,
"s": 27064,
"text": "Select the Entire Pivot table."
},
{
"code": null,
"e": 27148,
"s": 27095,
"text": "Right-click on any cell of the selected Pivot Table."
},
{
"code": null,
"e": 27214,
"s": 27148,
"text": "Click on Copy. This will copy the data of the entire Pivot Table."
},
{
"code": null,
"e": 27315,
"s": 27214,
"text": "Click the Home tab. Click on the Paste option. In the Paste Values section, click on the first icon."
},
{
"code": null,
"e": 27395,
"s": 27315,
"text": "The above steps would delete the Pivot Table but still keep the resulting data."
},
{
"code": null,
"e": 27475,
"s": 27395,
"text": "Below are the steps to keep the Pivot table and remove the resulting data only:"
},
{
"code": null,
"e": 27510,
"s": 27475,
"text": "Select any cell in the Pivot Table"
},
{
"code": null,
"e": 27550,
"s": 27510,
"text": "Choose the ‘Analyze’ tab in the ribbon."
},
{
"code": null,
"e": 27629,
"s": 27550,
"text": "Select the ‘Clear’ option in the actions group. Choose the ‘Clear All’ option."
},
{
"code": null,
"e": 27824,
"s": 27629,
"text": "We have learned the easy way of removing or deleting the pivot table in Excel. But deleting many pivot tables in a workbook is not that easy. So we need VBA code to delete pivot tables in one go"
},
{
"code": null,
"e": 27843,
"s": 27824,
"text": "Below is VBA code:"
},
{
"code": null,
"e": 28092,
"s": 27843,
"text": "Sub DeleteAllPivotTables()\nDim Ws As Worksheet, Pt As PivotTable\nOn Error Resume Next\nFor Each Ws In ActiveWorkbook.Worksheets\n For Each Pt In Ws.PivotTables\n Ws.Range(Pt.TableRange2.Address).Delete Shift:=xlUp\n Next Pt\nNext Ws\nEnd Sub"
},
{
"code": null,
"e": 28160,
"s": 28092,
"text": "This code needs to be placed in the regular module in the VB Editor"
},
{
"code": null,
"e": 28212,
"s": 28160,
"text": "Below are the steps to put this code in the module:"
},
{
"code": null,
"e": 28233,
"s": 28212,
"text": "Open an Excel sheet."
},
{
"code": null,
"e": 28297,
"s": 28233,
"text": "Use the shortcut ALT + F11(it will open the VBA Editor window)."
},
{
"code": null,
"e": 28439,
"s": 28297,
"text": "In this VBA Editor window, on the left, there is a project explorer. Right-click on any object in the sheet where you want this code to work."
},
{
"code": null,
"e": 28541,
"s": 28439,
"text": "Hover the cursor on Insert. Click on Module. This will insert a new module for the current worksheet."
},
{
"code": null,
"e": 28633,
"s": 28541,
"text": "In the module window, write VBA code, as the code will run it will remove all pivot tables."
},
{
"code": null,
"e": 28652,
"s": 28633,
"text": "Things to Remember"
},
{
"code": null,
"e": 28717,
"s": 28652,
"text": "We can remove the Excel pivot table and pivot worksheet as well."
},
{
"code": null,
"e": 28837,
"s": 28717,
"text": "Once the Excel pivot table is removed by using VBA code we cannot undo the action, so it is safe to have a backup copy."
},
{
"code": null,
"e": 28942,
"s": 28837,
"text": "Once the Excel pivot table is removed any changes in the database will not reflect on the removed field."
},
{
"code": null,
"e": 28949,
"s": 28942,
"text": "Picked"
},
{
"code": null,
"e": 28955,
"s": 28949,
"text": "Excel"
},
{
"code": null,
"e": 29053,
"s": 28955,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29081,
"s": 29053,
"text": "How to Use Solver in Excel?"
},
{
"code": null,
"e": 29136,
"s": 29081,
"text": "How to Find the Last Used Row and Column in Excel VBA?"
},
{
"code": null,
"e": 29177,
"s": 29136,
"text": "How to Get Length of Array in Excel VBA?"
},
{
"code": null,
"e": 29227,
"s": 29177,
"text": "Using CHOOSE Function along with VLOOKUP in Excel"
},
{
"code": null,
"e": 29243,
"s": 29227,
"text": "Macros in Excel"
},
{
"code": null,
"e": 29277,
"s": 29243,
"text": "Introduction to Excel Spreadsheet"
},
{
"code": null,
"e": 29328,
"s": 29277,
"text": "How to Extract the Last Word From a Cell in Excel?"
},
{
"code": null,
"e": 29386,
"s": 29328,
"text": "How to Show Percentages in Stacked Column Chart in Excel?"
},
{
"code": null,
"e": 29442,
"s": 29386,
"text": "How to Remove Duplicates From Array Using VBA in Excel?"
}
]
|
How to create a Read More component in ReactJS? - GeeksforGeeks | 03 Mar, 2021
The following example covers how to create a Read More component in React JS using useState() hook.
Prerequisite:
Basic knowledge of npm & create-react-app command.
Basic Knowledge of useState() React hooks.
Basic Setup: You will start a new project using create-react-app using the following command:
npx create-react-app react-read-more
Now go to your react-read-more folder by typing the given command in the terminal.
cd react-read-more
Now create the components folder in src then go to the components folder and create one file ReadMore.js.
Project Structure: The file structure in the project will look like this.
Example: In this example, we will design a Read more component, for that we will need to manipulate the App.js file and other created components file.
Show & Hide text, that’s where the role of useState() hook comes into play. We create a functional component Read More() in which we create a state with first element isReadMore as an initial state having a value of the true and the second element as function setIsReadMore() for updating state. Then a function is created by the name toggleReadMore which sets the value of the state isReadMore to the opposite of its present value whenever it is called.
The value of state isReadMore decides how much text has to be shown with help of a conditional operator. When our state’s value is true, it only shows the first 150 characters of our text with the help of string.slice(). You can choose any number of characters as per your choice. And a ‘read more’ link is also shown at the end. Otherwise, it shows the entire text and a ‘show less’ link at the end.
When we click on the ‘read more’ link, toggleReadMore sets the state value to false with the help of onClick function due to which we see the entire text with a ‘show less’ link at its end. And when we click on ‘show less’ link, it sets the state value to true which only shows a slice of our text with a ‘read more’ link at its end.
We write our text in a different functional component Content() and enclose it with a <ReadMore> tag due to which it becomes a child for ReadMore() function. That’s why we first destructure the children’s property in ReadMore() function so that we can access its value in our text string and implement the logic discussed above.
ReadMore.js
import React, { useState } from "react";import "../App.css"; const ReadMore = ({ children }) => { const text = children; const [isReadMore, setIsReadMore] = useState(true); const toggleReadMore = () => { setIsReadMore(!isReadMore); }; return ( <p className="text"> {isReadMore ? text.slice(0, 150) : text} <span onClick={toggleReadMore} className="read-or-hide"> {isReadMore ? "...read more" : " show less"} </span> </p> );}; const Content = () => { return ( <div className="container"> <h2> <ReadMore> GeeksforGeeks: A Computer Science portal for geeks. It contains well written, well thought and well explained computer science, programming articles and quizzes. It provides a variety of services for you to learn, so thrive and also have fun! Free Tutorials, Millions of Articles, Live, Online and Classroom Courses ,Frequent Coding Competitions, Webinars by Industry Experts, Internship opportunities, and Job Opportunities. Knowledge is power! </ReadMore> </h2> </div> );}; export default Content;
App.css
.container{ position: absolute; top: 10%; left: 23%; width: 50%;} .text{ display: inline; width: 100%;} .read-or-hide{ color: rgb(192,192,192); cursor: pointer;}
App.js
import Content from './components/ReadMore' function App() { return ( <Content /> );} export default App;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to set background images in ReactJS ?
How to create a table in ReactJS ?
ReactJS useNavigate() Hook
How to navigate on path by button click in react router ?
React-Router Hooks
Roadmap to Become a Web Developer in 2022
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Convert a string to an integer in JavaScript
Installation of Node.js on Linux
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 24852,
"s": 24824,
"text": "\n03 Mar, 2021"
},
{
"code": null,
"e": 24952,
"s": 24852,
"text": "The following example covers how to create a Read More component in React JS using useState() hook."
},
{
"code": null,
"e": 24966,
"s": 24952,
"text": "Prerequisite:"
},
{
"code": null,
"e": 25017,
"s": 24966,
"text": "Basic knowledge of npm & create-react-app command."
},
{
"code": null,
"e": 25060,
"s": 25017,
"text": "Basic Knowledge of useState() React hooks."
},
{
"code": null,
"e": 25154,
"s": 25060,
"text": "Basic Setup: You will start a new project using create-react-app using the following command:"
},
{
"code": null,
"e": 25191,
"s": 25154,
"text": "npx create-react-app react-read-more"
},
{
"code": null,
"e": 25274,
"s": 25191,
"text": "Now go to your react-read-more folder by typing the given command in the terminal."
},
{
"code": null,
"e": 25293,
"s": 25274,
"text": "cd react-read-more"
},
{
"code": null,
"e": 25399,
"s": 25293,
"text": "Now create the components folder in src then go to the components folder and create one file ReadMore.js."
},
{
"code": null,
"e": 25473,
"s": 25399,
"text": "Project Structure: The file structure in the project will look like this."
},
{
"code": null,
"e": 25624,
"s": 25473,
"text": "Example: In this example, we will design a Read more component, for that we will need to manipulate the App.js file and other created components file."
},
{
"code": null,
"e": 26079,
"s": 25624,
"text": "Show & Hide text, that’s where the role of useState() hook comes into play. We create a functional component Read More() in which we create a state with first element isReadMore as an initial state having a value of the true and the second element as function setIsReadMore() for updating state. Then a function is created by the name toggleReadMore which sets the value of the state isReadMore to the opposite of its present value whenever it is called."
},
{
"code": null,
"e": 26480,
"s": 26079,
"text": "The value of state isReadMore decides how much text has to be shown with help of a conditional operator. When our state’s value is true, it only shows the first 150 characters of our text with the help of string.slice(). You can choose any number of characters as per your choice. And a ‘read more’ link is also shown at the end. Otherwise, it shows the entire text and a ‘show less’ link at the end."
},
{
"code": null,
"e": 26814,
"s": 26480,
"text": "When we click on the ‘read more’ link, toggleReadMore sets the state value to false with the help of onClick function due to which we see the entire text with a ‘show less’ link at its end. And when we click on ‘show less’ link, it sets the state value to true which only shows a slice of our text with a ‘read more’ link at its end."
},
{
"code": null,
"e": 27143,
"s": 26814,
"text": "We write our text in a different functional component Content() and enclose it with a <ReadMore> tag due to which it becomes a child for ReadMore() function. That’s why we first destructure the children’s property in ReadMore() function so that we can access its value in our text string and implement the logic discussed above."
},
{
"code": null,
"e": 27155,
"s": 27143,
"text": "ReadMore.js"
},
{
"code": "import React, { useState } from \"react\";import \"../App.css\"; const ReadMore = ({ children }) => { const text = children; const [isReadMore, setIsReadMore] = useState(true); const toggleReadMore = () => { setIsReadMore(!isReadMore); }; return ( <p className=\"text\"> {isReadMore ? text.slice(0, 150) : text} <span onClick={toggleReadMore} className=\"read-or-hide\"> {isReadMore ? \"...read more\" : \" show less\"} </span> </p> );}; const Content = () => { return ( <div className=\"container\"> <h2> <ReadMore> GeeksforGeeks: A Computer Science portal for geeks. It contains well written, well thought and well explained computer science, programming articles and quizzes. It provides a variety of services for you to learn, so thrive and also have fun! Free Tutorials, Millions of Articles, Live, Online and Classroom Courses ,Frequent Coding Competitions, Webinars by Industry Experts, Internship opportunities, and Job Opportunities. Knowledge is power! </ReadMore> </h2> </div> );}; export default Content;",
"e": 28305,
"s": 27155,
"text": null
},
{
"code": null,
"e": 28313,
"s": 28305,
"text": "App.css"
},
{
"code": ".container{ position: absolute; top: 10%; left: 23%; width: 50%;} .text{ display: inline; width: 100%;} .read-or-hide{ color: rgb(192,192,192); cursor: pointer;}",
"e": 28485,
"s": 28313,
"text": null
},
{
"code": null,
"e": 28492,
"s": 28485,
"text": "App.js"
},
{
"code": "import Content from './components/ReadMore' function App() { return ( <Content /> );} export default App;",
"e": 28606,
"s": 28492,
"text": null
},
{
"code": null,
"e": 28719,
"s": 28606,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 28729,
"s": 28719,
"text": "npm start"
},
{
"code": null,
"e": 28828,
"s": 28729,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:"
},
{
"code": null,
"e": 28844,
"s": 28828,
"text": "React-Questions"
},
{
"code": null,
"e": 28852,
"s": 28844,
"text": "ReactJS"
},
{
"code": null,
"e": 28869,
"s": 28852,
"text": "Web Technologies"
},
{
"code": null,
"e": 28967,
"s": 28869,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29009,
"s": 28967,
"text": "How to set background images in ReactJS ?"
},
{
"code": null,
"e": 29044,
"s": 29009,
"text": "How to create a table in ReactJS ?"
},
{
"code": null,
"e": 29071,
"s": 29044,
"text": "ReactJS useNavigate() Hook"
},
{
"code": null,
"e": 29129,
"s": 29071,
"text": "How to navigate on path by button click in react router ?"
},
{
"code": null,
"e": 29148,
"s": 29129,
"text": "React-Router Hooks"
},
{
"code": null,
"e": 29190,
"s": 29148,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 29252,
"s": 29190,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 29297,
"s": 29252,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29330,
"s": 29297,
"text": "Installation of Node.js on Linux"
}
]
|
Merge Sort | Practice | GeeksforGeeks | Given an array arr[], its starting position l and its ending position r. Sort the array using merge sort algorithm.
Example 1:
Input:
N = 5
arr[] = {4 1 3 9 7}
Output:
1 3 4 7 9
Example 2:
Input:
N = 10
arr[] = {10 9 8 7 6 5 4 3 2 1}
Output:
1 2 3 4 5 6 7 8 9 10
Constraints:
1 <= N <= 105
1 <= arr[i] <= 103
0
adityakmcs2 days ago
this code giving me runtime error pls help
void merge(int arr[], int l, int m, int h) { // Your code here int i=l,j=m+1,k=l; int B[h+1]; while(i<=m&&j<=h){ if(arr[i]<arr[j]) B[k++]=arr[i++]; else B[k++]=arr[j++]; } for(;i<=j;i++){ B[k++]=arr[j++]; } for(;j<=h;j++){ B[k++]=arr[j]; } for(int i=l;i<=j;i++){ arr[i]=B[i]; } // return; } public: void mergeSort(int arr[], int l, int h) { //code here if(l<h){ int mid = (l+h)/2; mergeSort(arr,l,mid); mergeSort(arr,mid+1,h); merge(arr,l,mid,h); } // return ; }
0
shanu145 days ago
void merge(int arr[], int l, int m, int r)
{
// Your code here
int len1=m-l+1;
int len2=r-m;
int* a=new int[len1];
int* b=new int[len2];
int k=l;
for(int i=0;i<len1;i++){
a[i]=arr[k++];
}
k=m+1;
for(int i=0;i<len2;i++){
b[i]=arr[k++];
}
int index1=0;
int index2=0;
k=l;
while(index1<len1&&index2<len2){
if(a[index1]<b[index2]){
arr[k++]=a[index1++];
}
else{
arr[k++]=b[index2++];
}
}
while(index1<len1){
arr[k++]=a[index1++];
}
while(index2<len2){
arr[k++]=b[index2++];
}
}
public:
void mergeSort(int arr[], int l, int r)
{
//code here
int mid=(l+r)/2;
if(l<r){
mergeSort(arr,l,mid);
mergeSort(arr,mid+1,r);
merge(arr,l,mid,r);
}
}
-1
tejaswayadav2 weeks ago
Java Solution, but gives TLE:class Solution{ void merge(int arr[], int l, int m, int r) { int[] newArr = new int[r-l+1]; int i = l, j=m +1, k=0; while(i <= m && j <= r){ if(arr[i] <= arr[j]) { newArr[k++] = arr[i++]; } else{ newArr[k++] = arr[j++]; } } while(i <= m) { newArr[k++] = arr[i++]; } while(j <= r) { newArr[k++] = arr[j++]; } for (i=l; i<=r; i++) { arr[i] = newArr[i-l]; } } void mergeSort(int arr[], int l, int r) { if(l<r) { int m = (l+r)/2; mergeSort(arr,l,m); mergeSort(arr,m+1,r); merge(arr, l, m, r); } }}
0
karunakarmutthi3 weeks ago
can anyone say why code is showing TLE in 355 test case
void merge(int arr[], int l, int mid, int r) { int[] b=new int[arr.length]; int i=l; int j=mid+1; int k=l; while(i<=mid&&j<=r){ if(arr[i]<=arr[j]){ b[k++]=arr[i++]; }else{ b[k++]=arr[j++]; } } if(i>mid){ while(j<=r){ b[k++]=arr[j++]; } }else{ while(i<=mid){ b[k++]=arr[i++]; } } for(int p=l;p<=r;p++){ arr[p]=b[p]; } } void mergeSort(int arr[], int l, int r) { if(l<r){ int mid=(l+r)/2; mergeSort(arr,l,mid); mergeSort(arr,mid+1,r); merge(arr,l,mid,r); } }
0
alokkumar90193 weeks ago
void merge(int arr[], int l, int m, int r)
{
// Your code here
int n1=m-l+1, n2=r-m;
int left[n1], right[n2];
for(int i=0; i<n1; i++){
left[i]=arr[l+i];
}
for(int i=0; i<n2; i++){
right[i]=arr[m+1+i];
}
int i=0, j=0, k=l;
while(i<n1 && j<n2){
if(left[i]<=right[j]){
arr[k++]=left[i++];
} else{
arr[k++]=right[j++];
}
}
while(i<n1){
arr[k++]=left[i++];
}
while(j<n2){
arr[k++]=right[j++];
}
}
public:
void mergeSort(int arr[], int l, int r)
{
//code here
if(r>l){
int m=l+(r-l)/2;
mergeSort(arr,l,m);
mergeSort(arr,m+1,r);
merge(arr,l,m,r);
}
}
0
alokkumar9019
This comment was deleted.
0
namanv083 weeks ago
100% working c++ code
#include<iostream>
using namespace std;
void merge(int arr[],int l,int mid,int h){
if(l>=h){
return;
}
int len1=mid-l+1;
int len2=h-mid;
int first[len1];
int second[len2];
for(int i=0;i<len1;i++){
first[i]=arr[l+i];
}
for(int j=0;j<len2;j++){
second[j]=arr[mid+1+j];
}
int mainIndex=l;
int index1=0,index2=0;
while( index1<len1 && index2<len2){
if(first[index1]<=second[index2]){
arr[mainIndex]=first[index1];
mainIndex++;
index1++;
}
else{
arr[mainIndex]=second[index2];
mainIndex++;
index2++;
}
}
while(index1<len1){
arr[mainIndex++]=first[index1++];
}
while(index2<len2){
arr[mainIndex++]=second[index2++];
}
// delete[] first;
// delete[] second;
}
void mergesort(int arr[],int l,int h){
if(l>=h){
return ;
}
int mid=l+(h-l)/2;
mergesort(arr,l,mid);
mergesort(arr,mid+1,h);
merge(arr,l,mid,h);
}
int main(){
int n;
cout<<"Enter array size"<<" ";
cin>>n;
int arr[n];
cout<<"Enter array elements"<<" ";
for(int i=0;i<n;i++){
cin>>arr[i];
}
mergesort(arr,0,n-1);
for(int i=0;i<n;i++){
cout<<arr[i]<<" ";
}
return 0;
}
0
dhamanedivya9991 month ago
what is wrong with this code?
void merge(int arr[], int l, int m, int r) { int i =l; int j = m+1; int k =l; int b[500]; while(i<=m && j<=r){ if(arr[i]<arr[j]){ b[k++]= arr[i++]; } else{ b[k++]=arr[j++]; } } if(i>m){ while(j<=r){ b[k++]=arr[j++]; } } else{ while(i<=m){ b[k++]=arr[i++]; } } for( k =l;k<=r;k++){ arr[k] = b[k]; } } public: void mergeSort(int arr[], int l, int r) { if(l>=r){ return; } int m = l+(r-l)/2; mergeSort(arr,l,m); mergeSort(arr,m+1,r); merge(arr,l,m,r); }
0
dawsonquadros
This comment was deleted.
0
amishasahu3281 month ago
void merge(int arr[], int l, int m, int r)
{
// Your code here
int n1 = m-l+1, n2 = r-m;
int left[n1], right[n2];
for(int i = 0; i < n1; i++)
left[i] = arr[l+i];
for(int i = 0; i < n2; i++)
right[i] = arr[m+i+1];
int i = 0, j = 0, k = l;
while(i < n1 && j < n2)
{
if(left[i] <= right[j])
arr[k++] = left[i++];
else
arr[k++] = right[j++];
}
while(i < n1)
{
arr[k++] = left[i++];
}
while(j < n2)
{
arr[k++] = right[j++];
}
}
public:
void mergeSort(int arr[], int l, int r)
{
//code here
if(l >= r)
return;
int m = (l+r)/2;
mergeSort(arr, l, m);
mergeSort(arr, m+1, r);
merge(arr, l, m, r);
}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab. | [
{
"code": null,
"e": 365,
"s": 238,
"text": "Given an array arr[], its starting position l and its ending position r. Sort the array using merge sort algorithm.\nExample 1:"
},
{
"code": null,
"e": 417,
"s": 365,
"text": "Input:\nN = 5\narr[] = {4 1 3 9 7}\nOutput:\n1 3 4 7 9\n"
},
{
"code": null,
"e": 428,
"s": 417,
"text": "Example 2:"
},
{
"code": null,
"e": 502,
"s": 428,
"text": "Input:\nN = 10\narr[] = {10 9 8 7 6 5 4 3 2 1}\nOutput:\n1 2 3 4 5 6 7 8 9 10"
},
{
"code": null,
"e": 549,
"s": 502,
"text": "\nConstraints:\n1 <= N <= 105\n1 <= arr[i] <= 103"
},
{
"code": null,
"e": 551,
"s": 549,
"text": "0"
},
{
"code": null,
"e": 572,
"s": 551,
"text": "adityakmcs2 days ago"
},
{
"code": null,
"e": 615,
"s": 572,
"text": "this code giving me runtime error pls help"
},
{
"code": null,
"e": 1387,
"s": 622,
"text": " void merge(int arr[], int l, int m, int h) { // Your code here int i=l,j=m+1,k=l; int B[h+1]; while(i<=m&&j<=h){ if(arr[i]<arr[j]) B[k++]=arr[i++]; else B[k++]=arr[j++]; } for(;i<=j;i++){ B[k++]=arr[j++]; } for(;j<=h;j++){ B[k++]=arr[j]; } for(int i=l;i<=j;i++){ arr[i]=B[i]; } // return; } public: void mergeSort(int arr[], int l, int h) { //code here if(l<h){ int mid = (l+h)/2; mergeSort(arr,l,mid); mergeSort(arr,mid+1,h); merge(arr,l,mid,h); } // return ; }"
},
{
"code": null,
"e": 1389,
"s": 1387,
"text": "0"
},
{
"code": null,
"e": 1407,
"s": 1389,
"text": "shanu145 days ago"
},
{
"code": null,
"e": 2459,
"s": 1407,
"text": "void merge(int arr[], int l, int m, int r)\n {\n // Your code here\n int len1=m-l+1;\n int len2=r-m;\n int* a=new int[len1];\n int* b=new int[len2];\n \n int k=l;\n for(int i=0;i<len1;i++){\n a[i]=arr[k++];\n }\n k=m+1;\n for(int i=0;i<len2;i++){\n b[i]=arr[k++];\n }\n int index1=0;\n int index2=0;\n k=l;\n while(index1<len1&&index2<len2){\n if(a[index1]<b[index2]){\n arr[k++]=a[index1++];\n }\n else{\n arr[k++]=b[index2++];\n }\n }\n while(index1<len1){\n arr[k++]=a[index1++];\n }\n while(index2<len2){\n arr[k++]=b[index2++];\n }\n }\n public:\n void mergeSort(int arr[], int l, int r)\n {\n //code here\n int mid=(l+r)/2;\n if(l<r){\n mergeSort(arr,l,mid);\n mergeSort(arr,mid+1,r);\n merge(arr,l,mid,r);\n }\n }"
},
{
"code": null,
"e": 2462,
"s": 2459,
"text": "-1"
},
{
"code": null,
"e": 2486,
"s": 2462,
"text": "tejaswayadav2 weeks ago"
},
{
"code": null,
"e": 3275,
"s": 2486,
"text": "Java Solution, but gives TLE:class Solution{ void merge(int arr[], int l, int m, int r) { int[] newArr = new int[r-l+1]; int i = l, j=m +1, k=0; while(i <= m && j <= r){ if(arr[i] <= arr[j]) { newArr[k++] = arr[i++]; } else{ newArr[k++] = arr[j++]; } } while(i <= m) { newArr[k++] = arr[i++]; } while(j <= r) { newArr[k++] = arr[j++]; } for (i=l; i<=r; i++) { arr[i] = newArr[i-l]; } } void mergeSort(int arr[], int l, int r) { if(l<r) { int m = (l+r)/2; mergeSort(arr,l,m); mergeSort(arr,m+1,r); merge(arr, l, m, r); } }}"
},
{
"code": null,
"e": 3277,
"s": 3275,
"text": "0"
},
{
"code": null,
"e": 3304,
"s": 3277,
"text": "karunakarmutthi3 weeks ago"
},
{
"code": null,
"e": 3360,
"s": 3304,
"text": "can anyone say why code is showing TLE in 355 test case"
},
{
"code": null,
"e": 4081,
"s": 3362,
"text": "void merge(int arr[], int l, int mid, int r) { int[] b=new int[arr.length]; int i=l; int j=mid+1; int k=l; while(i<=mid&&j<=r){ if(arr[i]<=arr[j]){ b[k++]=arr[i++]; }else{ b[k++]=arr[j++]; } } if(i>mid){ while(j<=r){ b[k++]=arr[j++]; } }else{ while(i<=mid){ b[k++]=arr[i++]; } } for(int p=l;p<=r;p++){ arr[p]=b[p]; } } void mergeSort(int arr[], int l, int r) { if(l<r){ int mid=(l+r)/2; mergeSort(arr,l,mid); mergeSort(arr,mid+1,r); merge(arr,l,mid,r); } }"
},
{
"code": null,
"e": 4083,
"s": 4081,
"text": "0"
},
{
"code": null,
"e": 4108,
"s": 4083,
"text": "alokkumar90193 weeks ago"
},
{
"code": null,
"e": 4968,
"s": 4108,
"text": "void merge(int arr[], int l, int m, int r)\n {\n // Your code here\n int n1=m-l+1, n2=r-m;\n int left[n1], right[n2];\n for(int i=0; i<n1; i++){\n left[i]=arr[l+i];\n }\n for(int i=0; i<n2; i++){\n right[i]=arr[m+1+i];\n }\n int i=0, j=0, k=l;\n while(i<n1 && j<n2){\n if(left[i]<=right[j]){\n arr[k++]=left[i++];\n } else{\n arr[k++]=right[j++];\n }\n }\n while(i<n1){\n arr[k++]=left[i++];\n }\n while(j<n2){\n arr[k++]=right[j++];\n }\n }\n public:\n void mergeSort(int arr[], int l, int r)\n {\n //code here\n if(r>l){\n int m=l+(r-l)/2;\n mergeSort(arr,l,m);\n mergeSort(arr,m+1,r);\n merge(arr,l,m,r);\n }\n }"
},
{
"code": null,
"e": 4970,
"s": 4968,
"text": "0"
},
{
"code": null,
"e": 4984,
"s": 4970,
"text": "alokkumar9019"
},
{
"code": null,
"e": 5010,
"s": 4984,
"text": "This comment was deleted."
},
{
"code": null,
"e": 5012,
"s": 5010,
"text": "0"
},
{
"code": null,
"e": 5032,
"s": 5012,
"text": "namanv083 weeks ago"
},
{
"code": null,
"e": 5054,
"s": 5032,
"text": "100% working c++ code"
},
{
"code": null,
"e": 6366,
"s": 5056,
"text": "#include<iostream>\nusing namespace std;\n\nvoid merge(int arr[],int l,int mid,int h){\n\tif(l>=h){\n\t\treturn;\n\t}\n int len1=mid-l+1;\n int len2=h-mid;\n int first[len1];\n int second[len2];\n for(int i=0;i<len1;i++){\n first[i]=arr[l+i];\n }\n for(int j=0;j<len2;j++){\n second[j]=arr[mid+1+j];\n }\n int mainIndex=l;\n int index1=0,index2=0;\n while( index1<len1 && index2<len2){\n if(first[index1]<=second[index2]){\n arr[mainIndex]=first[index1];\n mainIndex++;\n index1++;\n }\n else{\n arr[mainIndex]=second[index2];\n mainIndex++;\n index2++;\n }\n }\n while(index1<len1){\n arr[mainIndex++]=first[index1++];\n }\n while(index2<len2){\n arr[mainIndex++]=second[index2++];\n }\n// delete[] first;\n// delete[] second;\n}\nvoid mergesort(int arr[],int l,int h){\n if(l>=h){\n \treturn ;\n\t}\n int mid=l+(h-l)/2;\n mergesort(arr,l,mid);\n mergesort(arr,mid+1,h);\n merge(arr,l,mid,h);\n}\nint main(){\n int n;\n cout<<\"Enter array size\"<<\" \";\n cin>>n;\n int arr[n];\n cout<<\"Enter array elements\"<<\" \";\n for(int i=0;i<n;i++){\n cin>>arr[i];\n }\n mergesort(arr,0,n-1);\n for(int i=0;i<n;i++){\n \tcout<<arr[i]<<\" \";\n\t}\n return 0;\n}"
},
{
"code": null,
"e": 6368,
"s": 6366,
"text": "0"
},
{
"code": null,
"e": 6395,
"s": 6368,
"text": "dhamanedivya9991 month ago"
},
{
"code": null,
"e": 6425,
"s": 6395,
"text": "what is wrong with this code?"
},
{
"code": null,
"e": 7202,
"s": 6427,
"text": "void merge(int arr[], int l, int m, int r) { int i =l; int j = m+1; int k =l; int b[500]; while(i<=m && j<=r){ if(arr[i]<arr[j]){ b[k++]= arr[i++]; } else{ b[k++]=arr[j++]; } } if(i>m){ while(j<=r){ b[k++]=arr[j++]; } } else{ while(i<=m){ b[k++]=arr[i++]; } } for( k =l;k<=r;k++){ arr[k] = b[k]; } } public: void mergeSort(int arr[], int l, int r) { if(l>=r){ return; } int m = l+(r-l)/2; mergeSort(arr,l,m); mergeSort(arr,m+1,r); merge(arr,l,m,r); }"
},
{
"code": null,
"e": 7204,
"s": 7202,
"text": "0"
},
{
"code": null,
"e": 7218,
"s": 7204,
"text": "dawsonquadros"
},
{
"code": null,
"e": 7244,
"s": 7218,
"text": "This comment was deleted."
},
{
"code": null,
"e": 7246,
"s": 7244,
"text": "0"
},
{
"code": null,
"e": 7271,
"s": 7246,
"text": "amishasahu3281 month ago"
},
{
"code": null,
"e": 8212,
"s": 7271,
"text": "void merge(int arr[], int l, int m, int r)\n {\n // Your code here\n int n1 = m-l+1, n2 = r-m;\n int left[n1], right[n2];\n for(int i = 0; i < n1; i++)\n left[i] = arr[l+i];\n for(int i = 0; i < n2; i++)\n right[i] = arr[m+i+1];\n \n int i = 0, j = 0, k = l;\n while(i < n1 && j < n2)\n {\n if(left[i] <= right[j])\n arr[k++] = left[i++];\n else\n arr[k++] = right[j++];\n }\n while(i < n1)\n {\n arr[k++] = left[i++];\n }\n while(j < n2)\n {\n arr[k++] = right[j++];\n }\n }\n public:\n void mergeSort(int arr[], int l, int r)\n {\n //code here\n if(l >= r)\n return;\n \n int m = (l+r)/2;\n mergeSort(arr, l, m);\n mergeSort(arr, m+1, r);\n merge(arr, l, m, r);\n }"
},
{
"code": null,
"e": 8358,
"s": 8212,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 8394,
"s": 8358,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 8404,
"s": 8394,
"text": "\nProblem\n"
},
{
"code": null,
"e": 8414,
"s": 8404,
"text": "\nContest\n"
},
{
"code": null,
"e": 8477,
"s": 8414,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 8625,
"s": 8477,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 8833,
"s": 8625,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 8939,
"s": 8833,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
]
|
Proper Ways to Pass Environment Variables in JSON for cURL POST | by Xu LIANG | Towards Data Science | The best practice is using a data generation function. Scrolling to the bottom for the detail.
When we build an API-based web (front-end and back-end separated), we usually want to see what the HTTP client is sending or to inspect and debug webhook requests. There are two approaches:
Build an API server by ourselves
Use a fake mock API server
In this post, we choose the second approach and use RequestBin.
The usage is super simple. The mock API server will be ready after clicking the button.
Run the below command to make a POST request:
$ curl -X POST https://requestbin.io/1bk0un41 -H "Content-Type: application/json" -d '{ "property1":"value1", "property2":"value2" }'
Refresh the web and confirm the status:
Run printenv will show the environment variable:
$ printenvLC_TERMINAL=iTerm2COLORTERM=truecolorTERM=xterm-256colorHOME=/Users/smap10...
We want to replace the value of property1 with TERM variable:
$ curl -X POST https://requestbin.io/1bk0un41 -H "Content-Type: application/json" -d '{ "property1":"$TERM", "property2":"value2" }'
But it seems TERM is not recognized as an environment variable.
$ curl -X POST https://requestbin.io/1bk0un41 -H "Content-Type: application/json" -d '{ "property1":"'"$TERM"'", "property2":"value2" }'
We can see the result is what we want.
The Outermost layer uses double-quotes. And add escaping mark for each double quote in the JSON data part.
$ curl -X POST https://requestbin.io/1bk0un41 -H "Content-Type: application/json" -d "{ \"property1\":\"$TERM\", \"property2\":\"value2\" }"
This method can save us from all sort of headaches concerning shell quoting and makes it easier to read and maintain.
generate_post_data(){ cat <<EOF{ "property1":"$TERM", "property2":"value2"}EOF}
Add the function to curl:
$ curl -X POST https://requestbin.io/1bk0un41 -H "Content-Type: application/json" -d "$(generate_post_data)"
Check out my other posts on Medium with a categorized view!GitHub: BrambleXuLinkedIn: Xu LiangBlog: BrambleXu.com
Understanding And Using REST APIs
How to include environment variable in bash line CURL?
Using curl POST with variables defined in bash script functions | [
{
"code": null,
"e": 266,
"s": 171,
"text": "The best practice is using a data generation function. Scrolling to the bottom for the detail."
},
{
"code": null,
"e": 456,
"s": 266,
"text": "When we build an API-based web (front-end and back-end separated), we usually want to see what the HTTP client is sending or to inspect and debug webhook requests. There are two approaches:"
},
{
"code": null,
"e": 489,
"s": 456,
"text": "Build an API server by ourselves"
},
{
"code": null,
"e": 516,
"s": 489,
"text": "Use a fake mock API server"
},
{
"code": null,
"e": 580,
"s": 516,
"text": "In this post, we choose the second approach and use RequestBin."
},
{
"code": null,
"e": 668,
"s": 580,
"text": "The usage is super simple. The mock API server will be ready after clicking the button."
},
{
"code": null,
"e": 714,
"s": 668,
"text": "Run the below command to make a POST request:"
},
{
"code": null,
"e": 848,
"s": 714,
"text": "$ curl -X POST https://requestbin.io/1bk0un41 -H \"Content-Type: application/json\" -d '{ \"property1\":\"value1\", \"property2\":\"value2\" }'"
},
{
"code": null,
"e": 888,
"s": 848,
"text": "Refresh the web and confirm the status:"
},
{
"code": null,
"e": 937,
"s": 888,
"text": "Run printenv will show the environment variable:"
},
{
"code": null,
"e": 1025,
"s": 937,
"text": "$ printenvLC_TERMINAL=iTerm2COLORTERM=truecolorTERM=xterm-256colorHOME=/Users/smap10..."
},
{
"code": null,
"e": 1087,
"s": 1025,
"text": "We want to replace the value of property1 with TERM variable:"
},
{
"code": null,
"e": 1221,
"s": 1087,
"text": "$ curl -X POST https://requestbin.io/1bk0un41 -H \"Content-Type: application/json\" -d '{ \"property1\":\"$TERM\", \"property2\":\"value2\" }'"
},
{
"code": null,
"e": 1285,
"s": 1221,
"text": "But it seems TERM is not recognized as an environment variable."
},
{
"code": null,
"e": 1423,
"s": 1285,
"text": "$ curl -X POST https://requestbin.io/1bk0un41 -H \"Content-Type: application/json\" -d '{ \"property1\":\"'\"$TERM\"'\", \"property2\":\"value2\" }'"
},
{
"code": null,
"e": 1462,
"s": 1423,
"text": "We can see the result is what we want."
},
{
"code": null,
"e": 1569,
"s": 1462,
"text": "The Outermost layer uses double-quotes. And add escaping mark for each double quote in the JSON data part."
},
{
"code": null,
"e": 1710,
"s": 1569,
"text": "$ curl -X POST https://requestbin.io/1bk0un41 -H \"Content-Type: application/json\" -d \"{ \\\"property1\\\":\\\"$TERM\\\", \\\"property2\\\":\\\"value2\\\" }\""
},
{
"code": null,
"e": 1828,
"s": 1710,
"text": "This method can save us from all sort of headaches concerning shell quoting and makes it easier to read and maintain."
},
{
"code": null,
"e": 1912,
"s": 1828,
"text": "generate_post_data(){ cat <<EOF{ \"property1\":\"$TERM\", \"property2\":\"value2\"}EOF}"
},
{
"code": null,
"e": 1938,
"s": 1912,
"text": "Add the function to curl:"
},
{
"code": null,
"e": 2047,
"s": 1938,
"text": "$ curl -X POST https://requestbin.io/1bk0un41 -H \"Content-Type: application/json\" -d \"$(generate_post_data)\""
},
{
"code": null,
"e": 2161,
"s": 2047,
"text": "Check out my other posts on Medium with a categorized view!GitHub: BrambleXuLinkedIn: Xu LiangBlog: BrambleXu.com"
},
{
"code": null,
"e": 2195,
"s": 2161,
"text": "Understanding And Using REST APIs"
},
{
"code": null,
"e": 2250,
"s": 2195,
"text": "How to include environment variable in bash line CURL?"
}
]
|
Evaluation of Expression Tree - GeeksforGeeks | 15 Mar, 2022
Given a simple expression tree, consisting of basic binary operators i.e., + , – ,* and / and some integers, evaluate the expression tree.
Examples:
Input: Root node of the below tree
Output:100
Input: Root node of the below tree
Output: 110
Approach: The approach to solve this problem is based on following observation:
As all the operators in the tree are binary, hence each node will have either 0 or 2 children. As it can be inferred from the examples above, all the integer values would appear at the leaf nodes, while the interior nodes represent the operators.
Therefore we can do inorder traversal of the binary tree and evaluate the expression as we move ahead.
To evaluate the syntax tree, a recursive approach can be followed.
Algorithm:
Let t be the syntax tree
If t is not null then If t.info is operand then Return t.infoElseA = solve(t.left)B = solve(t.right)return A operator B, where operator is the info contained in t
If t.info is operand then Return t.info
Return t.info
ElseA = solve(t.left)B = solve(t.right)return A operator B, where operator is the info contained in t
A = solve(t.left)
B = solve(t.right)
return A operator B, where operator is the info contained in t
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to evaluate an expression tree#include <bits/stdc++.h>using namespace std; // Class to represent the nodes of syntax treeclass node{public: string info; node *left = NULL, *right = NULL; node(string x) { info = x; }}; // Utility function to return the integer value// of a given stringint toInt(string s){ int num = 0; // Check if the integral value is // negative or not // If it is not negative, generate the number // normally if(s[0]!='-') for (int i=0; i<s.length(); i++) num = num*10 + (int(s[i])-48); // If it is negative, calculate the +ve number // first ignoring the sign and invert the // sign at the end else { for (int i=1; i<s.length(); i++) num = num*10 + (int(s[i])-48); num = num*-1; } return num;} // This function receives a node of the syntax tree// and recursively evaluates itint eval(node* root){ // empty tree if (!root) return 0; // leaf node i.e, an integer if (!root->left && !root->right) return toInt(root->info); // Evaluate left subtree int l_val = eval(root->left); // Evaluate right subtree int r_val = eval(root->right); // Check which operator to apply if (root->info=="+") return l_val+r_val; if (root->info=="-") return l_val-r_val; if (root->info=="*") return l_val*r_val; return l_val/r_val;} //driver function to check the above programint main(){ // create a syntax tree node *root = new node("+"); root->left = new node("*"); root->left->left = new node("5"); root->left->right = new node("-4"); root->right = new node("-"); root->right->left = new node("100"); root->right->right = new node("20"); cout << eval(root) << endl; delete(root); root = new node("+"); root->left = new node("*"); root->left->left = new node("5"); root->left->right = new node("4"); root->right = new node("-"); root->right->left = new node("100"); root->right->right = new node("/"); root->right->right->left = new node("20"); root->right->right->right = new node("2"); cout << eval(root); return 0;}
// Java program to evaluate expression treeimport java.lang.*; class GFG{ Node root; // Class to represent the nodes of syntax treepublic static class Node{ String data; Node left, right; Node(String d) { data = d; left = null; right = null; }} private static int toInt(String s){ int num = 0; // Check if the integral value is // negative or not // If it is not negative, generate // the number normally if (s.charAt(0) != '-') for(int i = 0; i < s.length(); i++) num = num * 10 + ((int)s.charAt(i) - 48); // If it is negative, calculate the +ve number // first ignoring the sign and invert the // sign at the end else { for(int i = 1; i < s.length(); i++) num = num * 10 + ((int)(s.charAt(i)) - 48); num = num * -1; } return num;} // This function receives a node of the syntax// tree and recursively evaluate itpublic static int evalTree(Node root){ // Empty tree if (root == null) return 0; // Leaf node i.e, an integer if (root.left == null && root.right == null) return toInt(root.data); // Evaluate left subtree int leftEval = evalTree(root.left); // Evaluate right subtree int rightEval = evalTree(root.right); // Check which operator to apply if (root.data.equals("+")) return leftEval + rightEval; if (root.data.equals("-")) return leftEval - rightEval; if (root.data.equals("*")) return leftEval * rightEval; return leftEval / rightEval;} // Driver codepublic static void main(String[] args){ // Creating a sample tree Node root = new Node("+"); root.left = new Node("*"); root.left.left = new Node("5"); root.left.right = new Node("-4"); root.right = new Node("-"); root.right.left = new Node("100"); root.right.right = new Node("20"); System.out.println(evalTree(root)); root = null; // Creating a sample tree root = new Node("+"); root.left = new Node("*"); root.left.left = new Node("5"); root.left.right = new Node("4"); root.right = new Node("-"); root.right.left = new Node("100"); root.right.right = new Node("/"); root.right.right.left = new Node("20"); root.right.right.right = new Node("2"); System.out.println(evalTree(root));}} // This code is contributed by Ankit Gupta
# Python program to evaluate expression tree # Class to represent the nodes of syntax tree class node: def __init__(self, value): self.left = None self.data = value self.right = None # This function receives a node of the syntax tree# and recursively evaluate it def evaluateExpressionTree(root): # empty tree if root is None: return 0 # leaf node if root.left is None and root.right is None: return int(root.data) # evaluate left tree left_sum = evaluateExpressionTree(root.left) # evaluate right tree right_sum = evaluateExpressionTree(root.right) # check which operation to apply if root.data == '+': return left_sum + right_sum elif root.data == '-': return left_sum - right_sum elif root.data == '*': return left_sum * right_sum else: return left_sum // right_sum # Driver function to test above problemif __name__ == '__main__': # creating a sample tree root = node('+') root.left = node('*') root.left.left = node('5') root.left.right = node('-50') root.right = node('-') root.right.left = node('100') root.right.right = node('20') print (evaluateExpressionTree(root)) root = None # creating a sample tree root = node('+') root.left = node('*') root.left.left = node('5') root.left.right = node('4') root.right = node('-') root.right.left = node('100') root.right.right = node('/') root.right.right.left = node('20') root.right.right.right = node('2') print (evaluateExpressionTree(root)) # This code is contributed by Harshit Sidhwa
// C# program to evaluate expression treeusing System; public class GFG{ // Class to represent the nodes of syntax tree public class Node { public String data; public Node left, right; public Node(String d) { data = d; left = null; right = null; } } private static int toInt(String s) { int num = 0; // Check if the integral value is // negative or not // If it is not negative, generate // the number normally if (s[0] != '-') for (int i = 0; i < s.Length; i++) num = num * 10 + ((int) s[i] - 48); // If it is negative, calculate the +ve number // first ignoring the sign and invert the // sign at the end else { for (int i = 1; i < s.Length; i++) num = num * 10 + ((int) (s[i]) - 48); num = num * -1; } return num; } // This function receives a node of the syntax // tree and recursively evaluate it public static int evalTree(Node root) { // Empty tree if (root == null) return 0; // Leaf node i.e, an integer if (root.left == null && root.right == null) return toInt(root.data); // Evaluate left subtree int leftEval = evalTree(root.left); // Evaluate right subtree int rightEval = evalTree(root.right); // Check which operator to apply if (root.data.Equals("+")) return leftEval + rightEval; if (root.data.Equals("-")) return leftEval - rightEval; if (root.data.Equals("*")) return leftEval * rightEval; return leftEval / rightEval; } // Driver code public static void Main(String[] args) { // Creating a sample tree Node root = new Node("+"); root.left = new Node("*"); root.left.left = new Node("5"); root.left.right = new Node("-4"); root.right = new Node("-"); root.right.left = new Node("100"); root.right.right = new Node("20"); Console.WriteLine(evalTree(root)); root = null; // Creating a sample tree root = new Node("+"); root.left = new Node("*"); root.left.left = new Node("5"); root.left.right = new Node("4"); root.right = new Node("-"); root.right.left = new Node("100"); root.right.right = new Node("/"); root.right.right.left = new Node("20"); root.right.right.right = new Node("2"); Console.WriteLine(evalTree(root)); }} // This code is contributed by umadevi9616
<script>// javascript program to evaluate expression tree var root; // Class to represent the nodes of syntax tree class Node { constructor(val) { this.data = val; this.left = null; this.right = null; } } function toInt( s) { var num = 0; // Check if the integral value is // negative or not // If it is not negative, generate // the number normally if (s.charAt(0) != '-') for (i = 0; i < s.length; i++) num = num * 10 + ( s.charCodeAt(i) - 48); // If it is negative, calculate the +ve number // first ignoring the sign and invert the // sign at the end else { for (i = 1; i < s.length; i++) num = num * 10 + (s.charCodeAt(i) - 48); num = num * -1; } return num; } // This function receives a node of the syntax // tree and recursively evaluate it function evalTree(root) { // Empty tree if (root == null) return 0; // Leaf node i.e, an integer if (root.left == null && root.right == null) return toInt(root.data); // Evaluate left subtree var leftEval = evalTree(root.left); // Evaluate right subtree var rightEval = evalTree(root.right); // Check which operator to apply if (root.data === ("+")) return leftEval + rightEval; if (root.data === ("-")) return leftEval - rightEval; if (root.data === ("*")) return leftEval * rightEval; return leftEval / rightEval; } // Driver code // Creating a sample tree var root = new Node("+"); root.left = new Node("*"); root.left.left = new Node("5"); root.left.right = new Node("-4"); root.right = new Node("-"); root.right.left = new Node("100"); root.right.right = new Node("20"); document.write(evalTree(root)); root = null; // Creating a sample tree root = new Node("+"); root.left = new Node("*"); root.left.left = new Node("5"); root.left.right = new Node("4"); root.right = new Node("-"); root.right.left = new Node("100"); root.right.right = new Node("/"); root.right.right.left = new Node("20"); root.right.right.right = new Node("2"); document.write("<br/>"+evalTree(root)); // This code is contributed by gauravrajput1</script>
60
110
Time Complexity: O(n), as each node is visited once.
YouTubeGeeksforGeeks500K subscribersEvaluation of Expression Tree | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 5:57•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=2tpcqDmvJBU" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Ashutosh Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
KumariPoojaMandal
ankitgupta50
GauravRajput1
amartyaghoshgfg
ramsudharsan75
RishabhPrabhu
Amazon
Flipkart
Snapdeal
Synopsys
Tree
Flipkart
Amazon
Snapdeal
Synopsys
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Tree Traversals (Inorder, Preorder and Postorder)
Binary Tree | Set 1 (Introduction)
AVL Tree | Set 1 (Insertion)
Level Order Binary Tree Traversal
Inorder Tree Traversal without Recursion
Binary Tree | Set 3 (Types of Binary Tree)
Write a Program to Find the Maximum Depth or Height of a Tree
Binary Tree | Set 2 (Properties)
A program to check if a binary tree is BST or not
Inorder Tree Traversal without recursion and without stack! | [
{
"code": null,
"e": 35457,
"s": 35429,
"text": "\n15 Mar, 2022"
},
{
"code": null,
"e": 35596,
"s": 35457,
"text": "Given a simple expression tree, consisting of basic binary operators i.e., + , – ,* and / and some integers, evaluate the expression tree."
},
{
"code": null,
"e": 35606,
"s": 35596,
"text": "Examples:"
},
{
"code": null,
"e": 35641,
"s": 35606,
"text": "Input: Root node of the below tree"
},
{
"code": null,
"e": 35652,
"s": 35641,
"text": "Output:100"
},
{
"code": null,
"e": 35687,
"s": 35652,
"text": "Input: Root node of the below tree"
},
{
"code": null,
"e": 35699,
"s": 35687,
"text": "Output: 110"
},
{
"code": null,
"e": 35779,
"s": 35699,
"text": "Approach: The approach to solve this problem is based on following observation:"
},
{
"code": null,
"e": 36026,
"s": 35779,
"text": "As all the operators in the tree are binary, hence each node will have either 0 or 2 children. As it can be inferred from the examples above, all the integer values would appear at the leaf nodes, while the interior nodes represent the operators."
},
{
"code": null,
"e": 36129,
"s": 36026,
"text": "Therefore we can do inorder traversal of the binary tree and evaluate the expression as we move ahead."
},
{
"code": null,
"e": 36196,
"s": 36129,
"text": "To evaluate the syntax tree, a recursive approach can be followed."
},
{
"code": null,
"e": 36207,
"s": 36196,
"text": "Algorithm:"
},
{
"code": null,
"e": 36232,
"s": 36207,
"text": "Let t be the syntax tree"
},
{
"code": null,
"e": 36403,
"s": 36232,
"text": "If t is not null then If t.info is operand then Return t.infoElseA = solve(t.left)B = solve(t.right)return A operator B, where operator is the info contained in t"
},
{
"code": null,
"e": 36445,
"s": 36403,
"text": "If t.info is operand then Return t.info"
},
{
"code": null,
"e": 36460,
"s": 36445,
"text": "Return t.info"
},
{
"code": null,
"e": 36562,
"s": 36460,
"text": "ElseA = solve(t.left)B = solve(t.right)return A operator B, where operator is the info contained in t"
},
{
"code": null,
"e": 36580,
"s": 36562,
"text": "A = solve(t.left)"
},
{
"code": null,
"e": 36599,
"s": 36580,
"text": "B = solve(t.right)"
},
{
"code": null,
"e": 36662,
"s": 36599,
"text": "return A operator B, where operator is the info contained in t"
},
{
"code": null,
"e": 36713,
"s": 36662,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 36717,
"s": 36713,
"text": "C++"
},
{
"code": null,
"e": 36722,
"s": 36717,
"text": "Java"
},
{
"code": null,
"e": 36730,
"s": 36722,
"text": "Python3"
},
{
"code": null,
"e": 36733,
"s": 36730,
"text": "C#"
},
{
"code": null,
"e": 36744,
"s": 36733,
"text": "Javascript"
},
{
"code": "// C++ program to evaluate an expression tree#include <bits/stdc++.h>using namespace std; // Class to represent the nodes of syntax treeclass node{public: string info; node *left = NULL, *right = NULL; node(string x) { info = x; }}; // Utility function to return the integer value// of a given stringint toInt(string s){ int num = 0; // Check if the integral value is // negative or not // If it is not negative, generate the number // normally if(s[0]!='-') for (int i=0; i<s.length(); i++) num = num*10 + (int(s[i])-48); // If it is negative, calculate the +ve number // first ignoring the sign and invert the // sign at the end else { for (int i=1; i<s.length(); i++) num = num*10 + (int(s[i])-48); num = num*-1; } return num;} // This function receives a node of the syntax tree// and recursively evaluates itint eval(node* root){ // empty tree if (!root) return 0; // leaf node i.e, an integer if (!root->left && !root->right) return toInt(root->info); // Evaluate left subtree int l_val = eval(root->left); // Evaluate right subtree int r_val = eval(root->right); // Check which operator to apply if (root->info==\"+\") return l_val+r_val; if (root->info==\"-\") return l_val-r_val; if (root->info==\"*\") return l_val*r_val; return l_val/r_val;} //driver function to check the above programint main(){ // create a syntax tree node *root = new node(\"+\"); root->left = new node(\"*\"); root->left->left = new node(\"5\"); root->left->right = new node(\"-4\"); root->right = new node(\"-\"); root->right->left = new node(\"100\"); root->right->right = new node(\"20\"); cout << eval(root) << endl; delete(root); root = new node(\"+\"); root->left = new node(\"*\"); root->left->left = new node(\"5\"); root->left->right = new node(\"4\"); root->right = new node(\"-\"); root->right->left = new node(\"100\"); root->right->right = new node(\"/\"); root->right->right->left = new node(\"20\"); root->right->right->right = new node(\"2\"); cout << eval(root); return 0;}",
"e": 38937,
"s": 36744,
"text": null
},
{
"code": "// Java program to evaluate expression treeimport java.lang.*; class GFG{ Node root; // Class to represent the nodes of syntax treepublic static class Node{ String data; Node left, right; Node(String d) { data = d; left = null; right = null; }} private static int toInt(String s){ int num = 0; // Check if the integral value is // negative or not // If it is not negative, generate // the number normally if (s.charAt(0) != '-') for(int i = 0; i < s.length(); i++) num = num * 10 + ((int)s.charAt(i) - 48); // If it is negative, calculate the +ve number // first ignoring the sign and invert the // sign at the end else { for(int i = 1; i < s.length(); i++) num = num * 10 + ((int)(s.charAt(i)) - 48); num = num * -1; } return num;} // This function receives a node of the syntax// tree and recursively evaluate itpublic static int evalTree(Node root){ // Empty tree if (root == null) return 0; // Leaf node i.e, an integer if (root.left == null && root.right == null) return toInt(root.data); // Evaluate left subtree int leftEval = evalTree(root.left); // Evaluate right subtree int rightEval = evalTree(root.right); // Check which operator to apply if (root.data.equals(\"+\")) return leftEval + rightEval; if (root.data.equals(\"-\")) return leftEval - rightEval; if (root.data.equals(\"*\")) return leftEval * rightEval; return leftEval / rightEval;} // Driver codepublic static void main(String[] args){ // Creating a sample tree Node root = new Node(\"+\"); root.left = new Node(\"*\"); root.left.left = new Node(\"5\"); root.left.right = new Node(\"-4\"); root.right = new Node(\"-\"); root.right.left = new Node(\"100\"); root.right.right = new Node(\"20\"); System.out.println(evalTree(root)); root = null; // Creating a sample tree root = new Node(\"+\"); root.left = new Node(\"*\"); root.left.left = new Node(\"5\"); root.left.right = new Node(\"4\"); root.right = new Node(\"-\"); root.right.left = new Node(\"100\"); root.right.right = new Node(\"/\"); root.right.right.left = new Node(\"20\"); root.right.right.right = new Node(\"2\"); System.out.println(evalTree(root));}} // This code is contributed by Ankit Gupta",
"e": 41323,
"s": 38937,
"text": null
},
{
"code": "# Python program to evaluate expression tree # Class to represent the nodes of syntax tree class node: def __init__(self, value): self.left = None self.data = value self.right = None # This function receives a node of the syntax tree# and recursively evaluate it def evaluateExpressionTree(root): # empty tree if root is None: return 0 # leaf node if root.left is None and root.right is None: return int(root.data) # evaluate left tree left_sum = evaluateExpressionTree(root.left) # evaluate right tree right_sum = evaluateExpressionTree(root.right) # check which operation to apply if root.data == '+': return left_sum + right_sum elif root.data == '-': return left_sum - right_sum elif root.data == '*': return left_sum * right_sum else: return left_sum // right_sum # Driver function to test above problemif __name__ == '__main__': # creating a sample tree root = node('+') root.left = node('*') root.left.left = node('5') root.left.right = node('-50') root.right = node('-') root.right.left = node('100') root.right.right = node('20') print (evaluateExpressionTree(root)) root = None # creating a sample tree root = node('+') root.left = node('*') root.left.left = node('5') root.left.right = node('4') root.right = node('-') root.right.left = node('100') root.right.right = node('/') root.right.right.left = node('20') root.right.right.right = node('2') print (evaluateExpressionTree(root)) # This code is contributed by Harshit Sidhwa",
"e": 42946,
"s": 41323,
"text": null
},
{
"code": "// C# program to evaluate expression treeusing System; public class GFG{ // Class to represent the nodes of syntax tree public class Node { public String data; public Node left, right; public Node(String d) { data = d; left = null; right = null; } } private static int toInt(String s) { int num = 0; // Check if the integral value is // negative or not // If it is not negative, generate // the number normally if (s[0] != '-') for (int i = 0; i < s.Length; i++) num = num * 10 + ((int) s[i] - 48); // If it is negative, calculate the +ve number // first ignoring the sign and invert the // sign at the end else { for (int i = 1; i < s.Length; i++) num = num * 10 + ((int) (s[i]) - 48); num = num * -1; } return num; } // This function receives a node of the syntax // tree and recursively evaluate it public static int evalTree(Node root) { // Empty tree if (root == null) return 0; // Leaf node i.e, an integer if (root.left == null && root.right == null) return toInt(root.data); // Evaluate left subtree int leftEval = evalTree(root.left); // Evaluate right subtree int rightEval = evalTree(root.right); // Check which operator to apply if (root.data.Equals(\"+\")) return leftEval + rightEval; if (root.data.Equals(\"-\")) return leftEval - rightEval; if (root.data.Equals(\"*\")) return leftEval * rightEval; return leftEval / rightEval; } // Driver code public static void Main(String[] args) { // Creating a sample tree Node root = new Node(\"+\"); root.left = new Node(\"*\"); root.left.left = new Node(\"5\"); root.left.right = new Node(\"-4\"); root.right = new Node(\"-\"); root.right.left = new Node(\"100\"); root.right.right = new Node(\"20\"); Console.WriteLine(evalTree(root)); root = null; // Creating a sample tree root = new Node(\"+\"); root.left = new Node(\"*\"); root.left.left = new Node(\"5\"); root.left.right = new Node(\"4\"); root.right = new Node(\"-\"); root.right.left = new Node(\"100\"); root.right.right = new Node(\"/\"); root.right.right.left = new Node(\"20\"); root.right.right.right = new Node(\"2\"); Console.WriteLine(evalTree(root)); }} // This code is contributed by umadevi9616",
"e": 45597,
"s": 42946,
"text": null
},
{
"code": "<script>// javascript program to evaluate expression tree var root; // Class to represent the nodes of syntax tree class Node { constructor(val) { this.data = val; this.left = null; this.right = null; } } function toInt( s) { var num = 0; // Check if the integral value is // negative or not // If it is not negative, generate // the number normally if (s.charAt(0) != '-') for (i = 0; i < s.length; i++) num = num * 10 + ( s.charCodeAt(i) - 48); // If it is negative, calculate the +ve number // first ignoring the sign and invert the // sign at the end else { for (i = 1; i < s.length; i++) num = num * 10 + (s.charCodeAt(i) - 48); num = num * -1; } return num; } // This function receives a node of the syntax // tree and recursively evaluate it function evalTree(root) { // Empty tree if (root == null) return 0; // Leaf node i.e, an integer if (root.left == null && root.right == null) return toInt(root.data); // Evaluate left subtree var leftEval = evalTree(root.left); // Evaluate right subtree var rightEval = evalTree(root.right); // Check which operator to apply if (root.data === (\"+\")) return leftEval + rightEval; if (root.data === (\"-\")) return leftEval - rightEval; if (root.data === (\"*\")) return leftEval * rightEval; return leftEval / rightEval; } // Driver code // Creating a sample tree var root = new Node(\"+\"); root.left = new Node(\"*\"); root.left.left = new Node(\"5\"); root.left.right = new Node(\"-4\"); root.right = new Node(\"-\"); root.right.left = new Node(\"100\"); root.right.right = new Node(\"20\"); document.write(evalTree(root)); root = null; // Creating a sample tree root = new Node(\"+\"); root.left = new Node(\"*\"); root.left.left = new Node(\"5\"); root.left.right = new Node(\"4\"); root.right = new Node(\"-\"); root.right.left = new Node(\"100\"); root.right.right = new Node(\"/\"); root.right.right.left = new Node(\"20\"); root.right.right.right = new Node(\"2\"); document.write(\"<br/>\"+evalTree(root)); // This code is contributed by gauravrajput1</script>",
"e": 48117,
"s": 45597,
"text": null
},
{
"code": null,
"e": 48124,
"s": 48117,
"text": "60\n110"
},
{
"code": null,
"e": 48178,
"s": 48124,
"text": "Time Complexity: O(n), as each node is visited once. "
},
{
"code": null,
"e": 49006,
"s": 48178,
"text": "YouTubeGeeksforGeeks500K subscribersEvaluation of Expression Tree | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 5:57•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=2tpcqDmvJBU\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>"
},
{
"code": null,
"e": 49304,
"s": 49006,
"text": "This article is contributed by Ashutosh Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 49429,
"s": 49304,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 49447,
"s": 49429,
"text": "KumariPoojaMandal"
},
{
"code": null,
"e": 49460,
"s": 49447,
"text": "ankitgupta50"
},
{
"code": null,
"e": 49474,
"s": 49460,
"text": "GauravRajput1"
},
{
"code": null,
"e": 49490,
"s": 49474,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 49505,
"s": 49490,
"text": "ramsudharsan75"
},
{
"code": null,
"e": 49519,
"s": 49505,
"text": "RishabhPrabhu"
},
{
"code": null,
"e": 49526,
"s": 49519,
"text": "Amazon"
},
{
"code": null,
"e": 49535,
"s": 49526,
"text": "Flipkart"
},
{
"code": null,
"e": 49544,
"s": 49535,
"text": "Snapdeal"
},
{
"code": null,
"e": 49553,
"s": 49544,
"text": "Synopsys"
},
{
"code": null,
"e": 49558,
"s": 49553,
"text": "Tree"
},
{
"code": null,
"e": 49567,
"s": 49558,
"text": "Flipkart"
},
{
"code": null,
"e": 49574,
"s": 49567,
"text": "Amazon"
},
{
"code": null,
"e": 49583,
"s": 49574,
"text": "Snapdeal"
},
{
"code": null,
"e": 49592,
"s": 49583,
"text": "Synopsys"
},
{
"code": null,
"e": 49597,
"s": 49592,
"text": "Tree"
},
{
"code": null,
"e": 49695,
"s": 49597,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 49704,
"s": 49695,
"text": "Comments"
},
{
"code": null,
"e": 49717,
"s": 49704,
"text": "Old Comments"
},
{
"code": null,
"e": 49767,
"s": 49717,
"text": "Tree Traversals (Inorder, Preorder and Postorder)"
},
{
"code": null,
"e": 49802,
"s": 49767,
"text": "Binary Tree | Set 1 (Introduction)"
},
{
"code": null,
"e": 49831,
"s": 49802,
"text": "AVL Tree | Set 1 (Insertion)"
},
{
"code": null,
"e": 49865,
"s": 49831,
"text": "Level Order Binary Tree Traversal"
},
{
"code": null,
"e": 49906,
"s": 49865,
"text": "Inorder Tree Traversal without Recursion"
},
{
"code": null,
"e": 49949,
"s": 49906,
"text": "Binary Tree | Set 3 (Types of Binary Tree)"
},
{
"code": null,
"e": 50011,
"s": 49949,
"text": "Write a Program to Find the Maximum Depth or Height of a Tree"
},
{
"code": null,
"e": 50044,
"s": 50011,
"text": "Binary Tree | Set 2 (Properties)"
},
{
"code": null,
"e": 50094,
"s": 50044,
"text": "A program to check if a binary tree is BST or not"
}
]
|
How to bring an activity to the foreground i.e. top of stack using Kotlin? | This example demonstrates how to bring an activity to the foreground i.e. top of stack using Kotlin.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="4dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="70dp"
android:background="#008080"
android:padding="5dp"
android:text="TutorialsPoint"
android:textColor="#fff"
android:textSize="24sp"
android:textStyle="bold" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.kt
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
val i = Intent(this, NewActivity::class.java)
i.flags = Intent.FLAG_ACTIVITY_REORDER_TO_FRONT
startActivity(i)
}
}
Step 4 − Create a empty activity (NewActivity) and add the following code −
NewActivity.kt −
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
class NewActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_new)
title = "KotlinApp"
}
}
activity_new.xml −
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="4dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="70dp"
android:background="#008080"
android:padding="5dp"
android:text="TutorialsPoint"
android:textColor="#fff"
android:textSize="24sp"
android:textStyle="bold" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="New Activity"
android:textAlignment="center"
android:textColor="@android:color/holo_blue_dark"
android:textSize="24sp"
android:textStyle="bold" />
</RelativeLayout>
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="com.example.q11">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen. | [
{
"code": null,
"e": 1163,
"s": 1062,
"text": "This example demonstrates how to bring an activity to the foreground i.e. top of stack using Kotlin."
},
{
"code": null,
"e": 1291,
"s": 1163,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project"
},
{
"code": null,
"e": 1356,
"s": 1291,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1968,
"s": 1356,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:padding=\"4dp\">\n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"70dp\"\n android:background=\"#008080\"\n android:padding=\"5dp\"\n android:text=\"TutorialsPoint\"\n android:textColor=\"#fff\"\n android:textSize=\"24sp\"\n android:textStyle=\"bold\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 2023,
"s": 1968,
"text": "Step 3 − Add the following code to src/MainActivity.kt"
},
{
"code": null,
"e": 2473,
"s": 2023,
"text": "import android.content.Intent\nimport android.os.Bundle\nimport androidx.appcompat.app.AppCompatActivity\nclass MainActivity : AppCompatActivity() {\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n val i = Intent(this, NewActivity::class.java)\n i.flags = Intent.FLAG_ACTIVITY_REORDER_TO_FRONT\n startActivity(i)\n }\n}"
},
{
"code": null,
"e": 2549,
"s": 2473,
"text": "Step 4 − Create a empty activity (NewActivity) and add the following code −"
},
{
"code": null,
"e": 2566,
"s": 2549,
"text": "NewActivity.kt −"
},
{
"code": null,
"e": 2855,
"s": 2566,
"text": "import androidx.appcompat.app.AppCompatActivity\nimport android.os.Bundle\nclass NewActivity : AppCompatActivity() {\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_new)\n title = \"KotlinApp\"\n }\n}"
},
{
"code": null,
"e": 2874,
"s": 2855,
"text": "activity_new.xml −"
},
{
"code": null,
"e": 3818,
"s": 2874,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:padding=\"4dp\">\n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"70dp\"\n android:background=\"#008080\"\n android:padding=\"5dp\"\n android:text=\"TutorialsPoint\"\n android:textColor=\"#fff\"\n android:textSize=\"24sp\"\n android:textStyle=\"bold\" />\n <TextView\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:text=\"New Activity\"\n android:textAlignment=\"center\"\n android:textColor=\"@android:color/holo_blue_dark\"\n android:textSize=\"24sp\"\n android:textStyle=\"bold\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 3873,
"s": 3818,
"text": "Step 5 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 4547,
"s": 3873,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"com.example.q11\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 4897,
"s": 4547,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen."
}
]
|
What is correct syntax to create Python dictionary? | A Python dictionary object is a collection of key-value pairs. Each item in a dictionary consists of a value associated with key. The association is defined by putting : between them. Such key-value pairs, separated by comma and included within curly brackets, forms a dictionary object.
Key component of item must be an immutable object and unique in the collection. Value component may be repeated and can be of any data type.
>>> D1={"name":"Raaj", "age":23, "subjects":["Phy", "Che", "maths"],"GPA":8.5} | [
{
"code": null,
"e": 1350,
"s": 1062,
"text": "A Python dictionary object is a collection of key-value pairs. Each item in a dictionary consists of a value associated with key. The association is defined by putting : between them. Such key-value pairs, separated by comma and included within curly brackets, forms a dictionary object."
},
{
"code": null,
"e": 1491,
"s": 1350,
"text": "Key component of item must be an immutable object and unique in the collection. Value component may be repeated and can be of any data type."
},
{
"code": null,
"e": 1570,
"s": 1491,
"text": ">>> D1={\"name\":\"Raaj\", \"age\":23, \"subjects\":[\"Phy\", \"Che\", \"maths\"],\"GPA\":8.5}"
}
]
|
How to reload CSS without reloading the page using JavaScript ? - GeeksforGeeks | 02 Jun, 2020
While working with CSS, you might have come across situations where you made some changes in the stylesheet and had to do a hard reload to see the changes reflected in your browser. Or maybe the style depends on some user interaction and you don’t wish to hard reload the page every time. Sometimes you don’t want to lose the changes made using the Dev Tools and simply wish to reload the CSS. Other times the CSS is so stubbornly cached that even refreshing the entire page doesn’t help. Today we will learn how to reload the CSS without reloading the entire page.
Using JavaScript, we can append a new version number to the CSS file path as a query parameter every time you update the CSS. By adding a different query parameter to a URL, the browser handles it as a unique URL and caches it separately allowing you to have the updated version loaded. You can attach this function to a button (or a combination of keyboard keys as a shortcut) that reloads CSS every time it is clicked. We can use the current date-time as the version number since it will always be a new and unique string.
Syntax: Add the created CSS file like the below format.<link rel="stylesheet" type="text/css" href="css/style.css?version=#">
<link rel="stylesheet" type="text/css" href="css/style.css?version=#">
index.html with JavaScript code:<!DOCTYPE html><html> <head> <link rel="stylesheet" type="text/css" href="style.css"/></head> <body> <h1>GeeksforGeeks</h1> <b>Reloding CSS without relodaing the page</b> <br><br> <button onclick="refreshCSS()"> Refresh CSS </button> <script> refreshCSS = () => { let links = document.getElementsByTagName('link'); for (let i = 0; i < links.length; i++) { if (links[i].getAttribute('rel') == 'stylesheet') { let href = links[i].getAttribute('href') .split('?')[0]; let newHref = href + '?version=' + new Date().getMilliseconds(); links[i].setAttribute('href', newHref); } } } </script></body> </html>
<!DOCTYPE html><html> <head> <link rel="stylesheet" type="text/css" href="style.css"/></head> <body> <h1>GeeksforGeeks</h1> <b>Reloding CSS without relodaing the page</b> <br><br> <button onclick="refreshCSS()"> Refresh CSS </button> <script> refreshCSS = () => { let links = document.getElementsByTagName('link'); for (let i = 0; i < links.length; i++) { if (links[i].getAttribute('rel') == 'stylesheet') { let href = links[i].getAttribute('href') .split('?')[0]; let newHref = href + '?version=' + new Date().getMilliseconds(); links[i].setAttribute('href', newHref); } } } </script></body> </html>
CSS file style.css:/* Coloring h1 tag */h1 { color: green;}/* Button styling */button { width: 200px; background-color: purple; color: black; border-radius: 10px; padding: 10px; font-weight: bold;}
/* Coloring h1 tag */h1 { color: green;}/* Button styling */button { width: 200px; background-color: purple; color: black; border-radius: 10px; padding: 10px; font-weight: bold;}
Output:
You can add this function as a JavaScript bookmarklet in your browser which will reload the CSS every time you click on it.javascript:(function(){
let links = document.getElementsByTagName('link');
for (let i = 0; i < links.length; i++) {
if (links[i].getAttribute('rel') == 'stylesheet') {
let href = links[i].getAttribute('href').split('?')[0];
let newHref = href + '?version='
+ new Date().getMilliseconds();
console.log(newHref)
links[i].setAttribute('href', newHref);
}
}
})();
javascript:(function(){
let links = document.getElementsByTagName('link');
for (let i = 0; i < links.length; i++) {
if (links[i].getAttribute('rel') == 'stylesheet') {
let href = links[i].getAttribute('href').split('?')[0];
let newHref = href + '?version='
+ new Date().getMilliseconds();
console.log(newHref)
links[i].setAttribute('href', newHref);
}
}
})();
Akanksha_Rai
CSS-Misc
HTML-Misc
JavaScript-Misc
Picked
CSS
HTML
JavaScript
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to create footer to stay at the bottom of a Web page?
Types of CSS (Cascading Style Sheet)
Create a Responsive Navbar using ReactJS
Design a web page using HTML and CSS
How to position a div at the bottom of its container using CSS?
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Hide or show elements in HTML using display property
Types of CSS (Cascading Style Sheet)
How to Insert Form Data into Database using PHP ? | [
{
"code": null,
"e": 24919,
"s": 24891,
"text": "\n02 Jun, 2020"
},
{
"code": null,
"e": 25485,
"s": 24919,
"text": "While working with CSS, you might have come across situations where you made some changes in the stylesheet and had to do a hard reload to see the changes reflected in your browser. Or maybe the style depends on some user interaction and you don’t wish to hard reload the page every time. Sometimes you don’t want to lose the changes made using the Dev Tools and simply wish to reload the CSS. Other times the CSS is so stubbornly cached that even refreshing the entire page doesn’t help. Today we will learn how to reload the CSS without reloading the entire page."
},
{
"code": null,
"e": 26010,
"s": 25485,
"text": "Using JavaScript, we can append a new version number to the CSS file path as a query parameter every time you update the CSS. By adding a different query parameter to a URL, the browser handles it as a unique URL and caches it separately allowing you to have the updated version loaded. You can attach this function to a button (or a combination of keyboard keys as a shortcut) that reloads CSS every time it is clicked. We can use the current date-time as the version number since it will always be a new and unique string."
},
{
"code": null,
"e": 26136,
"s": 26010,
"text": "Syntax: Add the created CSS file like the below format.<link rel=\"stylesheet\" type=\"text/css\" href=\"css/style.css?version=#\">"
},
{
"code": null,
"e": 26207,
"s": 26136,
"text": "<link rel=\"stylesheet\" type=\"text/css\" href=\"css/style.css?version=#\">"
},
{
"code": null,
"e": 27151,
"s": 26207,
"text": "index.html with JavaScript code:<!DOCTYPE html><html> <head> <link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\"/></head> <body> <h1>GeeksforGeeks</h1> <b>Reloding CSS without relodaing the page</b> <br><br> <button onclick=\"refreshCSS()\"> Refresh CSS </button> <script> refreshCSS = () => { let links = document.getElementsByTagName('link'); for (let i = 0; i < links.length; i++) { if (links[i].getAttribute('rel') == 'stylesheet') { let href = links[i].getAttribute('href') .split('?')[0]; let newHref = href + '?version=' + new Date().getMilliseconds(); links[i].setAttribute('href', newHref); } } } </script></body> </html>"
},
{
"code": "<!DOCTYPE html><html> <head> <link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\"/></head> <body> <h1>GeeksforGeeks</h1> <b>Reloding CSS without relodaing the page</b> <br><br> <button onclick=\"refreshCSS()\"> Refresh CSS </button> <script> refreshCSS = () => { let links = document.getElementsByTagName('link'); for (let i = 0; i < links.length; i++) { if (links[i].getAttribute('rel') == 'stylesheet') { let href = links[i].getAttribute('href') .split('?')[0]; let newHref = href + '?version=' + new Date().getMilliseconds(); links[i].setAttribute('href', newHref); } } } </script></body> </html>",
"e": 28063,
"s": 27151,
"text": null
},
{
"code": null,
"e": 28270,
"s": 28063,
"text": "CSS file style.css:/* Coloring h1 tag */h1 { color: green;}/* Button styling */button { width: 200px; background-color: purple; color: black; border-radius: 10px; padding: 10px; font-weight: bold;}"
},
{
"code": "/* Coloring h1 tag */h1 { color: green;}/* Button styling */button { width: 200px; background-color: purple; color: black; border-radius: 10px; padding: 10px; font-weight: bold;}",
"e": 28458,
"s": 28270,
"text": null
},
{
"code": null,
"e": 28466,
"s": 28458,
"text": "Output:"
},
{
"code": null,
"e": 29062,
"s": 28466,
"text": "You can add this function as a JavaScript bookmarklet in your browser which will reload the CSS every time you click on it.javascript:(function(){\n let links = document.getElementsByTagName('link');\n for (let i = 0; i < links.length; i++) {\n if (links[i].getAttribute('rel') == 'stylesheet') {\n let href = links[i].getAttribute('href').split('?')[0];\n let newHref = href + '?version=' \n + new Date().getMilliseconds();\n console.log(newHref)\n links[i].setAttribute('href', newHref);\n }\n }\n})();\n"
},
{
"code": null,
"e": 29535,
"s": 29062,
"text": "javascript:(function(){\n let links = document.getElementsByTagName('link');\n for (let i = 0; i < links.length; i++) {\n if (links[i].getAttribute('rel') == 'stylesheet') {\n let href = links[i].getAttribute('href').split('?')[0];\n let newHref = href + '?version=' \n + new Date().getMilliseconds();\n console.log(newHref)\n links[i].setAttribute('href', newHref);\n }\n }\n})();\n"
},
{
"code": null,
"e": 29548,
"s": 29535,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 29557,
"s": 29548,
"text": "CSS-Misc"
},
{
"code": null,
"e": 29567,
"s": 29557,
"text": "HTML-Misc"
},
{
"code": null,
"e": 29583,
"s": 29567,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 29590,
"s": 29583,
"text": "Picked"
},
{
"code": null,
"e": 29594,
"s": 29590,
"text": "CSS"
},
{
"code": null,
"e": 29599,
"s": 29594,
"text": "HTML"
},
{
"code": null,
"e": 29610,
"s": 29599,
"text": "JavaScript"
},
{
"code": null,
"e": 29627,
"s": 29610,
"text": "Web Technologies"
},
{
"code": null,
"e": 29654,
"s": 29627,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 29659,
"s": 29654,
"text": "HTML"
},
{
"code": null,
"e": 29757,
"s": 29659,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29766,
"s": 29757,
"text": "Comments"
},
{
"code": null,
"e": 29779,
"s": 29766,
"text": "Old Comments"
},
{
"code": null,
"e": 29837,
"s": 29779,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 29874,
"s": 29837,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 29915,
"s": 29874,
"text": "Create a Responsive Navbar using ReactJS"
},
{
"code": null,
"e": 29952,
"s": 29915,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 30016,
"s": 29952,
"text": "How to position a div at the bottom of its container using CSS?"
},
{
"code": null,
"e": 30076,
"s": 30016,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 30137,
"s": 30076,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 30190,
"s": 30137,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 30227,
"s": 30190,
"text": "Types of CSS (Cascading Style Sheet)"
}
]
|
Conditional Rendering in ReactJS | In this article, we are going to see how to conditionally render a component based on some conditions in a React application
In ReactJS, we can render only the desired components based on certain given conditions by using the if-else statements or by using the logical && operator of JavaScript. When the provided condition is satisfied, then React will match the UI and update it accordingly.
In this example, we will build a React application that has an App component as a parent component which will conditionally re-render the Form component and update the UI accordingly.
App.jsx
import React, { useState } from 'react';
const App = () => {
const [isLogin, setIsLogin] = useState(true);
return (
<div>
<div>Username: Tutorialspoint</div>
<div onClick={() => setIsLogin((prev) => !prev)}>
{isLogin ? <Form login /> : <Form logout />}
</div>
</div>
);
};
const Form = ({ login, logout }) => {
return (
<div>
{login ? (
<>
<input placeholder="Email" />
<input placeholder="Password" />
<button>Login</button>
</>
) : null}
{logout ? (
<button>Logout</button>
) : null}
</div>
);
};
export default App;
App.jsx
import React, { useState } from 'react';
const App = () => {
const [isLogin, setIsLogin] = useState(true);
return (
<div>
<div>Username: Tutorialspoint</div>
<div onClick={() => setIsLogin((prev) => !prev)}>
{isLogin ? <Form login /> : <Form logout />}
</div>
</div>
);
};
const Form = ({ login, logout }) => {
return (
<div>
{login && (
<>
<input placeholder="Email" />
<input placeholder="Password" />
<button>Login</button>
</>
)}
{logout && (
<button>Logout</button>
)}
</div>
);
};
export default App; | [
{
"code": null,
"e": 1187,
"s": 1062,
"text": "In this article, we are going to see how to conditionally render a component based on some conditions in a React application"
},
{
"code": null,
"e": 1456,
"s": 1187,
"text": "In ReactJS, we can render only the desired components based on certain given conditions by using the if-else statements or by using the logical && operator of JavaScript. When the provided condition is satisfied, then React will match the UI and update it accordingly."
},
{
"code": null,
"e": 1640,
"s": 1456,
"text": "In this example, we will build a React application that has an App component as a parent component which will conditionally re-render the Form component and update the UI accordingly."
},
{
"code": null,
"e": 1648,
"s": 1640,
"text": "App.jsx"
},
{
"code": null,
"e": 2303,
"s": 1648,
"text": "import React, { useState } from 'react';\nconst App = () => {\n const [isLogin, setIsLogin] = useState(true);\n return (\n <div>\n <div>Username: Tutorialspoint</div>\n <div onClick={() => setIsLogin((prev) => !prev)}>\n {isLogin ? <Form login /> : <Form logout />}\n </div>\n </div>\n );\n};\n\nconst Form = ({ login, logout }) => {\n return (\n <div>\n {login ? (\n <>\n <input placeholder=\"Email\" />\n <input placeholder=\"Password\" />\n <button>Login</button>\n </>\n ) : null}\n {logout ? (\n <button>Logout</button>\n ) : null}\n </div>\n );\n};\nexport default App;"
},
{
"code": null,
"e": 2311,
"s": 2303,
"text": "App.jsx"
},
{
"code": null,
"e": 2954,
"s": 2311,
"text": "import React, { useState } from 'react';\nconst App = () => {\n const [isLogin, setIsLogin] = useState(true);\n return (\n <div>\n <div>Username: Tutorialspoint</div>\n <div onClick={() => setIsLogin((prev) => !prev)}>\n {isLogin ? <Form login /> : <Form logout />}\n </div>\n </div>\n );\n};\n\nconst Form = ({ login, logout }) => {\n return (\n <div>\n {login && (\n <>\n <input placeholder=\"Email\" />\n <input placeholder=\"Password\" />\n <button>Login</button>\n </>\n )}\n {logout && (\n <button>Logout</button>\n )}\n </div>\n );\n};\nexport default App;"
}
]
|
Tryit Editor v3.7 - Show Java | class MyPackageClass {
public static void main(String[] args) {
System.out.println("This is my package!"); | []
|
Multidex in Android - GeeksforGeeks | 19 Sep, 2021
Now as we are aware of Methods/Functions in android we know that every library has a large number of pre-built methods. In many, we have to use a lot of libraries according to the needs of our project which obviously increases the total number of methods in our android app. After adding multiple libraries an error occurs saying that ...
cannot fit requested classes in a single dex file 99876 > 65536
So before understanding this error we have to understand
How android build system works?
What is a DEX?
What is Multidexing?
How to achieve Multidexing?
How Multidexing actually works?
We make our app using Activities, Layouts, resource files, dependencies. All these get into the compiler and get converted into a single DEX (Dalvik executable) which is compiled resource ready for APK packing. Then it gets converted into an .APK file. Take a look at the below image for a clear understanding, here resource files mean the additional files we add to the project like images, videos, svg files.
Now we know the source code is converted into a DEX (Dalvik Executable) file which can run as an Android App and can only be understood by a computer. Most importantly a single DEX file can only contain 65536 numbers of methods. If your project is exceeding the number of methods, the error mentioned above occurs and therefore the use of multidexing becomes a must.
If the number of methods in our project is less than or equal to 65536 then the app code will be easily converted into a DEX file. But if the number of methods is greater than 65536 then we have to allow our app to create more than 1 DEX file and hence calling it “Multidexing”.
Step by step Implementation
Step 1: Create new project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. You can choose any language Java/Kotlin.
Step 2: Add Dependencies
If you are using an Android API version below 21 add the following dependency to your build.gradle file.
implementation 'com.android.support:multidex:1.0.3'
Step 3: Working with build.gradle(module) file
Ignore Step 1 if you are using API version 21 or above. Most probably you are maybe using above 21. Go to build.gradle file, inside that you will find the scope { } of defaultConfig then inside that scope just add multiDexEnabled = true as shown below then click sync now.
multiDexEnabled = true
Until now we saw if the number of methods is greater than 65536 we have to use more than 1 DEX file. Once you enable multidexing and if a single DEX file crosses its limit then a Primary DEX file will be created and is followed by Supporting DEX files. The Supporting DEX files will only be created if the limit is crossed in the Primary DEX file.
Whenever you get errors listed below or related to dex/multidex , you can try the above steps, It will help to solve the problem
Too many field references: 131000; max is 65536.
You may try using --multi-dex option.
Conversion to Dalvik format failed:
Unable to execute dex: method ID not in [0, 0xffff]: 65536
cannot fit requested classes in a single dex file 99876 > 65536
Picked
Android
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
How to Add Image to Drawable Folder in Android Studio?
How to Change the Background Color After Clicking the Button in Android?
How to Retrieve Data from the Firebase Realtime Database in Android?
GridView in Android with Example
ImageView in Android with Example | [
{
"code": null,
"e": 24725,
"s": 24697,
"text": "\n19 Sep, 2021"
},
{
"code": null,
"e": 25065,
"s": 24725,
"text": "Now as we are aware of Methods/Functions in android we know that every library has a large number of pre-built methods. In many, we have to use a lot of libraries according to the needs of our project which obviously increases the total number of methods in our android app. After adding multiple libraries an error occurs saying that ... "
},
{
"code": null,
"e": 25129,
"s": 25065,
"text": "cannot fit requested classes in a single dex file 99876 > 65536"
},
{
"code": null,
"e": 25187,
"s": 25129,
"text": "So before understanding this error we have to understand "
},
{
"code": null,
"e": 25219,
"s": 25187,
"text": "How android build system works?"
},
{
"code": null,
"e": 25234,
"s": 25219,
"text": "What is a DEX?"
},
{
"code": null,
"e": 25255,
"s": 25234,
"text": "What is Multidexing?"
},
{
"code": null,
"e": 25283,
"s": 25255,
"text": "How to achieve Multidexing?"
},
{
"code": null,
"e": 25315,
"s": 25283,
"text": "How Multidexing actually works?"
},
{
"code": null,
"e": 25726,
"s": 25315,
"text": "We make our app using Activities, Layouts, resource files, dependencies. All these get into the compiler and get converted into a single DEX (Dalvik executable) which is compiled resource ready for APK packing. Then it gets converted into an .APK file. Take a look at the below image for a clear understanding, here resource files mean the additional files we add to the project like images, videos, svg files."
},
{
"code": null,
"e": 26093,
"s": 25726,
"text": "Now we know the source code is converted into a DEX (Dalvik Executable) file which can run as an Android App and can only be understood by a computer. Most importantly a single DEX file can only contain 65536 numbers of methods. If your project is exceeding the number of methods, the error mentioned above occurs and therefore the use of multidexing becomes a must."
},
{
"code": null,
"e": 26373,
"s": 26093,
"text": "If the number of methods in our project is less than or equal to 65536 then the app code will be easily converted into a DEX file. But if the number of methods is greater than 65536 then we have to allow our app to create more than 1 DEX file and hence calling it “Multidexing”. "
},
{
"code": null,
"e": 26401,
"s": 26373,
"text": "Step by step Implementation"
},
{
"code": null,
"e": 26428,
"s": 26401,
"text": "Step 1: Create new project"
},
{
"code": null,
"e": 26580,
"s": 26428,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. You can choose any language Java/Kotlin."
},
{
"code": null,
"e": 26605,
"s": 26580,
"text": "Step 2: Add Dependencies"
},
{
"code": null,
"e": 26710,
"s": 26605,
"text": "If you are using an Android API version below 21 add the following dependency to your build.gradle file."
},
{
"code": null,
"e": 26762,
"s": 26710,
"text": "implementation 'com.android.support:multidex:1.0.3'"
},
{
"code": null,
"e": 26809,
"s": 26762,
"text": "Step 3: Working with build.gradle(module) file"
},
{
"code": null,
"e": 27082,
"s": 26809,
"text": "Ignore Step 1 if you are using API version 21 or above. Most probably you are maybe using above 21. Go to build.gradle file, inside that you will find the scope { } of defaultConfig then inside that scope just add multiDexEnabled = true as shown below then click sync now."
},
{
"code": null,
"e": 27105,
"s": 27082,
"text": "multiDexEnabled = true"
},
{
"code": null,
"e": 27454,
"s": 27105,
"text": "Until now we saw if the number of methods is greater than 65536 we have to use more than 1 DEX file. Once you enable multidexing and if a single DEX file crosses its limit then a Primary DEX file will be created and is followed by Supporting DEX files. The Supporting DEX files will only be created if the limit is crossed in the Primary DEX file. "
},
{
"code": null,
"e": 27583,
"s": 27454,
"text": "Whenever you get errors listed below or related to dex/multidex , you can try the above steps, It will help to solve the problem"
},
{
"code": null,
"e": 27670,
"s": 27583,
"text": "Too many field references: 131000; max is 65536.\nYou may try using --multi-dex option."
},
{
"code": null,
"e": 27765,
"s": 27670,
"text": "Conversion to Dalvik format failed:\nUnable to execute dex: method ID not in [0, 0xffff]: 65536"
},
{
"code": null,
"e": 27829,
"s": 27765,
"text": "cannot fit requested classes in a single dex file 99876 > 65536"
},
{
"code": null,
"e": 27836,
"s": 27829,
"text": "Picked"
},
{
"code": null,
"e": 27844,
"s": 27836,
"text": "Android"
},
{
"code": null,
"e": 27852,
"s": 27844,
"text": "Android"
},
{
"code": null,
"e": 27950,
"s": 27852,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27959,
"s": 27950,
"text": "Comments"
},
{
"code": null,
"e": 27972,
"s": 27959,
"text": "Old Comments"
},
{
"code": null,
"e": 28011,
"s": 27972,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 28061,
"s": 28011,
"text": "How to Read Data from SQLite Database in Android?"
},
{
"code": null,
"e": 28112,
"s": 28061,
"text": "How to Post Data to API using Retrofit in Android?"
},
{
"code": null,
"e": 28150,
"s": 28112,
"text": "Android Listview in Java with Example"
},
{
"code": null,
"e": 28192,
"s": 28150,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 28247,
"s": 28192,
"text": "How to Add Image to Drawable Folder in Android Studio?"
},
{
"code": null,
"e": 28320,
"s": 28247,
"text": "How to Change the Background Color After Clicking the Button in Android?"
},
{
"code": null,
"e": 28389,
"s": 28320,
"text": "How to Retrieve Data from the Firebase Realtime Database in Android?"
},
{
"code": null,
"e": 28422,
"s": 28389,
"text": "GridView in Android with Example"
}
]
|
Advantages of Exception Handling - 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
Java provides a sophisticated exception handling mechanism that enables you to detect exceptional conditions in your programs and fix the exceptions as and when they occur. Using exception handling features offers several advantages. Let’s examine these advantages in detail.
One of the important purposes of exception handling in Java is to continue program execution after an exception is caught and handled.
The execution of a Java program does not terminate when an exception occurs. Once the exception is resolved, program execution continues till completion.
By using well-structured try, catch, and finally blocks, you can create programs that fix exceptions and continue execution as if there were no errors. If there is a possibility of more than one exception, you can use multiple catch blocks to handle the different exceptions.
The following program generates two random integers in each iteration of the for loop and performs a division operation. If a division by zero error occurs, the exception is handled in the catch block. Thus, an arithmetic exception does not terminate the program and the for loop continues execution after the catch block is executed.
import java.util.Random;
class ExceptionExample {
public static void main(String args[]) {
int a = 0, b = 0, c = 0;
Random r = new Random();
for (int i = 0; i < 10; i++) {
try {
b = r.nextInt();
c = r.nextInt();
a = 12345 / (b / c);
} catch (ArithmeticException e) {
System.out.println("Division by zero");
a = 0;
}
System.out.println("a: " + a);
}
}
}
The use of try/catch blocks segregates error-handling code and program code making it easier to identify the logical flow of a program. The logic in the program code does not include details of the actions to be performed when an exception occurs. Such details are present in the catch blocks.
Unlike many traditional programming languages that include confusing error reporting and error handling code in between the program code, Java allows you to create well-organized code. Separating error handling and program logic in this way makes it easier to understand and maintain programs in the long run.
Java’s exception handling mechanism works in such a way that error reports are propagated up the call stack. This is because whenever an exception occurs, Java’s runtime environment checks the call stack backwards to identify methods that can catch the exception.
When a program includes several calls between methods, propagation of exceptions up the call stack ensures that exceptions are caught by the right methods.
The exceptions thrown in a Java program are objects of a class. Since the Throwable class overrides the toString() method, you can obtain a description of an exception in the form of a string and display the description using a println() statement.
catch (ArithmeticException e) {
System.out.println("Exception occurred: " + e);
}
The above catch statement displays the following output when an arithmetic exception occurs:
Exception: java.lang.ArithmeticException: / by zero
Traditional programming languages use error codes for error reporting. In the case of large programs, debugging errors using their error codes gets complex. The meaningful descriptions provided by Java’s exception handling mechanism are helpful when you need to debug large programs or experiment with complex code.
Java provides several super classes and sub classes that group exceptions based on their type. While the super classes like IOException provide functionality to handle exceptions of a general type, sub classes like FileNotFoundException provide functionality to handle specific exception types.
A method can catch and handle a specific exception type by using a sub class object.
For example, FileNotFoundException is a sub class that only handles a file not found exception. In case a method needs to handle multiple exceptions that are of the same group, you can specify an object of a super class in the method’s catch statement.
For example, IOException is a super class that handles all IO-related exceptions.
Happy Learning 🙂
Checked and Unchecked Exceptions in Java
Try with Resources Example in Java
user defined exceptions in Java
Catching Multiple Exceptions in Java 7
Top 10 Exceptions in Java
Thread join Example in Java
Spring boot exception handling rest service (CRUD) operations
What is Hibernate
Hello World Java Program Example
Advantages of Java Programming
What is Exception in Java
How do we Handle Exception in Java
Exception Chaining and Debugging Example
Java – Types of Polymorphism and Advantages
Top 10 Advantages of Hibernate
Checked and Unchecked Exceptions in Java
Try with Resources Example in Java
user defined exceptions in Java
Catching Multiple Exceptions in Java 7
Top 10 Exceptions in Java
Thread join Example in Java
Spring boot exception handling rest service (CRUD) operations
What is Hibernate
Hello World Java Program Example
Advantages of Java Programming
What is Exception in Java
How do we Handle Exception in Java
Exception Chaining and Debugging Example
Java – Types of Polymorphism and Advantages
Top 10 Advantages of Hibernate
priya
July 6, 2018 at 11:29 am - Reply
An Exception in Java is an object which contains information about the error that has occurred. These Exception objects are automatically created when an unexpected situation arises.Thanks for sharing.
Priyanka Vasam
March 20, 2022 at 12:35 pm - Reply
This page is amazing..it helped me a lot in preparing for my exams
priya
July 6, 2018 at 11:29 am - Reply
An Exception in Java is an object which contains information about the error that has occurred. These Exception objects are automatically created when an unexpected situation arises.Thanks for sharing.
An Exception in Java is an object which contains information about the error that has occurred. These Exception objects are automatically created when an unexpected situation arises.Thanks for sharing.
Priyanka Vasam
March 20, 2022 at 12:35 pm - Reply
This page is amazing..it helped me a lot in preparing for my exams
This page is amazing..it helped me a lot in preparing for my exams
Δ
Install Java on Mac OS
Install AWS CLI on Windows
Install Minikube on Windows
Install Docker Toolbox on Windows
Install SOAPUI on Windows
Install Gradle on Windows
Install RabbitMQ on Windows
Install PuTTY on windows
Install Mysql on Windows
Install Hibernate Tools in Eclipse
Install Elasticsearch on Windows
Install Maven on Windows
Install Maven on Ubuntu
Install Maven on Windows Command
Add OJDBC jar to Maven Repository
Install Ant on Windows
Install RabbitMQ on Windows
Install Apache Kafka on Ubuntu
Install Apache Kafka on Windows
Java8 – Install Windows
Java8 – foreach
Java8 – forEach with index
Java8 – Stream Filter Objects
Java8 – Comparator Userdefined
Java8 – GroupingBy
Java8 – SummingInt
Java8 – walk ReadFiles
Java8 – JAVA_HOME on Windows
Howto – Install Java on Mac OS
Howto – Convert Iterable to Stream
Howto – Get common elements from two Lists
Howto – Convert List to String
Howto – Concatenate Arrays using Stream
Howto – Remove duplicates from List
Howto – Filter null values from Stream
Howto – Convert List to Map
Howto – Convert Stream to List
Howto – Sort a Map
Howto – Filter a Map
Howto – Get Current UTC Time
Howto – Verify an Array contains a specific value
Howto – Convert ArrayList to Array
Howto – Read File Line By Line
Howto – Convert Date to LocalDate
Howto – Merge Streams
Howto – Resolve NullPointerException in toMap
Howto -Get Stream count
Howto – Get Min and Max values in a Stream
Howto – Convert InputStream to String | [
{
"code": null,
"e": 158,
"s": 123,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 172,
"s": 158,
"text": "Java Examples"
},
{
"code": null,
"e": 183,
"s": 172,
"text": "C Examples"
},
{
"code": null,
"e": 195,
"s": 183,
"text": "C Tutorials"
},
{
"code": null,
"e": 199,
"s": 195,
"text": "aws"
},
{
"code": null,
"e": 234,
"s": 199,
"text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC"
},
{
"code": null,
"e": 245,
"s": 234,
"text": "EXCEPTIONS"
},
{
"code": null,
"e": 257,
"s": 245,
"text": "COLLECTIONS"
},
{
"code": null,
"e": 263,
"s": 257,
"text": "SWING"
},
{
"code": null,
"e": 268,
"s": 263,
"text": "JDBC"
},
{
"code": null,
"e": 275,
"s": 268,
"text": "JAVA 8"
},
{
"code": null,
"e": 282,
"s": 275,
"text": "SPRING"
},
{
"code": null,
"e": 294,
"s": 282,
"text": "SPRING BOOT"
},
{
"code": null,
"e": 304,
"s": 294,
"text": "HIBERNATE"
},
{
"code": null,
"e": 311,
"s": 304,
"text": "PYTHON"
},
{
"code": null,
"e": 315,
"s": 311,
"text": "PHP"
},
{
"code": null,
"e": 322,
"s": 315,
"text": "JQUERY"
},
{
"code": null,
"e": 357,
"s": 322,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 371,
"s": 357,
"text": "Java Examples"
},
{
"code": null,
"e": 382,
"s": 371,
"text": "C Examples"
},
{
"code": null,
"e": 394,
"s": 382,
"text": "C Tutorials"
},
{
"code": null,
"e": 398,
"s": 394,
"text": "aws"
},
{
"code": null,
"e": 674,
"s": 398,
"text": "Java provides a sophisticated exception handling mechanism that enables you to detect exceptional conditions in your programs and fix the exceptions as and when they occur. Using exception handling features offers several advantages. Let’s examine these advantages in detail."
},
{
"code": null,
"e": 810,
"s": 674,
"text": "One of the important purposes of exception handling in Java is to continue program execution after an exception is caught and handled. "
},
{
"code": null,
"e": 965,
"s": 810,
"text": "The execution of a Java program does not terminate when an exception occurs. Once the exception is resolved, program execution continues till completion. "
},
{
"code": null,
"e": 1241,
"s": 965,
"text": "By using well-structured try, catch, and finally blocks, you can create programs that fix exceptions and continue execution as if there were no errors. If there is a possibility of more than one exception, you can use multiple catch blocks to handle the different exceptions."
},
{
"code": null,
"e": 1576,
"s": 1241,
"text": "The following program generates two random integers in each iteration of the for loop and performs a division operation. If a division by zero error occurs, the exception is handled in the catch block. Thus, an arithmetic exception does not terminate the program and the for loop continues execution after the catch block is executed."
},
{
"code": null,
"e": 2103,
"s": 1576,
"text": "import java.util.Random;\n \nclass ExceptionExample {\n \n public static void main(String args[]) {\n int a = 0, b = 0, c = 0;\n Random r = new Random();\n \n for (int i = 0; i < 10; i++) {\n try {\n b = r.nextInt();\n c = r.nextInt();\n a = 12345 / (b / c);\n } catch (ArithmeticException e) {\n System.out.println(\"Division by zero\");\n a = 0;\n }\n System.out.println(\"a: \" + a);\n }\n }\n}"
},
{
"code": null,
"e": 2397,
"s": 2103,
"text": "The use of try/catch blocks segregates error-handling code and program code making it easier to identify the logical flow of a program. The logic in the program code does not include details of the actions to be performed when an exception occurs. Such details are present in the catch blocks."
},
{
"code": null,
"e": 2708,
"s": 2397,
"text": "Unlike many traditional programming languages that include confusing error reporting and error handling code in between the program code, Java allows you to create well-organized code. Separating error handling and program logic in this way makes it easier to understand and maintain programs in the long run. "
},
{
"code": null,
"e": 2974,
"s": 2708,
"text": " Java’s exception handling mechanism works in such a way that error reports are propagated up the call stack. This is because whenever an exception occurs, Java’s runtime environment checks the call stack backwards to identify methods that can catch the exception. "
},
{
"code": null,
"e": 3130,
"s": 2974,
"text": "When a program includes several calls between methods, propagation of exceptions up the call stack ensures that exceptions are caught by the right methods."
},
{
"code": null,
"e": 3380,
"s": 3130,
"text": "The exceptions thrown in a Java program are objects of a class. Since the Throwable class overrides the toString() method, you can obtain a description of an exception in the form of a string and display the description using a println() statement. "
},
{
"code": null,
"e": 3471,
"s": 3380,
"text": "catch (ArithmeticException e) {\n System.out.println(\"Exception occurred: \" + e);\n}\n\n"
},
{
"code": null,
"e": 3564,
"s": 3471,
"text": "The above catch statement displays the following output when an arithmetic exception occurs:"
},
{
"code": null,
"e": 3616,
"s": 3564,
"text": "Exception: java.lang.ArithmeticException: / by zero"
},
{
"code": null,
"e": 3932,
"s": 3616,
"text": "Traditional programming languages use error codes for error reporting. In the case of large programs, debugging errors using their error codes gets complex. The meaningful descriptions provided by Java’s exception handling mechanism are helpful when you need to debug large programs or experiment with complex code."
},
{
"code": null,
"e": 4229,
"s": 3932,
"text": " Java provides several super classes and sub classes that group exceptions based on their type. While the super classes like IOException provide functionality to handle exceptions of a general type, sub classes like FileNotFoundException provide functionality to handle specific exception types. "
},
{
"code": null,
"e": 4315,
"s": 4229,
"text": "A method can catch and handle a specific exception type by using a sub class object. "
},
{
"code": null,
"e": 4569,
"s": 4315,
"text": "For example, FileNotFoundException is a sub class that only handles a file not found exception. In case a method needs to handle multiple exceptions that are of the same group, you can specify an object of a super class in the method’s catch statement. "
},
{
"code": null,
"e": 4651,
"s": 4569,
"text": "For example, IOException is a super class that handles all IO-related exceptions."
},
{
"code": null,
"e": 4669,
"s": 4651,
"text": " Happy Learning 🙂"
},
{
"code": null,
"e": 5194,
"s": 4669,
"text": "\nChecked and Unchecked Exceptions in Java\nTry with Resources Example in Java\nuser defined exceptions in Java\nCatching Multiple Exceptions in Java 7\nTop 10 Exceptions in Java\nThread join Example in Java\nSpring boot exception handling rest service (CRUD) operations\nWhat is Hibernate\nHello World Java Program Example\nAdvantages of Java Programming\nWhat is Exception in Java\nHow do we Handle Exception in Java\nException Chaining and Debugging Example\nJava – Types of Polymorphism and Advantages\nTop 10 Advantages of Hibernate\n"
},
{
"code": null,
"e": 5235,
"s": 5194,
"text": "Checked and Unchecked Exceptions in Java"
},
{
"code": null,
"e": 5270,
"s": 5235,
"text": "Try with Resources Example in Java"
},
{
"code": null,
"e": 5302,
"s": 5270,
"text": "user defined exceptions in Java"
},
{
"code": null,
"e": 5341,
"s": 5302,
"text": "Catching Multiple Exceptions in Java 7"
},
{
"code": null,
"e": 5367,
"s": 5341,
"text": "Top 10 Exceptions in Java"
},
{
"code": null,
"e": 5396,
"s": 5367,
"text": "Thread join Example in Java"
},
{
"code": null,
"e": 5458,
"s": 5396,
"text": "Spring boot exception handling rest service (CRUD) operations"
},
{
"code": null,
"e": 5476,
"s": 5458,
"text": "What is Hibernate"
},
{
"code": null,
"e": 5509,
"s": 5476,
"text": "Hello World Java Program Example"
},
{
"code": null,
"e": 5540,
"s": 5509,
"text": "Advantages of Java Programming"
},
{
"code": null,
"e": 5566,
"s": 5540,
"text": "What is Exception in Java"
},
{
"code": null,
"e": 5601,
"s": 5566,
"text": "How do we Handle Exception in Java"
},
{
"code": null,
"e": 5642,
"s": 5601,
"text": "Exception Chaining and Debugging Example"
},
{
"code": null,
"e": 5686,
"s": 5642,
"text": "Java – Types of Polymorphism and Advantages"
},
{
"code": null,
"e": 5717,
"s": 5686,
"text": "Top 10 Advantages of Hibernate"
},
{
"code": null,
"e": 6099,
"s": 5717,
"text": "\n\n\n\n\n\npriya\nJuly 6, 2018 at 11:29 am - Reply \n\nAn Exception in Java is an object which contains information about the error that has occurred. These Exception objects are automatically created when an unexpected situation arises.Thanks for sharing.\n\n\n\n\n\n\n\n\n\nPriyanka Vasam\nMarch 20, 2022 at 12:35 pm - Reply \n\nThis page is amazing..it helped me a lot in preparing for my exams\n\n\n\n\n"
},
{
"code": null,
"e": 6351,
"s": 6099,
"text": "\n\n\n\n\npriya\nJuly 6, 2018 at 11:29 am - Reply \n\nAn Exception in Java is an object which contains information about the error that has occurred. These Exception objects are automatically created when an unexpected situation arises.Thanks for sharing.\n\n\n\n"
},
{
"code": null,
"e": 6553,
"s": 6351,
"text": "An Exception in Java is an object which contains information about the error that has occurred. These Exception objects are automatically created when an unexpected situation arises.Thanks for sharing."
},
{
"code": null,
"e": 6681,
"s": 6553,
"text": "\n\n\n\n\nPriyanka Vasam\nMarch 20, 2022 at 12:35 pm - Reply \n\nThis page is amazing..it helped me a lot in preparing for my exams\n\n\n\n"
},
{
"code": null,
"e": 6748,
"s": 6681,
"text": "This page is amazing..it helped me a lot in preparing for my exams"
},
{
"code": null,
"e": 6754,
"s": 6752,
"text": "Δ"
},
{
"code": null,
"e": 6778,
"s": 6754,
"text": " Install Java on Mac OS"
},
{
"code": null,
"e": 6806,
"s": 6778,
"text": " Install AWS CLI on Windows"
},
{
"code": null,
"e": 6835,
"s": 6806,
"text": " Install Minikube on Windows"
},
{
"code": null,
"e": 6870,
"s": 6835,
"text": " Install Docker Toolbox on Windows"
},
{
"code": null,
"e": 6897,
"s": 6870,
"text": " Install SOAPUI on Windows"
},
{
"code": null,
"e": 6924,
"s": 6897,
"text": " Install Gradle on Windows"
},
{
"code": null,
"e": 6953,
"s": 6924,
"text": " Install RabbitMQ on Windows"
},
{
"code": null,
"e": 6979,
"s": 6953,
"text": " Install PuTTY on windows"
},
{
"code": null,
"e": 7005,
"s": 6979,
"text": " Install Mysql on Windows"
},
{
"code": null,
"e": 7041,
"s": 7005,
"text": " Install Hibernate Tools in Eclipse"
},
{
"code": null,
"e": 7075,
"s": 7041,
"text": " Install Elasticsearch on Windows"
},
{
"code": null,
"e": 7101,
"s": 7075,
"text": " Install Maven on Windows"
},
{
"code": null,
"e": 7126,
"s": 7101,
"text": " Install Maven on Ubuntu"
},
{
"code": null,
"e": 7160,
"s": 7126,
"text": " Install Maven on Windows Command"
},
{
"code": null,
"e": 7195,
"s": 7160,
"text": " Add OJDBC jar to Maven Repository"
},
{
"code": null,
"e": 7219,
"s": 7195,
"text": " Install Ant on Windows"
},
{
"code": null,
"e": 7248,
"s": 7219,
"text": " Install RabbitMQ on Windows"
},
{
"code": null,
"e": 7280,
"s": 7248,
"text": " Install Apache Kafka on Ubuntu"
},
{
"code": null,
"e": 7313,
"s": 7280,
"text": " Install Apache Kafka on Windows"
},
{
"code": null,
"e": 7338,
"s": 7313,
"text": " Java8 – Install Windows"
},
{
"code": null,
"e": 7355,
"s": 7338,
"text": " Java8 – foreach"
},
{
"code": null,
"e": 7383,
"s": 7355,
"text": " Java8 – forEach with index"
},
{
"code": null,
"e": 7414,
"s": 7383,
"text": " Java8 – Stream Filter Objects"
},
{
"code": null,
"e": 7446,
"s": 7414,
"text": " Java8 – Comparator Userdefined"
},
{
"code": null,
"e": 7466,
"s": 7446,
"text": " Java8 – GroupingBy"
},
{
"code": null,
"e": 7486,
"s": 7466,
"text": " Java8 – SummingInt"
},
{
"code": null,
"e": 7510,
"s": 7486,
"text": " Java8 – walk ReadFiles"
},
{
"code": null,
"e": 7540,
"s": 7510,
"text": " Java8 – JAVA_HOME on Windows"
},
{
"code": null,
"e": 7572,
"s": 7540,
"text": " Howto – Install Java on Mac OS"
},
{
"code": null,
"e": 7608,
"s": 7572,
"text": " Howto – Convert Iterable to Stream"
},
{
"code": null,
"e": 7652,
"s": 7608,
"text": " Howto – Get common elements from two Lists"
},
{
"code": null,
"e": 7684,
"s": 7652,
"text": " Howto – Convert List to String"
},
{
"code": null,
"e": 7725,
"s": 7684,
"text": " Howto – Concatenate Arrays using Stream"
},
{
"code": null,
"e": 7762,
"s": 7725,
"text": " Howto – Remove duplicates from List"
},
{
"code": null,
"e": 7802,
"s": 7762,
"text": " Howto – Filter null values from Stream"
},
{
"code": null,
"e": 7831,
"s": 7802,
"text": " Howto – Convert List to Map"
},
{
"code": null,
"e": 7863,
"s": 7831,
"text": " Howto – Convert Stream to List"
},
{
"code": null,
"e": 7883,
"s": 7863,
"text": " Howto – Sort a Map"
},
{
"code": null,
"e": 7905,
"s": 7883,
"text": " Howto – Filter a Map"
},
{
"code": null,
"e": 7935,
"s": 7905,
"text": " Howto – Get Current UTC Time"
},
{
"code": null,
"e": 7986,
"s": 7935,
"text": " Howto – Verify an Array contains a specific value"
},
{
"code": null,
"e": 8022,
"s": 7986,
"text": " Howto – Convert ArrayList to Array"
},
{
"code": null,
"e": 8054,
"s": 8022,
"text": " Howto – Read File Line By Line"
},
{
"code": null,
"e": 8089,
"s": 8054,
"text": " Howto – Convert Date to LocalDate"
},
{
"code": null,
"e": 8112,
"s": 8089,
"text": " Howto – Merge Streams"
},
{
"code": null,
"e": 8159,
"s": 8112,
"text": " Howto – Resolve NullPointerException in toMap"
},
{
"code": null,
"e": 8184,
"s": 8159,
"text": " Howto -Get Stream count"
},
{
"code": null,
"e": 8228,
"s": 8184,
"text": " Howto – Get Min and Max values in a Stream"
}
]
|
jQuery Mobile - Datapicker Widget | The DatePicker function can be used with widgets using JqueryUI in jQuery mobile as it does not support jQuery mobile widget. It is used to focus on the input to open an interactive calendar in a small overlay.
The calender pops up when input is focused to insert date. Add data-role = "date" attribute in the <input> field to include the date, it displays in dd/mm/yy format.
Following example demonstrates the use of popup datapicker in the jQuery Mobile.
<!DOCTYPE html>
<html>
<head>
<meta name = "viewport" content = "width = device-width, initial-scale = 1">
<link rel = "stylesheet" href = "https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
<link rel = "stylesheet" href = "https://rawgithub.com/arschmitz/jquery-mobile-datepicker-wrapper/master/jquery.mobile.datepicker.css" />
<script src = "https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src = "https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<script src = "https://rawgithub.com/jquery/jquery-ui/1-10-stable/ui/jquery.ui.datepicker.js"></script>
<script src = "https://rawgithub.com/arschmitz/jquery-mobile-datepicker-wrapper/master/jquery.mobile.datepicker.js"></script>
</head>
<body>
<h2>Popup Datapicker Example</h2>
<form>
<input type = "text" data-role = "date">
</form>
</body>
</html>
Let's carry out the following steps to see how the above code works −
Save the above html code as popup_datapicker.html file in your server root folder.
Save the above html code as popup_datapicker.html file in your server root folder.
Open this HTML file as http://localhost/popup_datapicker.html and the following output will be displayed.
Open this HTML file as http://localhost/popup_datapicker.html and the following output will be displayed.
Include data-inline = "true" to display the interactive calendar.
Following example demonstrates the use of inline datapicker in the jQuery Mobile.
<!DOCTYPE html>
<html>
<head>
<meta name = "viewport" content = "width = device-width, initial-scale = 1">
<link rel = "stylesheet" href = "https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
<link rel = "stylesheet" href = "https://rawgithub.com/arschmitz/jquery-mobile-datepicker-wrapper/master/jquery.mobile.datepicker.css" />
<script src = "https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src = "https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<script src = "https://rawgithub.com/jquery/jquery-ui/1-10-stable/ui/jquery.ui.datepicker.js"></script>
<script src = "https://rawgithub.com/arschmitz/jquery-mobile-datepicker-wrapper/master/jquery.mobile.datepicker.js"></script>
</head>
<body>
<h2>Popup Datapicker Example</h2>
<form>
<input type = "text" data-role = "date" data-inline = "true">
</form>
</body>
</html>
Let's carry out the following steps to see how the above code works −
Save the above html code as inline_datapicker.html file in your server root folder.
Save the above html code as inline_datapicker.html file in your server root folder.
Open this HTML file as http://localhost/inline_datapicker.html and the following output will be displayed.
Open this HTML file as http://localhost/inline_datapicker.html and the following output will be displayed.
27 Lectures
1 hours
Mahesh Kumar
27 Lectures
1.5 hours
Pratik Singh
72 Lectures
4.5 hours
Frahaan Hussain
60 Lectures
9 hours
Eduonix Learning Solutions
17 Lectures
2 hours
Sandip Bhattacharya
12 Lectures
53 mins
Laurence Svekis
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2159,
"s": 1948,
"text": "The DatePicker function can be used with widgets using JqueryUI in jQuery mobile as it does not support jQuery mobile widget. It is used to focus on the input to open an interactive calendar in a small overlay."
},
{
"code": null,
"e": 2325,
"s": 2159,
"text": "The calender pops up when input is focused to insert date. Add data-role = \"date\" attribute in the <input> field to include the date, it displays in dd/mm/yy format."
},
{
"code": null,
"e": 2406,
"s": 2325,
"text": "Following example demonstrates the use of popup datapicker in the jQuery Mobile."
},
{
"code": null,
"e": 3351,
"s": 2406,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1\">\n <link rel = \"stylesheet\" href = \"https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css\">\n <link rel = \"stylesheet\" href = \"https://rawgithub.com/arschmitz/jquery-mobile-datepicker-wrapper/master/jquery.mobile.datepicker.css\" />\n <script src = \"https://code.jquery.com/jquery-1.11.3.min.js\"></script>\n <script src = \"https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js\"></script>\n <script src = \"https://rawgithub.com/jquery/jquery-ui/1-10-stable/ui/jquery.ui.datepicker.js\"></script>\n <script src = \"https://rawgithub.com/arschmitz/jquery-mobile-datepicker-wrapper/master/jquery.mobile.datepicker.js\"></script>\n </head>\n \n <body>\n <h2>Popup Datapicker Example</h2>\n <form>\n <input type = \"text\" data-role = \"date\">\n </form>\n </body>\n</html>"
},
{
"code": null,
"e": 3421,
"s": 3351,
"text": "Let's carry out the following steps to see how the above code works −"
},
{
"code": null,
"e": 3504,
"s": 3421,
"text": "Save the above html code as popup_datapicker.html file in your server root folder."
},
{
"code": null,
"e": 3587,
"s": 3504,
"text": "Save the above html code as popup_datapicker.html file in your server root folder."
},
{
"code": null,
"e": 3693,
"s": 3587,
"text": "Open this HTML file as http://localhost/popup_datapicker.html and the following output will be displayed."
},
{
"code": null,
"e": 3799,
"s": 3693,
"text": "Open this HTML file as http://localhost/popup_datapicker.html and the following output will be displayed."
},
{
"code": null,
"e": 3865,
"s": 3799,
"text": "Include data-inline = \"true\" to display the interactive calendar."
},
{
"code": null,
"e": 3947,
"s": 3865,
"text": "Following example demonstrates the use of inline datapicker in the jQuery Mobile."
},
{
"code": null,
"e": 4910,
"s": 3947,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1\">\n <link rel = \"stylesheet\" href = \"https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css\">\n <link rel = \"stylesheet\" href = \"https://rawgithub.com/arschmitz/jquery-mobile-datepicker-wrapper/master/jquery.mobile.datepicker.css\" />\n <script src = \"https://code.jquery.com/jquery-1.11.3.min.js\"></script>\n <script src = \"https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js\"></script>\n <script src = \"https://rawgithub.com/jquery/jquery-ui/1-10-stable/ui/jquery.ui.datepicker.js\"></script>\n <script src = \"https://rawgithub.com/arschmitz/jquery-mobile-datepicker-wrapper/master/jquery.mobile.datepicker.js\"></script>\n </head>\n \n <body>\n <h2>Popup Datapicker Example</h2>\n <form>\n <input type = \"text\" data-role = \"date\" data-inline = \"true\">\n </form>\n </body>\n</html>"
},
{
"code": null,
"e": 4980,
"s": 4910,
"text": "Let's carry out the following steps to see how the above code works −"
},
{
"code": null,
"e": 5064,
"s": 4980,
"text": "Save the above html code as inline_datapicker.html file in your server root folder."
},
{
"code": null,
"e": 5148,
"s": 5064,
"text": "Save the above html code as inline_datapicker.html file in your server root folder."
},
{
"code": null,
"e": 5255,
"s": 5148,
"text": "Open this HTML file as http://localhost/inline_datapicker.html and the following output will be displayed."
},
{
"code": null,
"e": 5362,
"s": 5255,
"text": "Open this HTML file as http://localhost/inline_datapicker.html and the following output will be displayed."
},
{
"code": null,
"e": 5395,
"s": 5362,
"text": "\n 27 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5409,
"s": 5395,
"text": " Mahesh Kumar"
},
{
"code": null,
"e": 5444,
"s": 5409,
"text": "\n 27 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5458,
"s": 5444,
"text": " Pratik Singh"
},
{
"code": null,
"e": 5493,
"s": 5458,
"text": "\n 72 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 5510,
"s": 5493,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 5543,
"s": 5510,
"text": "\n 60 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 5571,
"s": 5543,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 5604,
"s": 5571,
"text": "\n 17 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 5625,
"s": 5604,
"text": " Sandip Bhattacharya"
},
{
"code": null,
"e": 5657,
"s": 5625,
"text": "\n 12 Lectures \n 53 mins\n"
},
{
"code": null,
"e": 5674,
"s": 5657,
"text": " Laurence Svekis"
},
{
"code": null,
"e": 5681,
"s": 5674,
"text": " Print"
},
{
"code": null,
"e": 5692,
"s": 5681,
"text": " Add Notes"
}
]
|
C++ Program to Implement Bit Array | This is a C++ program to implement Bit Array. A Bit Array is an array data structures that compactly stores data. It is basically used to implement a simple data structure.
Functions and pseudocodes:
Begin
Function getBit(int val,int pos)
singleBit->b = 0
if(pos == 0)
singleBit->b = val & 1
else
singleBit->b = ( val & (1 << pos ) ) >> pos
return singleBit
Function setBit(BitArr *bt,B *bit,int pos)
bt->bVal[pos] = bit
return bt
Function getVal(BitArr *bArray)
initialize val = 0
initialize bVal = 0
bVal = bArray->bVal[0]->b
val= val|bVal
for i = 1 to B_A_LENGTH-1
bVal = bArray->bVal[i]->b
bVal =bVal << i
val=val | bVal
return val
done
End.
Live Demo
#include <iostream>
#include <string>
using namespace std;
#define B_A_LENGTH 4
typedef struct {
unsigned int b : 1;
} B;
class BitArr {
private:
B **bVal;
public:
BitArr() {
bVal = new B* [B_A_LENGTH];
}
B *getBit(int val,int pos) {
B *singleBit = new B;
singleBit->b = 0;
if(pos == 0) {
singleBit->b = val & 1;
} else {
singleBit->b = ( val & (1 << pos ) ) >> pos;
}
return singleBit;
}
BitArr *setBit(BitArr *bt,B *bit,int pos) {
bt->bVal[pos] = bit;
return bt;
}
int getVal(BitArr *bArray) {
int val = 0;
unsigned int bVal = 0;
bVal = bArray->bVal[0]->b;
val |= bVal;
for(int i = 1; i < B_A_LENGTH; i++) {
bVal = bArray->bVal[i]->b;
bVal <<= i;
val |= bVal;
}
return val;
}
};
int main() {
int v;
cout<<"Enter 4 bit integer value (0 - 8): ";
cin>>v;
BitArr bt, *samplebt;
samplebt = new BitArr;
for (int i = 0; i < B_A_LENGTH; i++) {
samplebt = bt.setBit(samplebt, bt.getBit(v, i), i);
cout<<"Bit of "<<v<<" at positon "<<i<<": "<<"\n"<<bt.getBit(v, i)->b<<endl;
}
cout<<"The value is: "<<bt.getVal(samplebt)<<endl;
return 0;
}
Enter 4 bit integer value (0 - 8): 6Bit of 6 at positon 0:
0
Bit of 6 at positon 1:
1
Bit of 6 at positon 2:
1
Bit of 6 at positon 3:
0
The value is: 6 | [
{
"code": null,
"e": 1235,
"s": 1062,
"text": "This is a C++ program to implement Bit Array. A Bit Array is an array data structures that compactly stores data. It is basically used to implement a simple data structure."
},
{
"code": null,
"e": 1262,
"s": 1235,
"text": "Functions and pseudocodes:"
},
{
"code": null,
"e": 1798,
"s": 1262,
"text": "Begin\n Function getBit(int val,int pos)\n singleBit->b = 0\n if(pos == 0)\n singleBit->b = val & 1\n else\n singleBit->b = ( val & (1 << pos ) ) >> pos\n return singleBit\n Function setBit(BitArr *bt,B *bit,int pos)\n bt->bVal[pos] = bit\n return bt\n Function getVal(BitArr *bArray)\n initialize val = 0\n initialize bVal = 0\n bVal = bArray->bVal[0]->b\n val= val|bVal\n for i = 1 to B_A_LENGTH-1\n bVal = bArray->bVal[i]->b\n bVal =bVal << i\n val=val | bVal\n return val\n done\nEnd."
},
{
"code": null,
"e": 1809,
"s": 1798,
"text": " Live Demo"
},
{
"code": null,
"e": 3057,
"s": 1809,
"text": "#include <iostream>\n#include <string>\nusing namespace std;\n#define B_A_LENGTH 4\ntypedef struct {\n unsigned int b : 1;\n} B;\nclass BitArr {\n private:\n B **bVal;\n public:\n BitArr() {\n bVal = new B* [B_A_LENGTH];\n }\n B *getBit(int val,int pos) {\n B *singleBit = new B;\n singleBit->b = 0;\n if(pos == 0) {\n singleBit->b = val & 1;\n } else {\n singleBit->b = ( val & (1 << pos ) ) >> pos;\n }\n return singleBit;\n }\n BitArr *setBit(BitArr *bt,B *bit,int pos) {\n bt->bVal[pos] = bit;\n return bt;\n }\n int getVal(BitArr *bArray) {\n int val = 0;\n unsigned int bVal = 0;\n bVal = bArray->bVal[0]->b;\n val |= bVal;\n for(int i = 1; i < B_A_LENGTH; i++) {\n bVal = bArray->bVal[i]->b;\n bVal <<= i;\n val |= bVal;\n }\n return val;\n }\n};\nint main() {\n int v;\n cout<<\"Enter 4 bit integer value (0 - 8): \";\n cin>>v;\n BitArr bt, *samplebt;\n samplebt = new BitArr;\n for (int i = 0; i < B_A_LENGTH; i++) {\n samplebt = bt.setBit(samplebt, bt.getBit(v, i), i);\n cout<<\"Bit of \"<<v<<\" at positon \"<<i<<\": \"<<\"\\n\"<<bt.getBit(v, i)->b<<endl;\n }\n cout<<\"The value is: \"<<bt.getVal(samplebt)<<endl;\n return 0;\n}"
},
{
"code": null,
"e": 3209,
"s": 3057,
"text": "Enter 4 bit integer value (0 - 8): 6Bit of 6 at positon 0:\n0\nBit of 6 at positon 1:\n1\nBit of 6 at positon 2:\n1\nBit of 6 at positon 3:\n0\nThe value is: 6"
}
]
|
C program to print the length of a String using %n format specifier - GeeksforGeeks | 11 Oct, 2019
Given string str. The task is to find the length of the string using %n format specifier
Examples:
Input: Geeks For Geeks
Output: 15
Input: Geeks
Output: 5
Appropach:
To find the length of string, we use special format specifier “%n” in printf function. In C printf(), %n is a special format specifier which instead of printing something causes printf() to load the variable pointed by the corresponding argument with a value equal to the number of characters that have been printed by printf() before the occurrence of %n.
Below is the implementation of the above approach:
// C program to print// the length of a String// using %n format specifier #include <stdio.h> // Driver codeint main(){ char str[100] = "Geeks for Geeks"; int len = 0; printf("%s%n", str, &len); printf(" = %d", len); return 0;}
Geeks for Geeks = 15
C Programs
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C Program to read contents of Whole File
Producer Consumer Problem in C
C program to find the length of a string
Exit codes in C/C++ with Examples
Difference between break and continue statement in C
Longest Common Subsequence | DP-4
Reverse a string in Java
Write a program to print all permutations of a given string
KMP Algorithm for Pattern Searching
C++ Data Types | [
{
"code": null,
"e": 24564,
"s": 24536,
"text": "\n11 Oct, 2019"
},
{
"code": null,
"e": 24653,
"s": 24564,
"text": "Given string str. The task is to find the length of the string using %n format specifier"
},
{
"code": null,
"e": 24663,
"s": 24653,
"text": "Examples:"
},
{
"code": null,
"e": 24723,
"s": 24663,
"text": "\nInput: Geeks For Geeks\nOutput: 15\n\nInput: Geeks\nOutput: 5\n"
},
{
"code": null,
"e": 24734,
"s": 24723,
"text": "Appropach:"
},
{
"code": null,
"e": 25091,
"s": 24734,
"text": "To find the length of string, we use special format specifier “%n” in printf function. In C printf(), %n is a special format specifier which instead of printing something causes printf() to load the variable pointed by the corresponding argument with a value equal to the number of characters that have been printed by printf() before the occurrence of %n."
},
{
"code": null,
"e": 25142,
"s": 25091,
"text": "Below is the implementation of the above approach:"
},
{
"code": "// C program to print// the length of a String// using %n format specifier #include <stdio.h> // Driver codeint main(){ char str[100] = \"Geeks for Geeks\"; int len = 0; printf(\"%s%n\", str, &len); printf(\" = %d\", len); return 0;}",
"e": 25391,
"s": 25142,
"text": null
},
{
"code": null,
"e": 25413,
"s": 25391,
"text": "Geeks for Geeks = 15\n"
},
{
"code": null,
"e": 25424,
"s": 25413,
"text": "C Programs"
},
{
"code": null,
"e": 25432,
"s": 25424,
"text": "Strings"
},
{
"code": null,
"e": 25440,
"s": 25432,
"text": "Strings"
},
{
"code": null,
"e": 25538,
"s": 25440,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25547,
"s": 25538,
"text": "Comments"
},
{
"code": null,
"e": 25560,
"s": 25547,
"text": "Old Comments"
},
{
"code": null,
"e": 25601,
"s": 25560,
"text": "C Program to read contents of Whole File"
},
{
"code": null,
"e": 25632,
"s": 25601,
"text": "Producer Consumer Problem in C"
},
{
"code": null,
"e": 25673,
"s": 25632,
"text": "C program to find the length of a string"
},
{
"code": null,
"e": 25707,
"s": 25673,
"text": "Exit codes in C/C++ with Examples"
},
{
"code": null,
"e": 25760,
"s": 25707,
"text": "Difference between break and continue statement in C"
},
{
"code": null,
"e": 25794,
"s": 25760,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 25819,
"s": 25794,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 25879,
"s": 25819,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 25915,
"s": 25879,
"text": "KMP Algorithm for Pattern Searching"
}
]
|
Custom Instance Segmentation Training With 7 Lines Of Code. | by Ayoola Olafenwa (she/her) | Towards Data Science | Image Segmentation is an important field in computer vision, it is applied in different fields of life. PixelLib is a library created to allow easy application of segmentation to real life problems. It supports instance segmentation of objects with Coco model. Segmentation with coco model is limited as you cannot perform segmentation beyond the 80 classes available in coco. It is now possible to train your custom objects’ segmentation model with PixelLib Library with just 7 Lines of Code.
Install PixelLib and its dependencies:
Install Tensorflow with:(PixelLib supports tensorflow 2.0 and above)
pip3 install tensorflow
Install imgaug with:
pip3 install imgaug
Install PixelLib with
pip3 install pixellib
If installed upgrade to the latest version using:
pip3 install pixellib — upgrade
STEP1:
Prepare your dataset:
Our goal is to create a model that can perform instance segmentation and object detection on butterflies and squirrels.
Collect images for the objects you want to detect and annotate your dataset for custom training. Labelme is the tool employed to perform polygon annotation of objects. Create a root directory or folder and within it create train and test folder. Separate the images required for training (a minimum of 300) and test. Put the images you want to use for training in the train folder and put the images you want to use for testing in the test folder. You will annotate both images in the train and test folder. Download Nature’s dataset used as a sample dataset in this article, unzip it to extract the images’’ folder. This dataset will serve as a guide for you to know how to organize your images. Ensure that the format of your dataset’s directory is not different from it. Nature is a dataset with two classes butterfly and squirrel. There are 300 images for each class for training and 100 images for each class for testing i.e 600 images for training and 200 images for validation. Nature is a dataset with 800 images.
Read this article to learn how to use labelme for annotating objects.
medium.com
Nature >>train>>>>>>>>>>>> image1.jpg image1.json image2.jpg image2.json >>test>>>>>>>>>>>> img1.jpg img1.json img2.jpg img2.json
Sample of folder directory after annotation.
Note: PixelLib supports annotation with Labelme. If you make use of another annotation tool it will not be compatible with the library.
STEP 2:
Visualize Dataset
Visualize a sample image before training to confirm that the masks and bounding boxes are well generated.
import pixellibfrom pixellib.custom_train import instance_custom_trainingvis_img = instance_custom_training()
We imported pixellib, from pixellib we imported the class instance_custom_training and created an instance of the class.
vis_img.load_dataset("Nature”)
We loaded the dataset using load_dataset function. PixelLib requires polygon annotations to be in coco format. When you call the load_dataset function, the individual json files in the train and test folder will be converted into a single train.json and test.json respectively. The train and test json files will be located in the root directory as the train and test folder. The new folder directory will now look like this:
Nature >>>>>>>>train>>>>>>>>>>>>>>> image1.jpg train.json image1.json image2.jpg image2.json >>>>>>>>>>>test>>>>>>>>>>>>>>> img1.jpg test.json img1.json img2.jpg img2.json
Inside the load_dataset function annotations are extracted from the jsons’s files. Masks are generated from the polygon points of the annotations and bounding boxes are generated from the masks. The smallest box that encapsulates all the pixels of a mask is used as a bounding box.
vis_img.visualize_sample()
When you call this function, it shows a sample image with a mask and bounding box.
Great! the dataset is fit for training, the load_dataset function successfully generates mask and bounding box for each object in the image. Random colors are generated for the masks in HSV space and then converted to RGB.
FINAL STEP:
Train a custom model using your dataset
This is the code for performing training. In just seven lines of code, you train your dataset.
train_maskrcnn.modelConfig(network_backbone = "resnet101", num_classes= 2, batch_size = 4)
We called the function modelConfig, i.e model’s configuration. It takes the following parameters:
network_backbone: This is the CNN network used as a feature extractor for mask-rcnn. The feature extractor used is resnet101.
num_classes: We set the number of classes to the categories of objects in the dataset. In this case, we have two classes(butterfly and squirrel) in nature’s dataset.
batch_size: This is the batch size for training the model. It is set to 4.
train_maskrcnn.load_pretrained_model("mask_rcnn_coco.h5")train_maskrcnn.load_dataset(“Nature”)
We are going to employ the technique of transfer learning for training the model. Coco model has been trained on 8O categories of objects, it has learnt a lot of features that will help in training the model. We called the function load_pretrained_model function to load the mask-rcnn coco model. We loaded the dataset using load_dataset function.
Download coco model from here.
train_maskrcnn.train_model(num_epochs = 300, augmentation=True,path_trained_models = “mask_rcnn_models”)
Finally, we called the train function for training mask r-cnn model. We called train_model function. The function took the following parameters:
num_epochs:The number of epochs required for training the model. It is set to 300.
augmentation: Data augmentation is applied on the dataset. This is because we want the model to learn different representations of the objects.
path_trained_models: This is the path to save the trained models during training. Models with the lowest validation losses are saved.
Using resnet101 as network backbone For Mask R-CNN modelTrain 600 images Validate 200 images Applying augmentation on dataset Checkpoint Path: mask_rcnn_modelsSelecting layers to trainEpoch 1/200100/100 - 164s - loss: 2.2184 - rpn_class_loss: 0.0174 - rpn_bbox_loss: 0.8019 - mrcnn_class_loss: 0.1655 - mrcnn_bbox_loss: 0.7274 - mrcnn_mask_loss: 0.5062 - val_loss: 2.5806 - val_rpn_class_loss: 0.0221 - val_rpn_bbox_loss: 1.4358 - val_mrcnn_class_loss: 0.1574 - val_mrcnn_bbox_loss: 0.6080 - val_mrcnn_mask_loss: 0.3572Epoch 2/200100/100 - 150s - loss: 1.4641 - rpn_class_loss: 0.0126 - rpn_bbox_loss: 0.5438 - mrcnn_class_loss: 0.1510 - mrcnn_bbox_loss: 0.4177 - mrcnn_mask_loss: 0.3390 - val_loss: 1.2217 - val_rpn_class_loss: 0.0115 - val_rpn_bbox_loss: 0.4896 - val_mrcnn_class_loss: 0.1542 - val_mrcnn_bbox_loss: 0.3111 - val_mrcnn_mask_loss: 0.2554Epoch 3/200100/100 - 145s - loss: 1.0980 - rpn_class_loss: 0.0118 - rpn_bbox_loss: 0.4122 - mrcnn_class_loss: 0.1271 - mrcnn_bbox_loss: 0.2860 - mrcnn_mask_loss: 0.2609 - val_loss: 1.0708 - val_rpn_class_loss: 0.0149 - val_rpn_bbox_loss: 0.3645 - val_mrcnn_class_loss: 0.1360 - val_mrcnn_bbox_loss: 0.3059 - val_mrcnn_mask_loss: 0.2493
This is the training log. It shows the network backbone used for training mask-rcnn which is resnet101, the number of images used for training and number of images used for validation. In the path_to_trained models’ directory, the models are saved based on decrease in validation loss, and typical model name will appear like this: mask_rcnn_model_25–0.55678, it is saved with its epoch number and its corresponding validation loss.
Network Backbones:
There are two network backbones for training mask-rcnn
Resnet101
Resnet50
Google colab: Google Colab provides a single 12GB NVIDIA Tesla K80 GPU that can be used up to 12 hours continuously.
Using Resnet101: Training Mask-RCNN consumes a lot of memory. On google colab using resnet101 as network backbone, you will be able to train with a batchsize of 4. The default network backbone is resnet101. Resnet101 is used as a default backbone because it appears to reach a lower validation loss during training faster than resnet50. It also works better for a dataset with multiple classes and much more images.
Using Resnet50: The advantage with resnet50 is that it consumes lesser memory. Thus, you can use a batch_size of 6 or 8 on google colab depending on how colab randomly allocates GPU.
The modified code supporting resnet50 will be like this.
Full code
The main differences from the original code is that in the model’s configuration function, we set network_backbone to be resnet50 and changed the batch size to 6.
The only difference in the training log is this:
Using resnet50 as network backbone For Mask R-CNN model
It shows that we are using resnet50 for training.
Note: The batch_sizes given are samples used for google colab. If you are using a less powerful GPU, reduce your batch size. For example, for a PC with a 4G RAM GPU, you should use a batch size of 1 for both resnet50 or resnet101. I used a batch size of 1 to train my model on my PC’s GPU, trained for less than 100 epochs and it produced a validation loss of 0.263. This is favourable because my dataset is not large. A PC with a more powerful GPU should be able to use a batch size of 2. If you have a large dataset with more classes and much more images, you can use google colab where you have free access to GPU. Most importantly, try to use a more powerful GPU and train for more epochs to produce a custom model that will perform efficiently across multiple classes.
Achieve better results by training with much more images. 300 images for each each class is recommended to be the minimum requirement for training.
Model Evaluation
When we are done with training, we should evaluate models with lowest validation losses. Model evaluation is used to access the performance of the trained model on the test dataset. Download the trained model from here.
output
mask_rcnn_models/Nature_model_resnet101.h5 evaluation using iou_threshold 0.5 is 0.890000
The mAP(Mean Avearge Precision) of the model is 0.89.
You can evaluate multiple models at once, what you just need is to pass in the folder directory of the models.
Output log
mask_rcnn_models\Nature_model_resnet101.h5 evaluation using iou_threshold 0.5 is 0.890000mask_rcnn_models\mask_rcnn_model_055.h5 evaluation using iou_threshold 0.5 is 0.867500mask_rcnn_models\mask_rcnn_model_058.h5 evaluation using iou_threshold 0.5 is 0.8507500
Evaluation with Resnet50
Note: Change the network_backbone to resnet50 if you are evaluating a resnet50 model.
Inference with a custom model
We have trained and evaluated the model. The next step is to see the performance of the model on unknown images.
We are going to test the model on the classes we have trained it on.
Sample1.jpg
import pixellibfrom pixellib.instance import custom_segmentation segment_image =custom_segmentation()segment_image.inferConfig(num_classes= 2, class_names= ["BG", "butterfly", "squirrel"])
We imported the class custom_segmentation, the class for performing inference and created an instance of the class. We called the model configuration’s function and introduced an extra parameter class_names.
class_names= ["BG", "butterfly", "squirrel"])
class_names:It is a list containing the names of classes the model is trained with. “BG” refers to the background of the image. It is the first class and must be available along the names of the classes.
Note: If you have multiple classes and you are confused of how to arrange the classes’s names according to their class ids, in your test.json in the dataset’s folder, check the categories’ list.
{"images": [{"height": 205,"width": 246,"id": 1,"file_name": "C:\\Users\\olafe\\Documents\\Ayoola\\PIXELLIB\\Final\\Nature\\test\\butterfly (1).png"},],"categories": [{"supercategory": "butterfly","id": 1,"name": "butterfly"},{"supercategory": "squirrel","id": 2,"name": "squirrel"}],
You can observe from the sample of the directory of test.json above that after the images’ list in the test.json is object categories’ list. The classes’ names are there with their corresponding class ids. Butterfly has a class id 1 and squirrel has a class id 2. Remember, the first id “0” is kept in reserve for the background.
segment_image.load_model("mask_rcnn_model/Nature_model_resnet101.h5)segment_image.segmentImage("sample1.jpg", show_bboxes=True, output_image_name="sample_out.jpg")
The custom model is loaded and we called the function to segment the image.
When parameter show_bboxes is set to True, we will be able to perform instance segmentation with object detection.
test_maskrcnn.segmentImage(“sample1.jpg”,show_bboxes = False, output_image_name=”sample_out.jpg”)
When show_bboxes is set to False, we obtain only segmentation masks.
Sample2.jpg
test_maskrcnn.segmentImage(“sample2.jpg”,show_bboxes = True, output_image_name=”sample_out.jpg”)
WOW! We have successfully trained a custom model for performing instance segmentation and object detection on butterflies and squirrels.
sample_video1
We want to perform segmentation on the butterflies in this video.
test_video.process_video("video.mp4", show_bboxes = True, output_video_name="video_out.mp4", frames_per_second=15)
The function process_video is called to perform segmentation on objects in a video.
It takes the following parameters:-
video_path: This is the path to the video file we want to segment.
frames_per_second: This is the parameter used to set the number of frames per second for the saved video file. In this case, it is set to 15 i.e the saved video file will have 15 frames per second.
output_video_name: This is the name of the saved segmented video. The output video will be saved in your current working directory.
Output_video
A sample of another segmented video with our custom model.
You can perform live camera segmentation with your custom model making use of this code:
You will replace the process_video funtion with process_camera function.In the function, we replaced the video’s filepath to capture i.e we are processing a stream of frames captured by the camera instead of a video file. We added extra parameters for the purpose of showing the camera frames:
show_frames: This parameter handles the showing of segmented camera’s frames.
frame_name: This is the name given to the shown camera’s frame.
Visit Google colab’s notebook set up for training a custom dataset.
colab.research.google.com
Visit Pixellib’s Official Github Repository
Visit Pixellib’s Official Documentation
Reach to me via:
Email: [email protected]
Linkedin: Ayoola Olafenwa
Twitter: @AyoolaOlafenwa
Facebook: Ayoola Olafenwa | [
{
"code": null,
"e": 665,
"s": 171,
"text": "Image Segmentation is an important field in computer vision, it is applied in different fields of life. PixelLib is a library created to allow easy application of segmentation to real life problems. It supports instance segmentation of objects with Coco model. Segmentation with coco model is limited as you cannot perform segmentation beyond the 80 classes available in coco. It is now possible to train your custom objects’ segmentation model with PixelLib Library with just 7 Lines of Code."
},
{
"code": null,
"e": 704,
"s": 665,
"text": "Install PixelLib and its dependencies:"
},
{
"code": null,
"e": 773,
"s": 704,
"text": "Install Tensorflow with:(PixelLib supports tensorflow 2.0 and above)"
},
{
"code": null,
"e": 797,
"s": 773,
"text": "pip3 install tensorflow"
},
{
"code": null,
"e": 818,
"s": 797,
"text": "Install imgaug with:"
},
{
"code": null,
"e": 838,
"s": 818,
"text": "pip3 install imgaug"
},
{
"code": null,
"e": 860,
"s": 838,
"text": "Install PixelLib with"
},
{
"code": null,
"e": 882,
"s": 860,
"text": "pip3 install pixellib"
},
{
"code": null,
"e": 932,
"s": 882,
"text": "If installed upgrade to the latest version using:"
},
{
"code": null,
"e": 964,
"s": 932,
"text": "pip3 install pixellib — upgrade"
},
{
"code": null,
"e": 971,
"s": 964,
"text": "STEP1:"
},
{
"code": null,
"e": 993,
"s": 971,
"text": "Prepare your dataset:"
},
{
"code": null,
"e": 1113,
"s": 993,
"text": "Our goal is to create a model that can perform instance segmentation and object detection on butterflies and squirrels."
},
{
"code": null,
"e": 2135,
"s": 1113,
"text": "Collect images for the objects you want to detect and annotate your dataset for custom training. Labelme is the tool employed to perform polygon annotation of objects. Create a root directory or folder and within it create train and test folder. Separate the images required for training (a minimum of 300) and test. Put the images you want to use for training in the train folder and put the images you want to use for testing in the test folder. You will annotate both images in the train and test folder. Download Nature’s dataset used as a sample dataset in this article, unzip it to extract the images’’ folder. This dataset will serve as a guide for you to know how to organize your images. Ensure that the format of your dataset’s directory is not different from it. Nature is a dataset with two classes butterfly and squirrel. There are 300 images for each class for training and 100 images for each class for testing i.e 600 images for training and 200 images for validation. Nature is a dataset with 800 images."
},
{
"code": null,
"e": 2205,
"s": 2135,
"text": "Read this article to learn how to use labelme for annotating objects."
},
{
"code": null,
"e": 2216,
"s": 2205,
"text": "medium.com"
},
{
"code": null,
"e": 2518,
"s": 2216,
"text": "Nature >>train>>>>>>>>>>>> image1.jpg image1.json image2.jpg image2.json >>test>>>>>>>>>>>> img1.jpg img1.json img2.jpg img2.json "
},
{
"code": null,
"e": 2563,
"s": 2518,
"text": "Sample of folder directory after annotation."
},
{
"code": null,
"e": 2699,
"s": 2563,
"text": "Note: PixelLib supports annotation with Labelme. If you make use of another annotation tool it will not be compatible with the library."
},
{
"code": null,
"e": 2707,
"s": 2699,
"text": "STEP 2:"
},
{
"code": null,
"e": 2725,
"s": 2707,
"text": "Visualize Dataset"
},
{
"code": null,
"e": 2831,
"s": 2725,
"text": "Visualize a sample image before training to confirm that the masks and bounding boxes are well generated."
},
{
"code": null,
"e": 2941,
"s": 2831,
"text": "import pixellibfrom pixellib.custom_train import instance_custom_trainingvis_img = instance_custom_training()"
},
{
"code": null,
"e": 3062,
"s": 2941,
"text": "We imported pixellib, from pixellib we imported the class instance_custom_training and created an instance of the class."
},
{
"code": null,
"e": 3093,
"s": 3062,
"text": "vis_img.load_dataset(\"Nature”)"
},
{
"code": null,
"e": 3519,
"s": 3093,
"text": "We loaded the dataset using load_dataset function. PixelLib requires polygon annotations to be in coco format. When you call the load_dataset function, the individual json files in the train and test folder will be converted into a single train.json and test.json respectively. The train and test json files will be located in the root directory as the train and test folder. The new folder directory will now look like this:"
},
{
"code": null,
"e": 3892,
"s": 3519,
"text": "Nature >>>>>>>>train>>>>>>>>>>>>>>> image1.jpg train.json image1.json image2.jpg image2.json >>>>>>>>>>>test>>>>>>>>>>>>>>> img1.jpg test.json img1.json img2.jpg img2.json"
},
{
"code": null,
"e": 4174,
"s": 3892,
"text": "Inside the load_dataset function annotations are extracted from the jsons’s files. Masks are generated from the polygon points of the annotations and bounding boxes are generated from the masks. The smallest box that encapsulates all the pixels of a mask is used as a bounding box."
},
{
"code": null,
"e": 4201,
"s": 4174,
"text": "vis_img.visualize_sample()"
},
{
"code": null,
"e": 4284,
"s": 4201,
"text": "When you call this function, it shows a sample image with a mask and bounding box."
},
{
"code": null,
"e": 4507,
"s": 4284,
"text": "Great! the dataset is fit for training, the load_dataset function successfully generates mask and bounding box for each object in the image. Random colors are generated for the masks in HSV space and then converted to RGB."
},
{
"code": null,
"e": 4519,
"s": 4507,
"text": "FINAL STEP:"
},
{
"code": null,
"e": 4559,
"s": 4519,
"text": "Train a custom model using your dataset"
},
{
"code": null,
"e": 4654,
"s": 4559,
"text": "This is the code for performing training. In just seven lines of code, you train your dataset."
},
{
"code": null,
"e": 4768,
"s": 4654,
"text": "train_maskrcnn.modelConfig(network_backbone = \"resnet101\", num_classes= 2, batch_size = 4) "
},
{
"code": null,
"e": 4866,
"s": 4768,
"text": "We called the function modelConfig, i.e model’s configuration. It takes the following parameters:"
},
{
"code": null,
"e": 4992,
"s": 4866,
"text": "network_backbone: This is the CNN network used as a feature extractor for mask-rcnn. The feature extractor used is resnet101."
},
{
"code": null,
"e": 5158,
"s": 4992,
"text": "num_classes: We set the number of classes to the categories of objects in the dataset. In this case, we have two classes(butterfly and squirrel) in nature’s dataset."
},
{
"code": null,
"e": 5233,
"s": 5158,
"text": "batch_size: This is the batch size for training the model. It is set to 4."
},
{
"code": null,
"e": 5328,
"s": 5233,
"text": "train_maskrcnn.load_pretrained_model(\"mask_rcnn_coco.h5\")train_maskrcnn.load_dataset(“Nature”)"
},
{
"code": null,
"e": 5676,
"s": 5328,
"text": "We are going to employ the technique of transfer learning for training the model. Coco model has been trained on 8O categories of objects, it has learnt a lot of features that will help in training the model. We called the function load_pretrained_model function to load the mask-rcnn coco model. We loaded the dataset using load_dataset function."
},
{
"code": null,
"e": 5707,
"s": 5676,
"text": "Download coco model from here."
},
{
"code": null,
"e": 5812,
"s": 5707,
"text": "train_maskrcnn.train_model(num_epochs = 300, augmentation=True,path_trained_models = “mask_rcnn_models”)"
},
{
"code": null,
"e": 5957,
"s": 5812,
"text": "Finally, we called the train function for training mask r-cnn model. We called train_model function. The function took the following parameters:"
},
{
"code": null,
"e": 6040,
"s": 5957,
"text": "num_epochs:The number of epochs required for training the model. It is set to 300."
},
{
"code": null,
"e": 6184,
"s": 6040,
"text": "augmentation: Data augmentation is applied on the dataset. This is because we want the model to learn different representations of the objects."
},
{
"code": null,
"e": 6318,
"s": 6184,
"text": "path_trained_models: This is the path to save the trained models during training. Models with the lowest validation losses are saved."
},
{
"code": null,
"e": 7508,
"s": 6318,
"text": "Using resnet101 as network backbone For Mask R-CNN modelTrain 600 images Validate 200 images Applying augmentation on dataset Checkpoint Path: mask_rcnn_modelsSelecting layers to trainEpoch 1/200100/100 - 164s - loss: 2.2184 - rpn_class_loss: 0.0174 - rpn_bbox_loss: 0.8019 - mrcnn_class_loss: 0.1655 - mrcnn_bbox_loss: 0.7274 - mrcnn_mask_loss: 0.5062 - val_loss: 2.5806 - val_rpn_class_loss: 0.0221 - val_rpn_bbox_loss: 1.4358 - val_mrcnn_class_loss: 0.1574 - val_mrcnn_bbox_loss: 0.6080 - val_mrcnn_mask_loss: 0.3572Epoch 2/200100/100 - 150s - loss: 1.4641 - rpn_class_loss: 0.0126 - rpn_bbox_loss: 0.5438 - mrcnn_class_loss: 0.1510 - mrcnn_bbox_loss: 0.4177 - mrcnn_mask_loss: 0.3390 - val_loss: 1.2217 - val_rpn_class_loss: 0.0115 - val_rpn_bbox_loss: 0.4896 - val_mrcnn_class_loss: 0.1542 - val_mrcnn_bbox_loss: 0.3111 - val_mrcnn_mask_loss: 0.2554Epoch 3/200100/100 - 145s - loss: 1.0980 - rpn_class_loss: 0.0118 - rpn_bbox_loss: 0.4122 - mrcnn_class_loss: 0.1271 - mrcnn_bbox_loss: 0.2860 - mrcnn_mask_loss: 0.2609 - val_loss: 1.0708 - val_rpn_class_loss: 0.0149 - val_rpn_bbox_loss: 0.3645 - val_mrcnn_class_loss: 0.1360 - val_mrcnn_bbox_loss: 0.3059 - val_mrcnn_mask_loss: 0.2493"
},
{
"code": null,
"e": 7941,
"s": 7508,
"text": "This is the training log. It shows the network backbone used for training mask-rcnn which is resnet101, the number of images used for training and number of images used for validation. In the path_to_trained models’ directory, the models are saved based on decrease in validation loss, and typical model name will appear like this: mask_rcnn_model_25–0.55678, it is saved with its epoch number and its corresponding validation loss."
},
{
"code": null,
"e": 7960,
"s": 7941,
"text": "Network Backbones:"
},
{
"code": null,
"e": 8015,
"s": 7960,
"text": "There are two network backbones for training mask-rcnn"
},
{
"code": null,
"e": 8025,
"s": 8015,
"text": "Resnet101"
},
{
"code": null,
"e": 8034,
"s": 8025,
"text": "Resnet50"
},
{
"code": null,
"e": 8151,
"s": 8034,
"text": "Google colab: Google Colab provides a single 12GB NVIDIA Tesla K80 GPU that can be used up to 12 hours continuously."
},
{
"code": null,
"e": 8567,
"s": 8151,
"text": "Using Resnet101: Training Mask-RCNN consumes a lot of memory. On google colab using resnet101 as network backbone, you will be able to train with a batchsize of 4. The default network backbone is resnet101. Resnet101 is used as a default backbone because it appears to reach a lower validation loss during training faster than resnet50. It also works better for a dataset with multiple classes and much more images."
},
{
"code": null,
"e": 8750,
"s": 8567,
"text": "Using Resnet50: The advantage with resnet50 is that it consumes lesser memory. Thus, you can use a batch_size of 6 or 8 on google colab depending on how colab randomly allocates GPU."
},
{
"code": null,
"e": 8807,
"s": 8750,
"text": "The modified code supporting resnet50 will be like this."
},
{
"code": null,
"e": 8817,
"s": 8807,
"text": "Full code"
},
{
"code": null,
"e": 8980,
"s": 8817,
"text": "The main differences from the original code is that in the model’s configuration function, we set network_backbone to be resnet50 and changed the batch size to 6."
},
{
"code": null,
"e": 9029,
"s": 8980,
"text": "The only difference in the training log is this:"
},
{
"code": null,
"e": 9085,
"s": 9029,
"text": "Using resnet50 as network backbone For Mask R-CNN model"
},
{
"code": null,
"e": 9135,
"s": 9085,
"text": "It shows that we are using resnet50 for training."
},
{
"code": null,
"e": 9909,
"s": 9135,
"text": "Note: The batch_sizes given are samples used for google colab. If you are using a less powerful GPU, reduce your batch size. For example, for a PC with a 4G RAM GPU, you should use a batch size of 1 for both resnet50 or resnet101. I used a batch size of 1 to train my model on my PC’s GPU, trained for less than 100 epochs and it produced a validation loss of 0.263. This is favourable because my dataset is not large. A PC with a more powerful GPU should be able to use a batch size of 2. If you have a large dataset with more classes and much more images, you can use google colab where you have free access to GPU. Most importantly, try to use a more powerful GPU and train for more epochs to produce a custom model that will perform efficiently across multiple classes."
},
{
"code": null,
"e": 10057,
"s": 9909,
"text": "Achieve better results by training with much more images. 300 images for each each class is recommended to be the minimum requirement for training."
},
{
"code": null,
"e": 10074,
"s": 10057,
"text": "Model Evaluation"
},
{
"code": null,
"e": 10294,
"s": 10074,
"text": "When we are done with training, we should evaluate models with lowest validation losses. Model evaluation is used to access the performance of the trained model on the test dataset. Download the trained model from here."
},
{
"code": null,
"e": 10301,
"s": 10294,
"text": "output"
},
{
"code": null,
"e": 10391,
"s": 10301,
"text": "mask_rcnn_models/Nature_model_resnet101.h5 evaluation using iou_threshold 0.5 is 0.890000"
},
{
"code": null,
"e": 10445,
"s": 10391,
"text": "The mAP(Mean Avearge Precision) of the model is 0.89."
},
{
"code": null,
"e": 10556,
"s": 10445,
"text": "You can evaluate multiple models at once, what you just need is to pass in the folder directory of the models."
},
{
"code": null,
"e": 10567,
"s": 10556,
"text": "Output log"
},
{
"code": null,
"e": 10830,
"s": 10567,
"text": "mask_rcnn_models\\Nature_model_resnet101.h5 evaluation using iou_threshold 0.5 is 0.890000mask_rcnn_models\\mask_rcnn_model_055.h5 evaluation using iou_threshold 0.5 is 0.867500mask_rcnn_models\\mask_rcnn_model_058.h5 evaluation using iou_threshold 0.5 is 0.8507500"
},
{
"code": null,
"e": 10855,
"s": 10830,
"text": "Evaluation with Resnet50"
},
{
"code": null,
"e": 10941,
"s": 10855,
"text": "Note: Change the network_backbone to resnet50 if you are evaluating a resnet50 model."
},
{
"code": null,
"e": 10971,
"s": 10941,
"text": "Inference with a custom model"
},
{
"code": null,
"e": 11084,
"s": 10971,
"text": "We have trained and evaluated the model. The next step is to see the performance of the model on unknown images."
},
{
"code": null,
"e": 11153,
"s": 11084,
"text": "We are going to test the model on the classes we have trained it on."
},
{
"code": null,
"e": 11165,
"s": 11153,
"text": "Sample1.jpg"
},
{
"code": null,
"e": 11354,
"s": 11165,
"text": "import pixellibfrom pixellib.instance import custom_segmentation segment_image =custom_segmentation()segment_image.inferConfig(num_classes= 2, class_names= [\"BG\", \"butterfly\", \"squirrel\"])"
},
{
"code": null,
"e": 11562,
"s": 11354,
"text": "We imported the class custom_segmentation, the class for performing inference and created an instance of the class. We called the model configuration’s function and introduced an extra parameter class_names."
},
{
"code": null,
"e": 11608,
"s": 11562,
"text": "class_names= [\"BG\", \"butterfly\", \"squirrel\"])"
},
{
"code": null,
"e": 11812,
"s": 11608,
"text": "class_names:It is a list containing the names of classes the model is trained with. “BG” refers to the background of the image. It is the first class and must be available along the names of the classes."
},
{
"code": null,
"e": 12007,
"s": 11812,
"text": "Note: If you have multiple classes and you are confused of how to arrange the classes’s names according to their class ids, in your test.json in the dataset’s folder, check the categories’ list."
},
{
"code": null,
"e": 12292,
"s": 12007,
"text": "{\"images\": [{\"height\": 205,\"width\": 246,\"id\": 1,\"file_name\": \"C:\\\\Users\\\\olafe\\\\Documents\\\\Ayoola\\\\PIXELLIB\\\\Final\\\\Nature\\\\test\\\\butterfly (1).png\"},],\"categories\": [{\"supercategory\": \"butterfly\",\"id\": 1,\"name\": \"butterfly\"},{\"supercategory\": \"squirrel\",\"id\": 2,\"name\": \"squirrel\"}],"
},
{
"code": null,
"e": 12622,
"s": 12292,
"text": "You can observe from the sample of the directory of test.json above that after the images’ list in the test.json is object categories’ list. The classes’ names are there with their corresponding class ids. Butterfly has a class id 1 and squirrel has a class id 2. Remember, the first id “0” is kept in reserve for the background."
},
{
"code": null,
"e": 12786,
"s": 12622,
"text": "segment_image.load_model(\"mask_rcnn_model/Nature_model_resnet101.h5)segment_image.segmentImage(\"sample1.jpg\", show_bboxes=True, output_image_name=\"sample_out.jpg\")"
},
{
"code": null,
"e": 12862,
"s": 12786,
"text": "The custom model is loaded and we called the function to segment the image."
},
{
"code": null,
"e": 12977,
"s": 12862,
"text": "When parameter show_bboxes is set to True, we will be able to perform instance segmentation with object detection."
},
{
"code": null,
"e": 13075,
"s": 12977,
"text": "test_maskrcnn.segmentImage(“sample1.jpg”,show_bboxes = False, output_image_name=”sample_out.jpg”)"
},
{
"code": null,
"e": 13144,
"s": 13075,
"text": "When show_bboxes is set to False, we obtain only segmentation masks."
},
{
"code": null,
"e": 13156,
"s": 13144,
"text": "Sample2.jpg"
},
{
"code": null,
"e": 13253,
"s": 13156,
"text": "test_maskrcnn.segmentImage(“sample2.jpg”,show_bboxes = True, output_image_name=”sample_out.jpg”)"
},
{
"code": null,
"e": 13390,
"s": 13253,
"text": "WOW! We have successfully trained a custom model for performing instance segmentation and object detection on butterflies and squirrels."
},
{
"code": null,
"e": 13404,
"s": 13390,
"text": "sample_video1"
},
{
"code": null,
"e": 13470,
"s": 13404,
"text": "We want to perform segmentation on the butterflies in this video."
},
{
"code": null,
"e": 13586,
"s": 13470,
"text": "test_video.process_video(\"video.mp4\", show_bboxes = True, output_video_name=\"video_out.mp4\", frames_per_second=15)"
},
{
"code": null,
"e": 13670,
"s": 13586,
"text": "The function process_video is called to perform segmentation on objects in a video."
},
{
"code": null,
"e": 13706,
"s": 13670,
"text": "It takes the following parameters:-"
},
{
"code": null,
"e": 13773,
"s": 13706,
"text": "video_path: This is the path to the video file we want to segment."
},
{
"code": null,
"e": 13971,
"s": 13773,
"text": "frames_per_second: This is the parameter used to set the number of frames per second for the saved video file. In this case, it is set to 15 i.e the saved video file will have 15 frames per second."
},
{
"code": null,
"e": 14103,
"s": 13971,
"text": "output_video_name: This is the name of the saved segmented video. The output video will be saved in your current working directory."
},
{
"code": null,
"e": 14116,
"s": 14103,
"text": "Output_video"
},
{
"code": null,
"e": 14175,
"s": 14116,
"text": "A sample of another segmented video with our custom model."
},
{
"code": null,
"e": 14264,
"s": 14175,
"text": "You can perform live camera segmentation with your custom model making use of this code:"
},
{
"code": null,
"e": 14558,
"s": 14264,
"text": "You will replace the process_video funtion with process_camera function.In the function, we replaced the video’s filepath to capture i.e we are processing a stream of frames captured by the camera instead of a video file. We added extra parameters for the purpose of showing the camera frames:"
},
{
"code": null,
"e": 14636,
"s": 14558,
"text": "show_frames: This parameter handles the showing of segmented camera’s frames."
},
{
"code": null,
"e": 14700,
"s": 14636,
"text": "frame_name: This is the name given to the shown camera’s frame."
},
{
"code": null,
"e": 14768,
"s": 14700,
"text": "Visit Google colab’s notebook set up for training a custom dataset."
},
{
"code": null,
"e": 14794,
"s": 14768,
"text": "colab.research.google.com"
},
{
"code": null,
"e": 14838,
"s": 14794,
"text": "Visit Pixellib’s Official Github Repository"
},
{
"code": null,
"e": 14878,
"s": 14838,
"text": "Visit Pixellib’s Official Documentation"
},
{
"code": null,
"e": 14895,
"s": 14878,
"text": "Reach to me via:"
},
{
"code": null,
"e": 14927,
"s": 14895,
"text": "Email: [email protected]"
},
{
"code": null,
"e": 14953,
"s": 14927,
"text": "Linkedin: Ayoola Olafenwa"
},
{
"code": null,
"e": 14978,
"s": 14953,
"text": "Twitter: @AyoolaOlafenwa"
}
]
|
Java Examples - Split PDF into Many | How to split a PDF in to many using Java.
Following is an example program to split a PDF in to many using Java.
import org.apache.pdfbox.multipdf.Splitter;
import org.apache.pdfbox.pdmodel.PDDocument;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Iterator;
public class SplittingPDF {
public static void main(String[] args) throws IOException {
//Loading an existing PDF document
File file = new File("C:/pdfBox/splitpdf_IP.pdf");
PDDocument doc = PDDocument.load(file);
//Instantiating Splitter class
Splitter splitter = new Splitter();
//splitting the pages of a PDF document
List<PDDocument> Pages = splitter.split(doc);
//Creating an iterator
Iterator<PDDocument> iterator = Pages.listIterator();
//Saving each page as an individual document
int i = 1;
while(iterator.hasNext()){
PDDocument pd = iterator.next();
pd.save("C:/pdfBox/splitOP"+ i++ +".pdf");
}
System.out.println("PDF splitted");
}
}
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2110,
"s": 2068,
"text": "How to split a PDF in to many using Java."
},
{
"code": null,
"e": 2180,
"s": 2110,
"text": "Following is an example program to split a PDF in to many using Java."
},
{
"code": null,
"e": 3199,
"s": 2180,
"text": "import org.apache.pdfbox.multipdf.Splitter; \nimport org.apache.pdfbox.pdmodel.PDDocument; \n\nimport java.io.File; \nimport java.io.IOException; \n\nimport java.util.List; \nimport java.util.Iterator; \n\npublic class SplittingPDF { \n public static void main(String[] args) throws IOException { \n \n //Loading an existing PDF document \n File file = new File(\"C:/pdfBox/splitpdf_IP.pdf\"); \n PDDocument doc = PDDocument.load(file); \n\n //Instantiating Splitter class \n Splitter splitter = new Splitter(); \n \n //splitting the pages of a PDF document \n List<PDDocument> Pages = splitter.split(doc); \n\n //Creating an iterator \n Iterator<PDDocument> iterator = Pages.listIterator(); \n\n //Saving each page as an individual document \n int i = 1; \n \n while(iterator.hasNext()){ \n PDDocument pd = iterator.next(); \n pd.save(\"C:/pdfBox/splitOP\"+ i++ +\".pdf\"); \n } \n System.out.println(\"PDF splitted\"); \n } \n}"
},
{
"code": null,
"e": 3208,
"s": 3201,
"text": " Print"
},
{
"code": null,
"e": 3219,
"s": 3208,
"text": " Add Notes"
}
]
|
eXtreme Deep Factorization Machine(xDeepFM) | by Abhishek Sharma | Towards Data Science | We are living in times where we are spoilt for choice. Whether it is food, music or entertainment the amount of options that we have is simply mind-boggling. But thanks to the recommendation engines that fuel these apps/sites these alternatives are provided to us in a ranked list. In this blog, we will be discussing a new recommendation algorithm called Extreme Deep Factorisation Machines (xDeepFM).
This blog is organized as follows:
Current recommendation systems in productionIntroducing xDeepFMIntroducing CIN (the core pillar of xDeepFM) 3.1 CIN characteristics 3.2 CIN hidden layers 3.3 Similarity with RNN 3.4 Similarity with CNN 3.5 Pooling and concatenation of hidden layers 3.6 Output of xdeepfmCIN complexity 4.1 Space Complexity 4.2 Time Complexity
Current recommendation systems in production
Introducing xDeepFM
Introducing CIN (the core pillar of xDeepFM) 3.1 CIN characteristics 3.2 CIN hidden layers 3.3 Similarity with RNN 3.4 Similarity with CNN 3.5 Pooling and concatenation of hidden layers 3.6 Output of xdeepfm
CIN complexity 4.1 Space Complexity 4.2 Time Complexity
5. Coded Example using deepCTR library
6. References
7. Summary
Let’s start!!
The current recommendation landscape is dominated by FM/DNN based models. But some good hybrid architectures which fuse FM and DNN based systems are also coming up.
1. Factorization Machine (FM) based approach
+ve: Learns pattern on combinatorial features automatically
+ve: Generalize well to unseen features
-ve: Tries to capture all feature interactions which results in learning of useless interactions. This might introduce noise.
Examples: the most trusted workhorse of the recommendation domain
2. Deep Neural Network ( DNN ) based approach
+ve: Learns sophisticated and selective feature interactions
-ve: Feature interactions are modeled at an elemental level. One hot encoding is used for categorical variables to represent them in dimension D. This will be fed into a fully connected layer. This is in stark contrast to FM based approaches which models feature interactions at a vector level (User vector * Item Vector).
Example: DNN part of Neural Collaborative Filtering(NCF), DNN for Youtube recommendations
3. DNN + FM (Hybrid) approach
+ve: Learns both low/high order feature interactions
Examples: Wide & Deep Network(Youtube), Neural Collaborative Filtering(NCF), Deep and Cross network(DCN), Deep Factorisation Machine (DeepFM) and eXtreme Deep Factorisation Machine (xDeepFM)
You can look into this post to get a brief overview of Neural Collaborative Filtering (NCF). This is the most cited of all hybrid models.
medium.com
All examples of the hybrid category use DNN to learn implicit bitwise feature interactions. They differ in how the high order feature interactions are learned.
xDeepFM comprises of 3 parts:
The linear model ( Directly work on top of raw input features )Plain DNN (Works on top of dense feature embeddings)CIN (Works on top of dense feature embeddings)
The linear model ( Directly work on top of raw input features )
Plain DNN (Works on top of dense feature embeddings)
CIN (Works on top of dense feature embeddings)
Out of these 3, CIN is unique to xDeepFM.
The problem with DNN based systems is that they learn the high order interactions implicitly. In xDeepFM the explicit high order feature interactions are learned through Compressed Interaction Network (CIN).
CIN is inducted by xDeepFM due to the following benefits:
It learns feature interactions at a vector wise level, not at a bitwise level.
It measures high order feature interactions explicitly.
Its complexity does not grow exponentially with the degree of interactions.
The explicit feature interactions are learned by the CIN through its hidden layers (Every x in Figure 4 is a hidden layer) which are defined as follows
X(k-1,i): Embedding vector of the ith field in k-th layer (k-1 hidden layer)X(0,j): Embedding vector of the jth field in k-th layer (base embedding/original feature embedding)W(k,h,i,j): Learnable parameter with dimension m * H(k-1)
Every row in X(k) is differentiated only by W(k,h). In contrast to DNN there is no activation to transform the hidden layer.
Equation 1 is similar to RNN based models as CIN’s output is dependent on the last hidden layer and additional input.
m: Number of rows in the original feature matrixH(k): Number of rows in the feature matrix at hidden layer k
Z(k+1) is an intermediate tensor which is an outer product of hidden layer X(k) and original feature matrix X(0). Z(k+1) can be regarded as a special type of image and W(k,h) as a filter.
As you slide the Weight Matrix along the dimension D (size of every feature embedding) you get a hidden vector X(k+1,i).
T: Depth of the network
The result of the hidden layers is summed row-wise and then concatenated together before being fed to the output layer.
Every hidden layer has a connection with the output unitsSum pooling is applied at every hidden layer to create a pooling vector as:
Every hidden layer has a connection with the output units
Sum pooling is applied at every hidden layer to create a pooling vector as:
All pooling vectors from hidden layers are concatenated before connected to output units:
Linear, CIN, and DNN are all trained parallelly with the output equation as follows:
Sigma: Sigmoid Functiona: Raw FeaturesW,b: Learnable parameters
DNN and CIN based layers complement each other well as together they can learn
1. Both implicit (DNN) and explicit (CIN) feature interactions.
2. Both low (DNN) and high (Both) order feature interactions.
First-term represents the number of parameters at the output layerSecond-term represents the number of parameters at every layer kIf we assume all hidden layers to have the same number of feature vectors H. The number of parameters can be represented as O(m*H*H*T)
Time complexity is equivalent to O(mHD * H * T). mhd: Cost of computing Z(k+1,h) for 1 rowH: Number of feature vectors (rows) at layer HT: Number of hidden layers in CIN
With that, we are done with the theory of xdeepfm. It’s time to see it in action.
I have used xDeepFM implementation from the deepCTR library. For some other implementations check out the References segment.
Download the sample data from here and then use the following code to read the data and separate features as dense or sparse.
The sparse features require embedding while the dense features require normalization. We are using MinMax scaler for normalization while LabelEncoder for feature encoding.
# creating a dense featdense_feature_columns = [DenseFeat(feat, 1) for feat in dense_features]
In the next code blob, we are initializing, compiling, training and predicting using xDeepFM
xDeepFM paperSome of the ready-made xDeepFM implementations are:- 1. Code from the writers of paper xDeepFM2. Code from Microsoft library for recommendation3. deepctr which is used in the following implementation
xDeepFM paper
Some of the ready-made xDeepFM implementations are:- 1. Code from the writers of paper xDeepFM2. Code from Microsoft library for recommendation3. deepctr which is used in the following implementation
xDeepFM is an example of a hybrid architecture. It combines MF with DNN to come up with a better performance. It does this by using CIN(Compressed Interaction Network). CIN has 2 special virtues:
It can learn bounded degree feature interactions effectively.It learns feature interactions at a vector-wise level.
It can learn bounded degree feature interactions effectively.
It learns feature interactions at a vector-wise level.
Like other popular hybrid methods, xDeepFM incorporates CIN with DNN.Due to which high order feature interactions can be learned both explicitly and implicitly. This reduces the need for manual feature engineering.
I will urge you to try out Microsoft’s library or the xDeepFM’s author’s code to play around with different xDeepFM’s implementations.
You can also look at this post to get a brief overview of NCF which is another popular hybrid architecture.
medium.com
Please feel free to share your thoughts and ideas in the comments section. | [
{
"code": null,
"e": 575,
"s": 172,
"text": "We are living in times where we are spoilt for choice. Whether it is food, music or entertainment the amount of options that we have is simply mind-boggling. But thanks to the recommendation engines that fuel these apps/sites these alternatives are provided to us in a ranked list. In this blog, we will be discussing a new recommendation algorithm called Extreme Deep Factorisation Machines (xDeepFM)."
},
{
"code": null,
"e": 610,
"s": 575,
"text": "This blog is organized as follows:"
},
{
"code": null,
"e": 937,
"s": 610,
"text": "Current recommendation systems in productionIntroducing xDeepFMIntroducing CIN (the core pillar of xDeepFM) 3.1 CIN characteristics 3.2 CIN hidden layers 3.3 Similarity with RNN 3.4 Similarity with CNN 3.5 Pooling and concatenation of hidden layers 3.6 Output of xdeepfmCIN complexity 4.1 Space Complexity 4.2 Time Complexity"
},
{
"code": null,
"e": 982,
"s": 937,
"text": "Current recommendation systems in production"
},
{
"code": null,
"e": 1002,
"s": 982,
"text": "Introducing xDeepFM"
},
{
"code": null,
"e": 1211,
"s": 1002,
"text": "Introducing CIN (the core pillar of xDeepFM) 3.1 CIN characteristics 3.2 CIN hidden layers 3.3 Similarity with RNN 3.4 Similarity with CNN 3.5 Pooling and concatenation of hidden layers 3.6 Output of xdeepfm"
},
{
"code": null,
"e": 1267,
"s": 1211,
"text": "CIN complexity 4.1 Space Complexity 4.2 Time Complexity"
},
{
"code": null,
"e": 1306,
"s": 1267,
"text": "5. Coded Example using deepCTR library"
},
{
"code": null,
"e": 1320,
"s": 1306,
"text": "6. References"
},
{
"code": null,
"e": 1331,
"s": 1320,
"text": "7. Summary"
},
{
"code": null,
"e": 1345,
"s": 1331,
"text": "Let’s start!!"
},
{
"code": null,
"e": 1510,
"s": 1345,
"text": "The current recommendation landscape is dominated by FM/DNN based models. But some good hybrid architectures which fuse FM and DNN based systems are also coming up."
},
{
"code": null,
"e": 1555,
"s": 1510,
"text": "1. Factorization Machine (FM) based approach"
},
{
"code": null,
"e": 1615,
"s": 1555,
"text": "+ve: Learns pattern on combinatorial features automatically"
},
{
"code": null,
"e": 1655,
"s": 1615,
"text": "+ve: Generalize well to unseen features"
},
{
"code": null,
"e": 1781,
"s": 1655,
"text": "-ve: Tries to capture all feature interactions which results in learning of useless interactions. This might introduce noise."
},
{
"code": null,
"e": 1847,
"s": 1781,
"text": "Examples: the most trusted workhorse of the recommendation domain"
},
{
"code": null,
"e": 1893,
"s": 1847,
"text": "2. Deep Neural Network ( DNN ) based approach"
},
{
"code": null,
"e": 1954,
"s": 1893,
"text": "+ve: Learns sophisticated and selective feature interactions"
},
{
"code": null,
"e": 2277,
"s": 1954,
"text": "-ve: Feature interactions are modeled at an elemental level. One hot encoding is used for categorical variables to represent them in dimension D. This will be fed into a fully connected layer. This is in stark contrast to FM based approaches which models feature interactions at a vector level (User vector * Item Vector)."
},
{
"code": null,
"e": 2367,
"s": 2277,
"text": "Example: DNN part of Neural Collaborative Filtering(NCF), DNN for Youtube recommendations"
},
{
"code": null,
"e": 2397,
"s": 2367,
"text": "3. DNN + FM (Hybrid) approach"
},
{
"code": null,
"e": 2450,
"s": 2397,
"text": "+ve: Learns both low/high order feature interactions"
},
{
"code": null,
"e": 2641,
"s": 2450,
"text": "Examples: Wide & Deep Network(Youtube), Neural Collaborative Filtering(NCF), Deep and Cross network(DCN), Deep Factorisation Machine (DeepFM) and eXtreme Deep Factorisation Machine (xDeepFM)"
},
{
"code": null,
"e": 2779,
"s": 2641,
"text": "You can look into this post to get a brief overview of Neural Collaborative Filtering (NCF). This is the most cited of all hybrid models."
},
{
"code": null,
"e": 2790,
"s": 2779,
"text": "medium.com"
},
{
"code": null,
"e": 2950,
"s": 2790,
"text": "All examples of the hybrid category use DNN to learn implicit bitwise feature interactions. They differ in how the high order feature interactions are learned."
},
{
"code": null,
"e": 2980,
"s": 2950,
"text": "xDeepFM comprises of 3 parts:"
},
{
"code": null,
"e": 3142,
"s": 2980,
"text": "The linear model ( Directly work on top of raw input features )Plain DNN (Works on top of dense feature embeddings)CIN (Works on top of dense feature embeddings)"
},
{
"code": null,
"e": 3206,
"s": 3142,
"text": "The linear model ( Directly work on top of raw input features )"
},
{
"code": null,
"e": 3259,
"s": 3206,
"text": "Plain DNN (Works on top of dense feature embeddings)"
},
{
"code": null,
"e": 3306,
"s": 3259,
"text": "CIN (Works on top of dense feature embeddings)"
},
{
"code": null,
"e": 3348,
"s": 3306,
"text": "Out of these 3, CIN is unique to xDeepFM."
},
{
"code": null,
"e": 3556,
"s": 3348,
"text": "The problem with DNN based systems is that they learn the high order interactions implicitly. In xDeepFM the explicit high order feature interactions are learned through Compressed Interaction Network (CIN)."
},
{
"code": null,
"e": 3614,
"s": 3556,
"text": "CIN is inducted by xDeepFM due to the following benefits:"
},
{
"code": null,
"e": 3693,
"s": 3614,
"text": "It learns feature interactions at a vector wise level, not at a bitwise level."
},
{
"code": null,
"e": 3749,
"s": 3693,
"text": "It measures high order feature interactions explicitly."
},
{
"code": null,
"e": 3825,
"s": 3749,
"text": "Its complexity does not grow exponentially with the degree of interactions."
},
{
"code": null,
"e": 3977,
"s": 3825,
"text": "The explicit feature interactions are learned by the CIN through its hidden layers (Every x in Figure 4 is a hidden layer) which are defined as follows"
},
{
"code": null,
"e": 4210,
"s": 3977,
"text": "X(k-1,i): Embedding vector of the ith field in k-th layer (k-1 hidden layer)X(0,j): Embedding vector of the jth field in k-th layer (base embedding/original feature embedding)W(k,h,i,j): Learnable parameter with dimension m * H(k-1)"
},
{
"code": null,
"e": 4335,
"s": 4210,
"text": "Every row in X(k) is differentiated only by W(k,h). In contrast to DNN there is no activation to transform the hidden layer."
},
{
"code": null,
"e": 4453,
"s": 4335,
"text": "Equation 1 is similar to RNN based models as CIN’s output is dependent on the last hidden layer and additional input."
},
{
"code": null,
"e": 4562,
"s": 4453,
"text": "m: Number of rows in the original feature matrixH(k): Number of rows in the feature matrix at hidden layer k"
},
{
"code": null,
"e": 4750,
"s": 4562,
"text": "Z(k+1) is an intermediate tensor which is an outer product of hidden layer X(k) and original feature matrix X(0). Z(k+1) can be regarded as a special type of image and W(k,h) as a filter."
},
{
"code": null,
"e": 4871,
"s": 4750,
"text": "As you slide the Weight Matrix along the dimension D (size of every feature embedding) you get a hidden vector X(k+1,i)."
},
{
"code": null,
"e": 4895,
"s": 4871,
"text": "T: Depth of the network"
},
{
"code": null,
"e": 5015,
"s": 4895,
"text": "The result of the hidden layers is summed row-wise and then concatenated together before being fed to the output layer."
},
{
"code": null,
"e": 5148,
"s": 5015,
"text": "Every hidden layer has a connection with the output unitsSum pooling is applied at every hidden layer to create a pooling vector as:"
},
{
"code": null,
"e": 5206,
"s": 5148,
"text": "Every hidden layer has a connection with the output units"
},
{
"code": null,
"e": 5282,
"s": 5206,
"text": "Sum pooling is applied at every hidden layer to create a pooling vector as:"
},
{
"code": null,
"e": 5372,
"s": 5282,
"text": "All pooling vectors from hidden layers are concatenated before connected to output units:"
},
{
"code": null,
"e": 5457,
"s": 5372,
"text": "Linear, CIN, and DNN are all trained parallelly with the output equation as follows:"
},
{
"code": null,
"e": 5521,
"s": 5457,
"text": "Sigma: Sigmoid Functiona: Raw FeaturesW,b: Learnable parameters"
},
{
"code": null,
"e": 5600,
"s": 5521,
"text": "DNN and CIN based layers complement each other well as together they can learn"
},
{
"code": null,
"e": 5664,
"s": 5600,
"text": "1. Both implicit (DNN) and explicit (CIN) feature interactions."
},
{
"code": null,
"e": 5726,
"s": 5664,
"text": "2. Both low (DNN) and high (Both) order feature interactions."
},
{
"code": null,
"e": 5991,
"s": 5726,
"text": "First-term represents the number of parameters at the output layerSecond-term represents the number of parameters at every layer kIf we assume all hidden layers to have the same number of feature vectors H. The number of parameters can be represented as O(m*H*H*T)"
},
{
"code": null,
"e": 6161,
"s": 5991,
"text": "Time complexity is equivalent to O(mHD * H * T). mhd: Cost of computing Z(k+1,h) for 1 rowH: Number of feature vectors (rows) at layer HT: Number of hidden layers in CIN"
},
{
"code": null,
"e": 6243,
"s": 6161,
"text": "With that, we are done with the theory of xdeepfm. It’s time to see it in action."
},
{
"code": null,
"e": 6369,
"s": 6243,
"text": "I have used xDeepFM implementation from the deepCTR library. For some other implementations check out the References segment."
},
{
"code": null,
"e": 6495,
"s": 6369,
"text": "Download the sample data from here and then use the following code to read the data and separate features as dense or sparse."
},
{
"code": null,
"e": 6667,
"s": 6495,
"text": "The sparse features require embedding while the dense features require normalization. We are using MinMax scaler for normalization while LabelEncoder for feature encoding."
},
{
"code": null,
"e": 6762,
"s": 6667,
"text": "# creating a dense featdense_feature_columns = [DenseFeat(feat, 1) for feat in dense_features]"
},
{
"code": null,
"e": 6855,
"s": 6762,
"text": "In the next code blob, we are initializing, compiling, training and predicting using xDeepFM"
},
{
"code": null,
"e": 7068,
"s": 6855,
"text": "xDeepFM paperSome of the ready-made xDeepFM implementations are:- 1. Code from the writers of paper xDeepFM2. Code from Microsoft library for recommendation3. deepctr which is used in the following implementation"
},
{
"code": null,
"e": 7082,
"s": 7068,
"text": "xDeepFM paper"
},
{
"code": null,
"e": 7282,
"s": 7082,
"text": "Some of the ready-made xDeepFM implementations are:- 1. Code from the writers of paper xDeepFM2. Code from Microsoft library for recommendation3. deepctr which is used in the following implementation"
},
{
"code": null,
"e": 7478,
"s": 7282,
"text": "xDeepFM is an example of a hybrid architecture. It combines MF with DNN to come up with a better performance. It does this by using CIN(Compressed Interaction Network). CIN has 2 special virtues:"
},
{
"code": null,
"e": 7594,
"s": 7478,
"text": "It can learn bounded degree feature interactions effectively.It learns feature interactions at a vector-wise level."
},
{
"code": null,
"e": 7656,
"s": 7594,
"text": "It can learn bounded degree feature interactions effectively."
},
{
"code": null,
"e": 7711,
"s": 7656,
"text": "It learns feature interactions at a vector-wise level."
},
{
"code": null,
"e": 7926,
"s": 7711,
"text": "Like other popular hybrid methods, xDeepFM incorporates CIN with DNN.Due to which high order feature interactions can be learned both explicitly and implicitly. This reduces the need for manual feature engineering."
},
{
"code": null,
"e": 8061,
"s": 7926,
"text": "I will urge you to try out Microsoft’s library or the xDeepFM’s author’s code to play around with different xDeepFM’s implementations."
},
{
"code": null,
"e": 8169,
"s": 8061,
"text": "You can also look at this post to get a brief overview of NCF which is another popular hybrid architecture."
},
{
"code": null,
"e": 8180,
"s": 8169,
"text": "medium.com"
}
]
|
How to provide shadow effect in a Plot using path_effect attribute in Matplotlib | In order to provide path effects like shadow effect in a plot or a graph, we can use the path_effect attribute.
For example, let’s see how we can use the path_effect attribute in Matplotlib add a shadow effect to a sigmoid function.
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patheffects import PathPatchEffect, SimpleLineShadow, Normal
Now let us define the size of the figure and plot the sigmoid function,
plt.style.use('seaborn-deep')
plt.subplots(figsize=(10,10))
Let us define the datapoints for the plot,
x = np.linspace(-10, 10, 50)
y = 1+ np.exp(-x))
Let us define the shadow property in the plot,
plt.plot(x, y, linewidth=8, color='blue', path_effects=
[SimpleLineShadow(), Normal()])
#Show the Plot
plt.show() | [
{
"code": null,
"e": 1174,
"s": 1062,
"text": "In order to provide path effects like shadow effect in a plot or a graph, we can use the path_effect attribute."
},
{
"code": null,
"e": 1295,
"s": 1174,
"text": "For example, let’s see how we can use the path_effect attribute in Matplotlib add a shadow effect to a sigmoid function."
},
{
"code": null,
"e": 1423,
"s": 1295,
"text": "import matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib.patheffects import PathPatchEffect, SimpleLineShadow, Normal"
},
{
"code": null,
"e": 1495,
"s": 1423,
"text": "Now let us define the size of the figure and plot the sigmoid function,"
},
{
"code": null,
"e": 1555,
"s": 1495,
"text": "plt.style.use('seaborn-deep')\nplt.subplots(figsize=(10,10))"
},
{
"code": null,
"e": 1598,
"s": 1555,
"text": "Let us define the datapoints for the plot,"
},
{
"code": null,
"e": 1646,
"s": 1598,
"text": "x = np.linspace(-10, 10, 50)\ny = 1+ np.exp(-x))"
},
{
"code": null,
"e": 1693,
"s": 1646,
"text": "Let us define the shadow property in the plot,"
},
{
"code": null,
"e": 1807,
"s": 1693,
"text": "plt.plot(x, y, linewidth=8, color='blue', path_effects=\n[SimpleLineShadow(), Normal()])\n#Show the Plot\nplt.show()"
}
]
|
AngularJs Data Binding Example | ng-model in Angular Example Tutorials | 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
One of the important feature of AngularJs is Data Binding. Data binding makes the AngularJs application synchronisation, that means it maintains the sync between the model and view.
Data binding is used to bind the data between the ui (html elements) and AngularJs controller variables.
AngularJs application maintains the Data models to represents the data. Typically these Data Models are consisting with data.
Example of AngularJs Data Modal:
var app = angular.module('dataController', []);
app.controller('dataController', function($scope) {
$scope.firstname = "Chandra Shekhar";
$scope.lastname = "Goka";
});
The above example represents a typical data model in AngularJs. This data would be bind with the corresponding html elements. So that when ever any changes made on any data member from controller, it will automatically effected on the view.
Here the communication is happening between the controller and view because of $scope object. $scope is acts as a mediator between the controller and view.
AngularJs supports two types of Data Binding :
One-way Binding
Two-way Binding
In one-way binding the Data will be updated from the controller. When ever the values changed in Angular controller the corresponding html elements (input, select, textarea) will be updated accordingly. Here is no need of getter and setters like legacy Javascript and JQuery stuff.
Here the binding, data will taking from the controller variables and updated on html elements.
This will happen by making use of either AngularJs Expressions {{}} or ng-bind AngularJs directive.
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="expCtrl">
<p>First name: <b>{{firstname}}</b>
</p>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('expCtrl', function ($scope) {
$scope.firstname = "Chandra";
});
</script>
<p>Here the binding happening from controller.</p>
</body>
</html>
Output :
[advanced_iframe securitykey=”85899c43cd5d45b9ec5729b5189d1961d89f90d9′′ src=”https://www.onlinetutorialspoint.com/AngularJsExamples/AngularJs_Binding_Expression.html”]
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="bindCtrl">
<p>First name: <b ng-bind="firstname"></b></p>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('bindCtrl', function($scope) {
$scope.firstname = "Chandra";
});
</script>
<p>Here the binding happening from controller.</p>
</body>
</html>
Output :
[advanced_iframe securitykey=”85899c43cd5d45b9ec5729b5189d1961d89f90d9′′ src=”https://www.onlinetutorialspoint.com/AngularJsExamples/AngularJs_Binding-ng-bind.html”]
In Two-way binding the html elements and controller variables are sync in each other.
When ever you change the values from html it will reflect to the corresponding variables in controller and vice-versa.
It can be implement by using ng-model directive.
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="">
<p></p>
<p>Enter Your Name:
<input type="text" ng-model="firstName">
</p>
<p>Hello : <b>{{ firstName}}</b> How Are you ?</p>
</div>
</body>
</html>
Output :
[advanced_iframe securitykey=”85899c43cd5d45b9ec5729b5189d1961d89f90d9′′ src=”https://www.onlinetutorialspoint.com/AngularJsExamples/AngularJs_Binding-ng-model.html”]
Happy Learning 🙂
Angular http (AJAX) Example Tutorials
Angular Module Example Tutorials
AngularJs Filters Example Tutorials
AngularJs lowercase Filter Example
AngularJs Currency Filter Example
AngularJs Orderby Filter Example
AngularJs Search Filter Example
Angularjs Custom Filter Example
Angularjs Services Example Tutorials
AngularJs Custom Service Example
AngularJs Custom Directive Example
AngularJs Directive Example Tutorials
Using Array in AngularJs Example
Array of objects in AngularJs Example
Steps to Create AngularJs Controller
Angular http (AJAX) Example Tutorials
Angular Module Example Tutorials
AngularJs Filters Example Tutorials
AngularJs lowercase Filter Example
AngularJs Currency Filter Example
AngularJs Orderby Filter Example
AngularJs Search Filter Example
Angularjs Custom Filter Example
Angularjs Services Example Tutorials
AngularJs Custom Service Example
AngularJs Custom Directive Example
AngularJs Directive Example Tutorials
Using Array in AngularJs Example
Array of objects in AngularJs Example
Steps to Create AngularJs Controller | [
{
"code": null,
"e": 158,
"s": 123,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 172,
"s": 158,
"text": "Java Examples"
},
{
"code": null,
"e": 183,
"s": 172,
"text": "C Examples"
},
{
"code": null,
"e": 195,
"s": 183,
"text": "C Tutorials"
},
{
"code": null,
"e": 199,
"s": 195,
"text": "aws"
},
{
"code": null,
"e": 234,
"s": 199,
"text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC"
},
{
"code": null,
"e": 245,
"s": 234,
"text": "EXCEPTIONS"
},
{
"code": null,
"e": 257,
"s": 245,
"text": "COLLECTIONS"
},
{
"code": null,
"e": 263,
"s": 257,
"text": "SWING"
},
{
"code": null,
"e": 268,
"s": 263,
"text": "JDBC"
},
{
"code": null,
"e": 275,
"s": 268,
"text": "JAVA 8"
},
{
"code": null,
"e": 282,
"s": 275,
"text": "SPRING"
},
{
"code": null,
"e": 294,
"s": 282,
"text": "SPRING BOOT"
},
{
"code": null,
"e": 304,
"s": 294,
"text": "HIBERNATE"
},
{
"code": null,
"e": 311,
"s": 304,
"text": "PYTHON"
},
{
"code": null,
"e": 315,
"s": 311,
"text": "PHP"
},
{
"code": null,
"e": 322,
"s": 315,
"text": "JQUERY"
},
{
"code": null,
"e": 357,
"s": 322,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 371,
"s": 357,
"text": "Java Examples"
},
{
"code": null,
"e": 382,
"s": 371,
"text": "C Examples"
},
{
"code": null,
"e": 394,
"s": 382,
"text": "C Tutorials"
},
{
"code": null,
"e": 398,
"s": 394,
"text": "aws"
},
{
"code": null,
"e": 580,
"s": 398,
"text": "One of the important feature of AngularJs is Data Binding. Data binding makes the AngularJs application synchronisation, that means it maintains the sync between the model and view."
},
{
"code": null,
"e": 685,
"s": 580,
"text": "Data binding is used to bind the data between the ui (html elements) and AngularJs controller variables."
},
{
"code": null,
"e": 811,
"s": 685,
"text": "AngularJs application maintains the Data models to represents the data. Typically these Data Models are consisting with data."
},
{
"code": null,
"e": 844,
"s": 811,
"text": "Example of AngularJs Data Modal:"
},
{
"code": null,
"e": 1012,
"s": 844,
"text": "var app = angular.module('dataController', []);\napp.controller('dataController', function($scope) {\n$scope.firstname = \"Chandra Shekhar\";\n$scope.lastname = \"Goka\";\n});"
},
{
"code": null,
"e": 1253,
"s": 1012,
"text": "The above example represents a typical data model in AngularJs. This data would be bind with the corresponding html elements. So that when ever any changes made on any data member from controller, it will automatically effected on the view."
},
{
"code": null,
"e": 1409,
"s": 1253,
"text": "Here the communication is happening between the controller and view because of $scope object. $scope is acts as a mediator between the controller and view."
},
{
"code": null,
"e": 1456,
"s": 1409,
"text": "AngularJs supports two types of Data Binding :"
},
{
"code": null,
"e": 1472,
"s": 1456,
"text": "One-way Binding"
},
{
"code": null,
"e": 1488,
"s": 1472,
"text": "Two-way Binding"
},
{
"code": null,
"e": 1770,
"s": 1488,
"text": "In one-way binding the Data will be updated from the controller. When ever the values changed in Angular controller the corresponding html elements (input, select, textarea) will be updated accordingly. Here is no need of getter and setters like legacy Javascript and JQuery stuff."
},
{
"code": null,
"e": 1865,
"s": 1770,
"text": "Here the binding, data will taking from the controller variables and updated on html elements."
},
{
"code": null,
"e": 1965,
"s": 1865,
"text": "This will happen by making use of either AngularJs Expressions {{}} or ng-bind AngularJs directive."
},
{
"code": null,
"e": 2520,
"s": 1965,
"text": "<!DOCTYPE html>\n<html>\n <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js\"></script>\n\n <body>\n <div ng-app=\"myApp\" ng-controller=\"expCtrl\">\n <p>First name: <b>{{firstname}}</b>\n </p> \n </div> \n <script>\n var app = angular.module('myApp', []);\n app.controller('expCtrl', function ($scope) {\n $scope.firstname = \"Chandra\";\n });\n </script> \n <p>Here the binding happening from controller.</p> \n </body> \n</html>"
},
{
"code": null,
"e": 2529,
"s": 2520,
"text": "Output :"
},
{
"code": null,
"e": 2698,
"s": 2529,
"text": "[advanced_iframe securitykey=”85899c43cd5d45b9ec5729b5189d1961d89f90d9′′ src=”https://www.onlinetutorialspoint.com/AngularJsExamples/AngularJs_Binding_Expression.html”]"
},
{
"code": null,
"e": 3192,
"s": 2698,
"text": "<!DOCTYPE html>\n<html>\n<script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js\"></script>\n\n<body>\n <div ng-app=\"myApp\" ng-controller=\"bindCtrl\">\n <p>First name: <b ng-bind=\"firstname\"></b></p>\n </div>\n <script>\n var app = angular.module('myApp', []);\n app.controller('bindCtrl', function($scope) {\n $scope.firstname = \"Chandra\";\n });\n </script>\n <p>Here the binding happening from controller.</p>\n</body>\n\n</html>"
},
{
"code": null,
"e": 3201,
"s": 3192,
"text": "Output :"
},
{
"code": null,
"e": 3367,
"s": 3201,
"text": "[advanced_iframe securitykey=”85899c43cd5d45b9ec5729b5189d1961d89f90d9′′ src=”https://www.onlinetutorialspoint.com/AngularJsExamples/AngularJs_Binding-ng-bind.html”]"
},
{
"code": null,
"e": 3453,
"s": 3367,
"text": "In Two-way binding the html elements and controller variables are sync in each other."
},
{
"code": null,
"e": 3573,
"s": 3453,
"text": "When ever you change the values from html it will reflect to the corresponding variables in controller and vice-versa."
},
{
"code": null,
"e": 3622,
"s": 3573,
"text": "It can be implement by using ng-model directive."
},
{
"code": null,
"e": 3963,
"s": 3622,
"text": "<!DOCTYPE html>\n<html>\n<script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js\"></script>\n\n<body>\n <div ng-app=\"\">\n <p></p>\n <p>Enter Your Name:\n <input type=\"text\" ng-model=\"firstName\">\n </p>\n <p>Hello : <b>{{ firstName}}</b> How Are you ?</p>\n </div>\n</body>\n\n</html>"
},
{
"code": null,
"e": 3972,
"s": 3963,
"text": "Output :"
},
{
"code": null,
"e": 4139,
"s": 3972,
"text": "[advanced_iframe securitykey=”85899c43cd5d45b9ec5729b5189d1961d89f90d9′′ src=”https://www.onlinetutorialspoint.com/AngularJsExamples/AngularJs_Binding-ng-model.html”]"
},
{
"code": null,
"e": 4156,
"s": 4139,
"text": "Happy Learning 🙂"
},
{
"code": null,
"e": 4683,
"s": 4156,
"text": "\nAngular http (AJAX) Example Tutorials\nAngular Module Example Tutorials\nAngularJs Filters Example Tutorials\nAngularJs lowercase Filter Example\nAngularJs Currency Filter Example\nAngularJs Orderby Filter Example\nAngularJs Search Filter Example\nAngularjs Custom Filter Example\nAngularjs Services Example Tutorials\nAngularJs Custom Service Example\nAngularJs Custom Directive Example\nAngularJs Directive Example Tutorials\nUsing Array in AngularJs Example\nArray of objects in AngularJs Example\nSteps to Create AngularJs Controller\n"
},
{
"code": null,
"e": 4721,
"s": 4683,
"text": "Angular http (AJAX) Example Tutorials"
},
{
"code": null,
"e": 4754,
"s": 4721,
"text": "Angular Module Example Tutorials"
},
{
"code": null,
"e": 4790,
"s": 4754,
"text": "AngularJs Filters Example Tutorials"
},
{
"code": null,
"e": 4825,
"s": 4790,
"text": "AngularJs lowercase Filter Example"
},
{
"code": null,
"e": 4859,
"s": 4825,
"text": "AngularJs Currency Filter Example"
},
{
"code": null,
"e": 4892,
"s": 4859,
"text": "AngularJs Orderby Filter Example"
},
{
"code": null,
"e": 4924,
"s": 4892,
"text": "AngularJs Search Filter Example"
},
{
"code": null,
"e": 4956,
"s": 4924,
"text": "Angularjs Custom Filter Example"
},
{
"code": null,
"e": 4993,
"s": 4956,
"text": "Angularjs Services Example Tutorials"
},
{
"code": null,
"e": 5026,
"s": 4993,
"text": "AngularJs Custom Service Example"
},
{
"code": null,
"e": 5061,
"s": 5026,
"text": "AngularJs Custom Directive Example"
},
{
"code": null,
"e": 5099,
"s": 5061,
"text": "AngularJs Directive Example Tutorials"
},
{
"code": null,
"e": 5132,
"s": 5099,
"text": "Using Array in AngularJs Example"
},
{
"code": null,
"e": 5171,
"s": 5132,
"text": "Array of objects in AngularJs Example"
}
]
|
CSS - Fade In Left Effect | The image come or cause to come gradually into or out of view, or to merge into another shot.
@keyframes fadeInLeft {
0% {
opacity: 0;
transform: translateX(-20px);
}
100% {
opacity: 1;
transform: translateX(0);
}
}
Transform − Transform applies to 2d and 3d transformation to an element.
Transform − Transform applies to 2d and 3d transformation to an element.
Opacity − Opacity applies to an element to make translucence.
Opacity − Opacity applies to an element to make translucence.
<html>
<head>
<style>
.animated {
background-image: url(/css/images/logo.png);
background-repeat: no-repeat;
background-position: left top;
padding-top:95px;
margin-bottom:60px;
-webkit-animation-duration: 10s;
animation-duration: 10s;
-webkit-animation-fill-mode: both;
animation-fill-mode: both;
}
@-webkit-keyframes fadeInLeft {
0% {
opacity: 0;
-webkit-transform: translateX(-20px);
}
100% {
opacity: 1;
-webkit-transform: translateX(0);
}
}
@keyframes fadeInLeft {
0% {
opacity: 0;
transform: translateX(-20px);
}
100% {
opacity: 1;
transform: translateX(0);
}
}
.fadeInLeft {
-webkit-animation-name: fadeInLeft;
animation-name: fadeInLeft;
}
animation-name: fadeInDown;
</style>
</head>
<body>
<div id = "animated-example" class = "animated fadeInLeft"></div>
<button onclick = "myFunction()">Reload page</button>
<script>
function myFunction() {
location.reload();
}
</script>
</body>
</head>
It will produce the following result −
Academic Tutorials
Big Data & Analytics
Computer Programming
Computer Science
Databases
DevOps
Digital Marketing
Engineering Tutorials
Exams Syllabus
Famous Monuments
GATE Exams Tutorials
Latest Technologies
Machine Learning
Mainframe Development
Management Tutorials
Mathematics Tutorials
Microsoft Technologies
Misc tutorials
Mobile Development
Java Technologies
Python Technologies
SAP Tutorials
Programming Scripts
Selected Reading
Software Quality
Soft Skills
Telecom Tutorials
UPSC IAS Exams
Web Development
Sports Tutorials
XML Technologies
Multi-Language
Interview Questions
Academic Tutorials
Big Data & Analytics
Computer Programming
Computer Science
Databases
DevOps
Digital Marketing
Engineering Tutorials
Exams Syllabus
Famous Monuments
GATE Exams Tutorials
Latest Technologies
Machine Learning
Mainframe Development
Management Tutorials
Mathematics Tutorials
Microsoft Technologies
Misc tutorials
Mobile Development
Java Technologies
Python Technologies
SAP Tutorials
Programming Scripts
Selected Reading
Software Quality
Soft Skills
Telecom Tutorials
UPSC IAS Exams
Web Development
Sports Tutorials
XML Technologies
Multi-Language
Interview Questions
Selected Reading
UPSC IAS Exams Notes
Developer's Best Practices
Questions and Answers
Effective Resume Writing
HR Interview Questions
Computer Glossary
Who is Who
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2720,
"s": 2626,
"text": "The image come or cause to come gradually into or out of view, or to merge into another shot."
},
{
"code": null,
"e": 2881,
"s": 2720,
"text": "@keyframes fadeInLeft {\n 0% {\n opacity: 0;\n transform: translateX(-20px);\n }\n 100% {\n opacity: 1;\n transform: translateX(0);\n }\n} "
},
{
"code": null,
"e": 2954,
"s": 2881,
"text": "Transform − Transform applies to 2d and 3d transformation to an element."
},
{
"code": null,
"e": 3027,
"s": 2954,
"text": "Transform − Transform applies to 2d and 3d transformation to an element."
},
{
"code": null,
"e": 3089,
"s": 3027,
"text": "Opacity − Opacity applies to an element to make translucence."
},
{
"code": null,
"e": 3151,
"s": 3089,
"text": "Opacity − Opacity applies to an element to make translucence."
},
{
"code": null,
"e": 4595,
"s": 3151,
"text": "<html>\n <head>\n <style>\n .animated {\n background-image: url(/css/images/logo.png);\n background-repeat: no-repeat;\n background-position: left top;\n padding-top:95px;\n margin-bottom:60px;\n -webkit-animation-duration: 10s;\n animation-duration: 10s;\n -webkit-animation-fill-mode: both;\n animation-fill-mode: both;\n }\n \n @-webkit-keyframes fadeInLeft {\n 0% {\n opacity: 0;\n -webkit-transform: translateX(-20px);\n }\n 100% {\n opacity: 1;\n -webkit-transform: translateX(0);\n }\n }\n \n @keyframes fadeInLeft {\n 0% {\n opacity: 0;\n transform: translateX(-20px);\n }\n 100% {\n opacity: 1;\n transform: translateX(0);\n }\n }\n \n .fadeInLeft {\n -webkit-animation-name: fadeInLeft;\n animation-name: fadeInLeft;\n } \n animation-name: fadeInDown;\n </style>\n </head>\n\n <body>\n \n <div id = \"animated-example\" class = \"animated fadeInLeft\"></div>\n <button onclick = \"myFunction()\">Reload page</button>\n \n <script>\n function myFunction() {\n location.reload();\n }\n </script>\n </body>\n</head>"
},
{
"code": null,
"e": 4634,
"s": 4595,
"text": "It will produce the following result −"
},
{
"code": null,
"e": 5281,
"s": 4634,
"text": "\n\n Academic Tutorials\n Big Data & Analytics \n Computer Programming \n Computer Science \n Databases \n DevOps \n Digital Marketing \n Engineering Tutorials \n Exams Syllabus \n Famous Monuments \n GATE Exams Tutorials\n Latest Technologies \n Machine Learning \n Mainframe Development \n Management Tutorials \n Mathematics Tutorials\n Microsoft Technologies \n Misc tutorials \n Mobile Development \n Java Technologies \n Python Technologies \n SAP Tutorials \nProgramming Scripts \n Selected Reading \n Software Quality \n Soft Skills \n Telecom Tutorials \n UPSC IAS Exams \n Web Development \n Sports Tutorials \n XML Technologies \n Multi-Language\n Interview Questions\n\n"
},
{
"code": null,
"e": 5301,
"s": 5281,
"text": " Academic Tutorials"
},
{
"code": null,
"e": 5324,
"s": 5301,
"text": " Big Data & Analytics "
},
{
"code": null,
"e": 5347,
"s": 5324,
"text": " Computer Programming "
},
{
"code": null,
"e": 5366,
"s": 5347,
"text": " Computer Science "
},
{
"code": null,
"e": 5378,
"s": 5366,
"text": " Databases "
},
{
"code": null,
"e": 5387,
"s": 5378,
"text": " DevOps "
},
{
"code": null,
"e": 5407,
"s": 5387,
"text": " Digital Marketing "
},
{
"code": null,
"e": 5431,
"s": 5407,
"text": " Engineering Tutorials "
},
{
"code": null,
"e": 5448,
"s": 5431,
"text": " Exams Syllabus "
},
{
"code": null,
"e": 5467,
"s": 5448,
"text": " Famous Monuments "
},
{
"code": null,
"e": 5489,
"s": 5467,
"text": " GATE Exams Tutorials"
},
{
"code": null,
"e": 5511,
"s": 5489,
"text": " Latest Technologies "
},
{
"code": null,
"e": 5530,
"s": 5511,
"text": " Machine Learning "
},
{
"code": null,
"e": 5554,
"s": 5530,
"text": " Mainframe Development "
},
{
"code": null,
"e": 5577,
"s": 5554,
"text": " Management Tutorials "
},
{
"code": null,
"e": 5600,
"s": 5577,
"text": " Mathematics Tutorials"
},
{
"code": null,
"e": 5625,
"s": 5600,
"text": " Microsoft Technologies "
},
{
"code": null,
"e": 5642,
"s": 5625,
"text": " Misc tutorials "
},
{
"code": null,
"e": 5663,
"s": 5642,
"text": " Mobile Development "
},
{
"code": null,
"e": 5683,
"s": 5663,
"text": " Java Technologies "
},
{
"code": null,
"e": 5705,
"s": 5683,
"text": " Python Technologies "
},
{
"code": null,
"e": 5721,
"s": 5705,
"text": " SAP Tutorials "
},
{
"code": null,
"e": 5742,
"s": 5721,
"text": "Programming Scripts "
},
{
"code": null,
"e": 5761,
"s": 5742,
"text": " Selected Reading "
},
{
"code": null,
"e": 5780,
"s": 5761,
"text": " Software Quality "
},
{
"code": null,
"e": 5794,
"s": 5780,
"text": " Soft Skills "
},
{
"code": null,
"e": 5814,
"s": 5794,
"text": " Telecom Tutorials "
},
{
"code": null,
"e": 5831,
"s": 5814,
"text": " UPSC IAS Exams "
},
{
"code": null,
"e": 5849,
"s": 5831,
"text": " Web Development "
},
{
"code": null,
"e": 5868,
"s": 5849,
"text": " Sports Tutorials "
},
{
"code": null,
"e": 5887,
"s": 5868,
"text": " XML Technologies "
},
{
"code": null,
"e": 5903,
"s": 5887,
"text": " Multi-Language"
},
{
"code": null,
"e": 5924,
"s": 5903,
"text": " Interview Questions"
},
{
"code": null,
"e": 5941,
"s": 5924,
"text": "Selected Reading"
},
{
"code": null,
"e": 5962,
"s": 5941,
"text": "UPSC IAS Exams Notes"
},
{
"code": null,
"e": 5989,
"s": 5962,
"text": "Developer's Best Practices"
},
{
"code": null,
"e": 6011,
"s": 5989,
"text": "Questions and Answers"
},
{
"code": null,
"e": 6036,
"s": 6011,
"text": "Effective Resume Writing"
},
{
"code": null,
"e": 6059,
"s": 6036,
"text": "HR Interview Questions"
},
{
"code": null,
"e": 6077,
"s": 6059,
"text": "Computer Glossary"
},
{
"code": null,
"e": 6088,
"s": 6077,
"text": "Who is Who"
},
{
"code": null,
"e": 6095,
"s": 6088,
"text": " Print"
},
{
"code": null,
"e": 6106,
"s": 6095,
"text": " Add Notes"
}
]
|
Second Chance (or Clock) Page Replacement Policy - GeeksforGeeks | 08 Feb, 2022
Prerequisite – Page Replacement Algorithms Apart from LRU, OPT and FIFO page replacement policies, we also have the second chance/clock page replacement policy. In the Second Chance page replacement policy, the candidate pages for removal are considered in a round robin matter, and a page that has been accessed between consecutive considerations will not be replaced. The page replaced is the one that, when considered in a round robin matter, has not been accessed since its last consideration. It can be implemented by adding a “second chance” bit to each memory frame-every time the frame is considered (due to a reference made to the page inside it), this bit is set to 1, which gives the page a second chance, as when we consider the candidate page for replacement, we replace the first one with this bit set to 0 (while zeroing out bits of the other pages we see in the process). Thus, a page with the “second chance” bit set to 1 is never replaced during the first consideration and will only be replaced if all the other pages deserve a second chance too!Example – Let’s say the reference string is 0 4 1 4 2 4 3 4 2 4 0 4 1 4 2 4 3 4 and we have 3 frames. Let’s see how the algorithm proceeds by tracking the second chance bit and the pointer.
Initially, all frames are empty so after first 3 passes they will be filled with {0, 4, 1} and the second chance array will be {0, 0, 0} as none has been referenced yet. Also, the pointer will cycle back to 0.
Pass-4: Frame={0, 4, 1}, second_chance = {0, 1, 0} [4 will get a second chance], pointer = 0 (No page needed to be updated so the candidate is still page in frame 0), pf = 3 (No increase in page fault number).
Pass-5: Frame={2, 4, 1}, second_chance= {0, 1, 0} [0 replaced; it’s second chance bit was 0, so it didn’t get a second chance], pointer=1 (updated), pf=4
Pass-6: Frame={2, 4, 1}, second_chance={0, 1, 0}, pointer=1, pf=4 (No change)
Pass-7: Frame={2, 4, 3}, second_chance= {0, 0, 0} [4 survived but it’s second chance bit became 0], pointer=0 (as element at index 2 was finally replaced), pf=5
Pass-8: Frame={2, 4, 3}, second_chance= {0, 1, 0} [4 referenced again], pointer=0, pf=5
Pass-9: Frame={2, 4, 3}, second_chance= {1, 1, 0} [2 referenced again], pointer=0, pf=5
Pass-10: Frame={2, 4, 3}, second_chance= {1, 1, 0}, pointer=0, pf=5 (no change)
Pass-11: Frame={2, 4, 0}, second_chance= {0, 0, 0}, pointer=0, pf=6 (2 and 4 got second chances)
Pass-12: Frame={2, 4, 0}, second_chance= {0, 1, 0}, pointer=0, pf=6 (4 will again get a second chance)
Pass-13: Frame={1, 4, 0}, second_chance= {0, 1, 0}, pointer=1, pf=7 (pointer updated, pf updated)
Page-14: Frame={1, 4, 0}, second_chance= {0, 1, 0}, pointer=1, pf=7 (No change)
Page-15: Frame={1, 4, 2}, second_chance= {0, 0, 0}, pointer=0, pf=8 (4 survived again due to 2nd chance!)
Page-16: Frame={1, 4, 2}, second_chance= {0, 1, 0}, pointer=0, pf=8 (2nd chance updated)
Page-17: Frame={3, 4, 2}, second_chance= {0, 1, 0}, pointer=1, pf=9 (pointer, pf updated)
Page-18: Frame={3, 4, 2}, second_chance= {0, 1, 0}, pointer=1, pf=9 (No change)
In this example, second chance algorithm does as well as the LRU method, which is much more expensive to implement in hardware.More Examples –
Input: 2 5 10 1 2 2 6 9 1 2 10 2 6 1 2 1 6 9 5 1
3
Output: 14
Input: 2 5 10 1 2 2 6 9 1 2 10 2 6 1 2 1 6 9 5 1
4
Output: 11
Algorithm – Create an array frames to track the pages currently in memory and another Boolean array second_chance to track whether that page has been accessed since it’s last replacement (that is if it deserves a second chance or not) and a variable pointer to track the target for replacement.
Start traversing the array arr. If the page already exists, simply set its corresponding element in second_chance to true and return. If the page doesn’t exist, check whether the space pointed to by pointer is empty (indicating cache isn’t full yet) – if so, we will put the element there and return, else we’ll traverse the array arr one by one (cyclically using the value of pointer), marking all corresponding second_chance elements as false, till we find a one that’s already false. That is the most suitable page for replacement, so we do so and return. Finally, we report the page fault count.
Start traversing the array arr. If the page already exists, simply set its corresponding element in second_chance to true and return.
If the page doesn’t exist, check whether the space pointed to by pointer is empty (indicating cache isn’t full yet) – if so, we will put the element there and return, else we’ll traverse the array arr one by one (cyclically using the value of pointer), marking all corresponding second_chance elements as false, till we find a one that’s already false. That is the most suitable page for replacement, so we do so and return.
Finally, we report the page fault count.
C++
Java
Python3
C#
Javascript
// CPP program to find largest in an array// without conditional/bitwise/ternary/ operators// and without library functions.#include<iostream>#include<cstring>#include<sstream>using namespace std; // If page found, updates the second chance bit to truestatic bool findAndUpdate(int x,int arr[], bool second_chance[],int frames) { int i; for(i = 0; i < frames; i++) { if(arr[i] == x) { // Mark that the page deserves a second chance second_chance[i] = true; // Return 'true', that is there was a hit // and so there's no need to replace any page return true; } } // Return 'false' so that a page for replacement is selected // as he reuested page doesn't exist in memory return false; } // Updates the page in memory and returns the pointerstatic int replaceAndUpdate(int x,int arr[], bool second_chance[],int frames,int pointer){ while(true) { // We found the page to replace if(!second_chance[pointer]) { // Replace with new page arr[pointer] = x; // Return updated pointer return (pointer + 1) % frames; } // Mark it 'false' as it got one chance // and will be replaced next time unless accessed again second_chance[pointer] = false; //Pointer is updated in round robin manner pointer = (pointer + 1) % frames; }} static void printHitsAndFaults(string reference_string, int frames){ int pointer, i, l=0, x, pf; //initially we consider frame 0 is to be replaced pointer = 0; //number of page faults pf = 0; // Create a array to hold page numbers int arr[frames]; // No pages initially in frame, // which is indicated by -1 memset(arr, -1, sizeof(arr)); // Create second chance array. // Can also be a byte array for optimizing memory bool second_chance[frames]; // Split the string into tokens, // that is page numbers, based on space string str[100]; string word = ""; for (auto x : reference_string) { if (x == ' ') { str[l]=word; word = ""; l++; } else { word = word + x; } } str[l] = word; l++; // l=the length of array for(i = 0; i < l; i++) { x = stoi(str[i]); // Finds if there exists a need to replace // any page at all if(!findAndUpdate(x,arr,second_chance,frames)) { // Selects and updates a victim page pointer = replaceAndUpdate(x,arr, second_chance,frames,pointer); // Update page faults pf++; } } cout << "Total page faults were " << pf << "\n";} // Driver codeint main(){ string reference_string = ""; int frames = 0; // Test 1: reference_string = "0 4 1 4 2 4 3 4 2 4 0 4 1 4 2 4 3 4"; frames = 3; // Output is 9 printHitsAndFaults(reference_string,frames); // Test 2: reference_string = "2 5 10 1 2 2 6 9 1 2 10 2 6 1 2 1 6 9 5 1"; frames = 4; // Output is 11 printHitsAndFaults(reference_string,frames); return 0;} // This code is contributed by NikhilRathor
// Java program to find largest in an array// without conditional/bitwise/ternary/ operators// and without library functions.import java.util.*;import java.io.*;class secondChance{ public static void main(String args[])throws IOException { String reference_string = ""; int frames = 0; //Test 1: reference_string = "0 4 1 4 2 4 3 4 2 4 0 4 1 4 2 4 3 4"; frames = 3; //Output is 9 printHitsAndFaults(reference_string,frames); //Test 2: reference_string = "2 5 10 1 2 2 6 9 1 2 10 2 6 1 2 1 6 9 5 1"; frames = 4; //Output is 11 printHitsAndFaults(reference_string,frames); } //If page found, updates the second chance bit to true static boolean findAndUpdate(int x,int arr[], boolean second_chance[],int frames) { int i; for(i = 0; i < frames; i++) { if(arr[i] == x) { //Mark that the page deserves a second chance second_chance[i] = true; //Return 'true', that is there was a hit //and so there's no need to replace any page return true; } } //Return 'false' so that a page for replacement is selected //as he reuested page doesn't exist in memory return false; } //Updates the page in memory and returns the pointer static int replaceAndUpdate(int x,int arr[], boolean second_chance[],int frames,int pointer) { while(true) { //We found the page to replace if(!second_chance[pointer]) { //Replace with new page arr[pointer] = x; //Return updated pointer return (pointer+1)%frames; } //Mark it 'false' as it got one chance // and will be replaced next time unless accessed again second_chance[pointer] = false; //Pointer is updated in round robin manner pointer = (pointer+1)%frames; } } static void printHitsAndFaults(String reference_string, int frames) { int pointer,i,l,x,pf; //initially we consider frame 0 is to be replaced pointer = 0; //number of page faults pf = 0; //Create a array to hold page numbers int arr[] = new int[frames]; //No pages initially in frame, //which is indicated by -1 Arrays.fill(arr,-1); //Create second chance array. //Can also be a byte array for optimizing memory boolean second_chance[] = new boolean[frames]; //Split the string into tokens, //that is page numbers, based on space String str[] = reference_string.split(" "); //get the length of array l = str.length; for(i = 0; i<l; i++) { x = Integer.parseInt(str[i]); //Finds if there exists a need to replace //any page at all if(!findAndUpdate(x,arr,second_chance,frames)) { //Selects and updates a victim page pointer = replaceAndUpdate(x,arr, second_chance,frames,pointer); //Update page faults pf++; } } System.out.println("Total page faults were "+pf); }}
# Python3 program to find largest in an array# without conditional/bitwise/ternary/ operators# and without library functions. # If page found, updates the second chance bit to truedef findAndUpdate(x, arr, second_chance, frames): for i in range(frames): if arr[i] == x: # Mark that the page deserves a second chance second_chance[i] = True # Return 'true', that is there was a hit #and so there's no need to replace any page return True # Return 'false' so that a page # for replacement is selected # as he reuested page doesn't # exist in memory return False # Updates the page in memory# and returns the pointerdef replaceAndUpdate(x, arr, second_chance, frames, pointer): while(True): # We found the page to replace if not second_chance[pointer]: # Replace with new page arr[pointer] = x #Return updated pointer return (pointer+1)%frames # Mark it 'false' as it got one chance # and will be replaced next time unless accessed again second_chance[pointer] = False # Pointer is updated in round robin manner pointer = (pointer + 1) % frames def printHitsAndFaults(reference_string, frames): # initially we consider # frame 0 is to be replaced pointer = 0 # number of page faults pf = 0 # Create a array to hold page numbers arr = [0]*frames # No pages initially in frame, # which is indicated by -1 for s in range(frames): arr[s] = -1 # Create second chance array. # Can also be a byte array for optimizing memory second_chance = [False]*frames # Split the string into tokens, # that is page numbers, based on space Str = reference_string.split(' ') # get the length of array l = len(Str) for i in range(l): x = Str[i] # Finds if there exists a need to replace # any page at all if not findAndUpdate(x,arr,second_chance,frames): # Selects and updates a victim page pointer = replaceAndUpdate(x,arr,second_chance,frames,pointer) # Update page faults pf += 1 print("Total page faults were", pf) reference_string = ""frames = 0 # Test 1:reference_string = "0 4 1 4 2 4 3 4 2 4 0 4 1 4 2 4 3 4"frames = 3 # Output is 9printHitsAndFaults(reference_string,frames) # Test 2:reference_string = "2 5 10 1 2 2 6 9 1 2 10 2 6 1 2 1 6 9 5 1"frames = 4 # Output is 11printHitsAndFaults(reference_string,frames) # This code is contributed by mukesh07.
// C# program to find largest in an array// without conditional/bitwise/ternary/ operators// and without library functions.using System; public class secondChance{ public static void Main() { String reference_string = ""; int frames = 0; // Test 1: reference_string = "0 4 1 4 2 4 3 4 2 4 0 4 1 4 2 4 3 4"; frames = 3; // Output is 9 printHitsAndFaults(reference_string,frames); // Test 2: reference_string = "2 5 10 1 2 2 6 9 1 2 10 2 6 1 2 1 6 9 5 1"; frames = 4; // Output is 11 printHitsAndFaults(reference_string,frames); } // If page found, updates the second chance bit to true static bool findAndUpdate(int x,int []arr, bool []second_chance,int frames) { int i; for(i = 0; i < frames; i++) { if(arr[i] == x) { //Mark that the page deserves a second chance second_chance[i] = true; //Return 'true', that is there was a hit //and so there's no need to replace any page return true; } } // Return 'false' so that a page // for replacement is selected // as he reuested page doesn't // exist in memory return false; } // Updates the page in memory // and returns the pointer static int replaceAndUpdate(int x,int []arr, bool []second_chance,int frames,int pointer) { while(true) { //We found the page to replace if(!second_chance[pointer]) { //Replace with new page arr[pointer] = x; //Return updated pointer return (pointer+1)%frames; } //Mark it 'false' as it got one chance // and will be replaced next time unless accessed again second_chance[pointer] = false; //Pointer is updated in round robin manner pointer = (pointer + 1) % frames; } } static void printHitsAndFaults(String reference_string, int frames) { int pointer, i, l, x, pf; // initially we consider // frame 0 is to be replaced pointer = 0; // number of page faults pf = 0; // Create a array to hold page numbers int []arr = new int[frames]; // No pages initially in frame, // which is indicated by -1 for(int s = 0;s<frames;s++) arr[s]=-1; //Create second chance array. //Can also be a byte array for optimizing memory bool []second_chance = new bool[frames]; //Split the string into tokens, //that is page numbers, based on space String []str = reference_string.Split(); //get the length of array l = str.Length; for(i = 0; i < l; i++) { x = int.Parse(str[i]); //Finds if there exists a need to replace //any page at all if(!findAndUpdate(x,arr,second_chance,frames)) { //Selects and updates a victim page pointer = replaceAndUpdate(x,arr, second_chance,frames,pointer); //Update page faults pf++; } } Console.WriteLine("Total page faults were "+pf); }} // This code has been contributed by 29AjayKumar
<script> // Javascript program to find largest in an array // without conditional/bitwise/ternary/ operators // and without library functions. // If page found, updates the second chance bit to true function findAndUpdate(x, arr, second_chance, frames) { let i; for(i = 0; i < frames; i++) { if(arr[i] == x) { //Mark that the page deserves a second chance second_chance[i] = true; //Return 'true', that is there was a hit //and so there's no need to replace any page return true; } } // Return 'false' so that a page // for replacement is selected // as he reuested page doesn't // exist in memory return false; } // Updates the page in memory // and returns the pointer function replaceAndUpdate(x, arr, second_chance, frames, pointer) { while(true) { //We found the page to replace if(!second_chance[pointer]) { //Replace with new page arr[pointer] = x; //Return updated pointer return (pointer+1)%frames; } //Mark it 'false' as it got one chance // and will be replaced next time unless accessed again second_chance[pointer] = false; //Pointer is updated in round robin manner pointer = (pointer + 1) % frames; } } function printHitsAndFaults(reference_string, frames) { let pointer, i, l, x, pf; // initially we consider // frame 0 is to be replaced pointer = 0; // number of page faults pf = 0; // Create a array to hold page numbers let arr = new Array(frames); arr.fill(0); // No pages initially in frame, // which is indicated by -1 for(let s = 0;s<frames;s++) arr[s]=-1; //Create second chance array. //Can also be a byte array for optimizing memory let second_chance = new Array(frames); second_chance.fill(false); //Split the string into tokens, //that is page numbers, based on space let str = reference_string.split(' '); //get the length of array l = str.length; for(i = 0; i < l; i++) { x = str[i]; //Finds if there exists a need to replace //any page at all if(!findAndUpdate(x,arr,second_chance,frames)) { //Selects and updates a victim page pointer = replaceAndUpdate(x,arr, second_chance,frames,pointer); //Update page faults pf++; } } document.write("Total page faults were " + pf + "</br>"); } let reference_string = ""; let frames = 0; // Test 1: reference_string = "0 4 1 4 2 4 3 4 2 4 0 4 1 4 2 4 3 4"; frames = 3; // Output is 9 printHitsAndFaults(reference_string,frames); // Test 2: reference_string = "2 5 10 1 2 2 6 9 1 2 10 2 6 1 2 1 6 9 5 1"; frames = 4; // Output is 11 printHitsAndFaults(reference_string,frames); // This code is contributed by divyesh072019.</script>
Output:
Total page faults were 9
Total page faults were 11
Note:
The arrays arr and second_chance can be replaced and combined together via a hashmap (with element as key, true/false as value) to speed up search.Time complexity of this method is O(Number_of_frames*reference_string_length) or O(mn) but since number of frames will be a constant in an Operating System (as main memory size is fixed), it is simply O(n) [Same as hashmap approach, but that will have lower constants]Second chance algorithm may suffer from Belady’s Anomaly.
The arrays arr and second_chance can be replaced and combined together via a hashmap (with element as key, true/false as value) to speed up search.
Time complexity of this method is O(Number_of_frames*reference_string_length) or O(mn) but since number of frames will be a constant in an Operating System (as main memory size is fixed), it is simply O(n) [Same as hashmap approach, but that will have lower constants]
Second chance algorithm may suffer from Belady’s Anomaly.
29AjayKumar
NikhilRathor
code_rama
divyesh072019
mukesh07
rkbhola5
Operating Systems-Memory Management
Operating Systems
Operating Systems
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Memory Management in Operating System
File Allocation Methods
Logical and Physical Address in Operating System
Difference between Internal and External fragmentation
File Access Methods in Operating System
Memory Hierarchy Design and its Characteristics
Process Table and Process Control Block (PCB)
Program for Least Recently Used (LRU) Page Replacement algorithm
States of a Process in Operating Systems
Introduction of Process Management | [
{
"code": null,
"e": 24614,
"s": 24586,
"text": "\n08 Feb, 2022"
},
{
"code": null,
"e": 25871,
"s": 24614,
"text": "Prerequisite – Page Replacement Algorithms Apart from LRU, OPT and FIFO page replacement policies, we also have the second chance/clock page replacement policy. In the Second Chance page replacement policy, the candidate pages for removal are considered in a round robin matter, and a page that has been accessed between consecutive considerations will not be replaced. The page replaced is the one that, when considered in a round robin matter, has not been accessed since its last consideration. It can be implemented by adding a “second chance” bit to each memory frame-every time the frame is considered (due to a reference made to the page inside it), this bit is set to 1, which gives the page a second chance, as when we consider the candidate page for replacement, we replace the first one with this bit set to 0 (while zeroing out bits of the other pages we see in the process). Thus, a page with the “second chance” bit set to 1 is never replaced during the first consideration and will only be replaced if all the other pages deserve a second chance too!Example – Let’s say the reference string is 0 4 1 4 2 4 3 4 2 4 0 4 1 4 2 4 3 4 and we have 3 frames. Let’s see how the algorithm proceeds by tracking the second chance bit and the pointer. "
},
{
"code": null,
"e": 26083,
"s": 25871,
"text": "Initially, all frames are empty so after first 3 passes they will be filled with {0, 4, 1} and the second chance array will be {0, 0, 0} as none has been referenced yet. Also, the pointer will cycle back to 0. "
},
{
"code": null,
"e": 26295,
"s": 26083,
"text": "Pass-4: Frame={0, 4, 1}, second_chance = {0, 1, 0} [4 will get a second chance], pointer = 0 (No page needed to be updated so the candidate is still page in frame 0), pf = 3 (No increase in page fault number). "
},
{
"code": null,
"e": 26451,
"s": 26295,
"text": "Pass-5: Frame={2, 4, 1}, second_chance= {0, 1, 0} [0 replaced; it’s second chance bit was 0, so it didn’t get a second chance], pointer=1 (updated), pf=4 "
},
{
"code": null,
"e": 26531,
"s": 26451,
"text": "Pass-6: Frame={2, 4, 1}, second_chance={0, 1, 0}, pointer=1, pf=4 (No change) "
},
{
"code": null,
"e": 26694,
"s": 26531,
"text": "Pass-7: Frame={2, 4, 3}, second_chance= {0, 0, 0} [4 survived but it’s second chance bit became 0], pointer=0 (as element at index 2 was finally replaced), pf=5 "
},
{
"code": null,
"e": 26784,
"s": 26694,
"text": "Pass-8: Frame={2, 4, 3}, second_chance= {0, 1, 0} [4 referenced again], pointer=0, pf=5 "
},
{
"code": null,
"e": 26874,
"s": 26784,
"text": "Pass-9: Frame={2, 4, 3}, second_chance= {1, 1, 0} [2 referenced again], pointer=0, pf=5 "
},
{
"code": null,
"e": 26956,
"s": 26874,
"text": "Pass-10: Frame={2, 4, 3}, second_chance= {1, 1, 0}, pointer=0, pf=5 (no change) "
},
{
"code": null,
"e": 27055,
"s": 26956,
"text": "Pass-11: Frame={2, 4, 0}, second_chance= {0, 0, 0}, pointer=0, pf=6 (2 and 4 got second chances) "
},
{
"code": null,
"e": 27160,
"s": 27055,
"text": "Pass-12: Frame={2, 4, 0}, second_chance= {0, 1, 0}, pointer=0, pf=6 (4 will again get a second chance) "
},
{
"code": null,
"e": 27260,
"s": 27160,
"text": "Pass-13: Frame={1, 4, 0}, second_chance= {0, 1, 0}, pointer=1, pf=7 (pointer updated, pf updated) "
},
{
"code": null,
"e": 27342,
"s": 27260,
"text": "Page-14: Frame={1, 4, 0}, second_chance= {0, 1, 0}, pointer=1, pf=7 (No change) "
},
{
"code": null,
"e": 27450,
"s": 27342,
"text": "Page-15: Frame={1, 4, 2}, second_chance= {0, 0, 0}, pointer=0, pf=8 (4 survived again due to 2nd chance!) "
},
{
"code": null,
"e": 27541,
"s": 27450,
"text": "Page-16: Frame={1, 4, 2}, second_chance= {0, 1, 0}, pointer=0, pf=8 (2nd chance updated) "
},
{
"code": null,
"e": 27633,
"s": 27541,
"text": "Page-17: Frame={3, 4, 2}, second_chance= {0, 1, 0}, pointer=1, pf=9 (pointer, pf updated) "
},
{
"code": null,
"e": 27715,
"s": 27633,
"text": "Page-18: Frame={3, 4, 2}, second_chance= {0, 1, 0}, pointer=1, pf=9 (No change) "
},
{
"code": null,
"e": 27860,
"s": 27715,
"text": "In this example, second chance algorithm does as well as the LRU method, which is much more expensive to implement in hardware.More Examples – "
},
{
"code": null,
"e": 27986,
"s": 27860,
"text": "Input: 2 5 10 1 2 2 6 9 1 2 10 2 6 1 2 1 6 9 5 1\n3\nOutput: 14\n\nInput: 2 5 10 1 2 2 6 9 1 2 10 2 6 1 2 1 6 9 5 1\n4\nOutput: 11 "
},
{
"code": null,
"e": 28283,
"s": 27986,
"text": "Algorithm – Create an array frames to track the pages currently in memory and another Boolean array second_chance to track whether that page has been accessed since it’s last replacement (that is if it deserves a second chance or not) and a variable pointer to track the target for replacement. "
},
{
"code": null,
"e": 28887,
"s": 28283,
"text": "Start traversing the array arr. If the page already exists, simply set its corresponding element in second_chance to true and return. If the page doesn’t exist, check whether the space pointed to by pointer is empty (indicating cache isn’t full yet) – if so, we will put the element there and return, else we’ll traverse the array arr one by one (cyclically using the value of pointer), marking all corresponding second_chance elements as false, till we find a one that’s already false. That is the most suitable page for replacement, so we do so and return. Finally, we report the page fault count. "
},
{
"code": null,
"e": 29023,
"s": 28887,
"text": "Start traversing the array arr. If the page already exists, simply set its corresponding element in second_chance to true and return. "
},
{
"code": null,
"e": 29450,
"s": 29023,
"text": "If the page doesn’t exist, check whether the space pointed to by pointer is empty (indicating cache isn’t full yet) – if so, we will put the element there and return, else we’ll traverse the array arr one by one (cyclically using the value of pointer), marking all corresponding second_chance elements as false, till we find a one that’s already false. That is the most suitable page for replacement, so we do so and return. "
},
{
"code": null,
"e": 29493,
"s": 29450,
"text": "Finally, we report the page fault count. "
},
{
"code": null,
"e": 29501,
"s": 29497,
"text": "C++"
},
{
"code": null,
"e": 29506,
"s": 29501,
"text": "Java"
},
{
"code": null,
"e": 29514,
"s": 29506,
"text": "Python3"
},
{
"code": null,
"e": 29517,
"s": 29514,
"text": "C#"
},
{
"code": null,
"e": 29528,
"s": 29517,
"text": "Javascript"
},
{
"code": "// CPP program to find largest in an array// without conditional/bitwise/ternary/ operators// and without library functions.#include<iostream>#include<cstring>#include<sstream>using namespace std; // If page found, updates the second chance bit to truestatic bool findAndUpdate(int x,int arr[], bool second_chance[],int frames) { int i; for(i = 0; i < frames; i++) { if(arr[i] == x) { // Mark that the page deserves a second chance second_chance[i] = true; // Return 'true', that is there was a hit // and so there's no need to replace any page return true; } } // Return 'false' so that a page for replacement is selected // as he reuested page doesn't exist in memory return false; } // Updates the page in memory and returns the pointerstatic int replaceAndUpdate(int x,int arr[], bool second_chance[],int frames,int pointer){ while(true) { // We found the page to replace if(!second_chance[pointer]) { // Replace with new page arr[pointer] = x; // Return updated pointer return (pointer + 1) % frames; } // Mark it 'false' as it got one chance // and will be replaced next time unless accessed again second_chance[pointer] = false; //Pointer is updated in round robin manner pointer = (pointer + 1) % frames; }} static void printHitsAndFaults(string reference_string, int frames){ int pointer, i, l=0, x, pf; //initially we consider frame 0 is to be replaced pointer = 0; //number of page faults pf = 0; // Create a array to hold page numbers int arr[frames]; // No pages initially in frame, // which is indicated by -1 memset(arr, -1, sizeof(arr)); // Create second chance array. // Can also be a byte array for optimizing memory bool second_chance[frames]; // Split the string into tokens, // that is page numbers, based on space string str[100]; string word = \"\"; for (auto x : reference_string) { if (x == ' ') { str[l]=word; word = \"\"; l++; } else { word = word + x; } } str[l] = word; l++; // l=the length of array for(i = 0; i < l; i++) { x = stoi(str[i]); // Finds if there exists a need to replace // any page at all if(!findAndUpdate(x,arr,second_chance,frames)) { // Selects and updates a victim page pointer = replaceAndUpdate(x,arr, second_chance,frames,pointer); // Update page faults pf++; } } cout << \"Total page faults were \" << pf << \"\\n\";} // Driver codeint main(){ string reference_string = \"\"; int frames = 0; // Test 1: reference_string = \"0 4 1 4 2 4 3 4 2 4 0 4 1 4 2 4 3 4\"; frames = 3; // Output is 9 printHitsAndFaults(reference_string,frames); // Test 2: reference_string = \"2 5 10 1 2 2 6 9 1 2 10 2 6 1 2 1 6 9 5 1\"; frames = 4; // Output is 11 printHitsAndFaults(reference_string,frames); return 0;} // This code is contributed by NikhilRathor",
"e": 32959,
"s": 29528,
"text": null
},
{
"code": "// Java program to find largest in an array// without conditional/bitwise/ternary/ operators// and without library functions.import java.util.*;import java.io.*;class secondChance{ public static void main(String args[])throws IOException { String reference_string = \"\"; int frames = 0; //Test 1: reference_string = \"0 4 1 4 2 4 3 4 2 4 0 4 1 4 2 4 3 4\"; frames = 3; //Output is 9 printHitsAndFaults(reference_string,frames); //Test 2: reference_string = \"2 5 10 1 2 2 6 9 1 2 10 2 6 1 2 1 6 9 5 1\"; frames = 4; //Output is 11 printHitsAndFaults(reference_string,frames); } //If page found, updates the second chance bit to true static boolean findAndUpdate(int x,int arr[], boolean second_chance[],int frames) { int i; for(i = 0; i < frames; i++) { if(arr[i] == x) { //Mark that the page deserves a second chance second_chance[i] = true; //Return 'true', that is there was a hit //and so there's no need to replace any page return true; } } //Return 'false' so that a page for replacement is selected //as he reuested page doesn't exist in memory return false; } //Updates the page in memory and returns the pointer static int replaceAndUpdate(int x,int arr[], boolean second_chance[],int frames,int pointer) { while(true) { //We found the page to replace if(!second_chance[pointer]) { //Replace with new page arr[pointer] = x; //Return updated pointer return (pointer+1)%frames; } //Mark it 'false' as it got one chance // and will be replaced next time unless accessed again second_chance[pointer] = false; //Pointer is updated in round robin manner pointer = (pointer+1)%frames; } } static void printHitsAndFaults(String reference_string, int frames) { int pointer,i,l,x,pf; //initially we consider frame 0 is to be replaced pointer = 0; //number of page faults pf = 0; //Create a array to hold page numbers int arr[] = new int[frames]; //No pages initially in frame, //which is indicated by -1 Arrays.fill(arr,-1); //Create second chance array. //Can also be a byte array for optimizing memory boolean second_chance[] = new boolean[frames]; //Split the string into tokens, //that is page numbers, based on space String str[] = reference_string.split(\" \"); //get the length of array l = str.length; for(i = 0; i<l; i++) { x = Integer.parseInt(str[i]); //Finds if there exists a need to replace //any page at all if(!findAndUpdate(x,arr,second_chance,frames)) { //Selects and updates a victim page pointer = replaceAndUpdate(x,arr, second_chance,frames,pointer); //Update page faults pf++; } } System.out.println(\"Total page faults were \"+pf); }}",
"e": 36662,
"s": 32959,
"text": null
},
{
"code": "# Python3 program to find largest in an array# without conditional/bitwise/ternary/ operators# and without library functions. # If page found, updates the second chance bit to truedef findAndUpdate(x, arr, second_chance, frames): for i in range(frames): if arr[i] == x: # Mark that the page deserves a second chance second_chance[i] = True # Return 'true', that is there was a hit #and so there's no need to replace any page return True # Return 'false' so that a page # for replacement is selected # as he reuested page doesn't # exist in memory return False # Updates the page in memory# and returns the pointerdef replaceAndUpdate(x, arr, second_chance, frames, pointer): while(True): # We found the page to replace if not second_chance[pointer]: # Replace with new page arr[pointer] = x #Return updated pointer return (pointer+1)%frames # Mark it 'false' as it got one chance # and will be replaced next time unless accessed again second_chance[pointer] = False # Pointer is updated in round robin manner pointer = (pointer + 1) % frames def printHitsAndFaults(reference_string, frames): # initially we consider # frame 0 is to be replaced pointer = 0 # number of page faults pf = 0 # Create a array to hold page numbers arr = [0]*frames # No pages initially in frame, # which is indicated by -1 for s in range(frames): arr[s] = -1 # Create second chance array. # Can also be a byte array for optimizing memory second_chance = [False]*frames # Split the string into tokens, # that is page numbers, based on space Str = reference_string.split(' ') # get the length of array l = len(Str) for i in range(l): x = Str[i] # Finds if there exists a need to replace # any page at all if not findAndUpdate(x,arr,second_chance,frames): # Selects and updates a victim page pointer = replaceAndUpdate(x,arr,second_chance,frames,pointer) # Update page faults pf += 1 print(\"Total page faults were\", pf) reference_string = \"\"frames = 0 # Test 1:reference_string = \"0 4 1 4 2 4 3 4 2 4 0 4 1 4 2 4 3 4\"frames = 3 # Output is 9printHitsAndFaults(reference_string,frames) # Test 2:reference_string = \"2 5 10 1 2 2 6 9 1 2 10 2 6 1 2 1 6 9 5 1\"frames = 4 # Output is 11printHitsAndFaults(reference_string,frames) # This code is contributed by mukesh07.",
"e": 39415,
"s": 36662,
"text": null
},
{
"code": "// C# program to find largest in an array// without conditional/bitwise/ternary/ operators// and without library functions.using System; public class secondChance{ public static void Main() { String reference_string = \"\"; int frames = 0; // Test 1: reference_string = \"0 4 1 4 2 4 3 4 2 4 0 4 1 4 2 4 3 4\"; frames = 3; // Output is 9 printHitsAndFaults(reference_string,frames); // Test 2: reference_string = \"2 5 10 1 2 2 6 9 1 2 10 2 6 1 2 1 6 9 5 1\"; frames = 4; // Output is 11 printHitsAndFaults(reference_string,frames); } // If page found, updates the second chance bit to true static bool findAndUpdate(int x,int []arr, bool []second_chance,int frames) { int i; for(i = 0; i < frames; i++) { if(arr[i] == x) { //Mark that the page deserves a second chance second_chance[i] = true; //Return 'true', that is there was a hit //and so there's no need to replace any page return true; } } // Return 'false' so that a page // for replacement is selected // as he reuested page doesn't // exist in memory return false; } // Updates the page in memory // and returns the pointer static int replaceAndUpdate(int x,int []arr, bool []second_chance,int frames,int pointer) { while(true) { //We found the page to replace if(!second_chance[pointer]) { //Replace with new page arr[pointer] = x; //Return updated pointer return (pointer+1)%frames; } //Mark it 'false' as it got one chance // and will be replaced next time unless accessed again second_chance[pointer] = false; //Pointer is updated in round robin manner pointer = (pointer + 1) % frames; } } static void printHitsAndFaults(String reference_string, int frames) { int pointer, i, l, x, pf; // initially we consider // frame 0 is to be replaced pointer = 0; // number of page faults pf = 0; // Create a array to hold page numbers int []arr = new int[frames]; // No pages initially in frame, // which is indicated by -1 for(int s = 0;s<frames;s++) arr[s]=-1; //Create second chance array. //Can also be a byte array for optimizing memory bool []second_chance = new bool[frames]; //Split the string into tokens, //that is page numbers, based on space String []str = reference_string.Split(); //get the length of array l = str.Length; for(i = 0; i < l; i++) { x = int.Parse(str[i]); //Finds if there exists a need to replace //any page at all if(!findAndUpdate(x,arr,second_chance,frames)) { //Selects and updates a victim page pointer = replaceAndUpdate(x,arr, second_chance,frames,pointer); //Update page faults pf++; } } Console.WriteLine(\"Total page faults were \"+pf); }} // This code has been contributed by 29AjayKumar",
"e": 43174,
"s": 39415,
"text": null
},
{
"code": "<script> // Javascript program to find largest in an array // without conditional/bitwise/ternary/ operators // and without library functions. // If page found, updates the second chance bit to true function findAndUpdate(x, arr, second_chance, frames) { let i; for(i = 0; i < frames; i++) { if(arr[i] == x) { //Mark that the page deserves a second chance second_chance[i] = true; //Return 'true', that is there was a hit //and so there's no need to replace any page return true; } } // Return 'false' so that a page // for replacement is selected // as he reuested page doesn't // exist in memory return false; } // Updates the page in memory // and returns the pointer function replaceAndUpdate(x, arr, second_chance, frames, pointer) { while(true) { //We found the page to replace if(!second_chance[pointer]) { //Replace with new page arr[pointer] = x; //Return updated pointer return (pointer+1)%frames; } //Mark it 'false' as it got one chance // and will be replaced next time unless accessed again second_chance[pointer] = false; //Pointer is updated in round robin manner pointer = (pointer + 1) % frames; } } function printHitsAndFaults(reference_string, frames) { let pointer, i, l, x, pf; // initially we consider // frame 0 is to be replaced pointer = 0; // number of page faults pf = 0; // Create a array to hold page numbers let arr = new Array(frames); arr.fill(0); // No pages initially in frame, // which is indicated by -1 for(let s = 0;s<frames;s++) arr[s]=-1; //Create second chance array. //Can also be a byte array for optimizing memory let second_chance = new Array(frames); second_chance.fill(false); //Split the string into tokens, //that is page numbers, based on space let str = reference_string.split(' '); //get the length of array l = str.length; for(i = 0; i < l; i++) { x = str[i]; //Finds if there exists a need to replace //any page at all if(!findAndUpdate(x,arr,second_chance,frames)) { //Selects and updates a victim page pointer = replaceAndUpdate(x,arr, second_chance,frames,pointer); //Update page faults pf++; } } document.write(\"Total page faults were \" + pf + \"</br>\"); } let reference_string = \"\"; let frames = 0; // Test 1: reference_string = \"0 4 1 4 2 4 3 4 2 4 0 4 1 4 2 4 3 4\"; frames = 3; // Output is 9 printHitsAndFaults(reference_string,frames); // Test 2: reference_string = \"2 5 10 1 2 2 6 9 1 2 10 2 6 1 2 1 6 9 5 1\"; frames = 4; // Output is 11 printHitsAndFaults(reference_string,frames); // This code is contributed by divyesh072019.</script>",
"e": 46735,
"s": 43174,
"text": null
},
{
"code": null,
"e": 46745,
"s": 46735,
"text": "Output: "
},
{
"code": null,
"e": 46796,
"s": 46745,
"text": "Total page faults were 9\nTotal page faults were 11"
},
{
"code": null,
"e": 46803,
"s": 46796,
"text": "Note: "
},
{
"code": null,
"e": 47276,
"s": 46803,
"text": "The arrays arr and second_chance can be replaced and combined together via a hashmap (with element as key, true/false as value) to speed up search.Time complexity of this method is O(Number_of_frames*reference_string_length) or O(mn) but since number of frames will be a constant in an Operating System (as main memory size is fixed), it is simply O(n) [Same as hashmap approach, but that will have lower constants]Second chance algorithm may suffer from Belady’s Anomaly."
},
{
"code": null,
"e": 47424,
"s": 47276,
"text": "The arrays arr and second_chance can be replaced and combined together via a hashmap (with element as key, true/false as value) to speed up search."
},
{
"code": null,
"e": 47693,
"s": 47424,
"text": "Time complexity of this method is O(Number_of_frames*reference_string_length) or O(mn) but since number of frames will be a constant in an Operating System (as main memory size is fixed), it is simply O(n) [Same as hashmap approach, but that will have lower constants]"
},
{
"code": null,
"e": 47751,
"s": 47693,
"text": "Second chance algorithm may suffer from Belady’s Anomaly."
},
{
"code": null,
"e": 47763,
"s": 47751,
"text": "29AjayKumar"
},
{
"code": null,
"e": 47776,
"s": 47763,
"text": "NikhilRathor"
},
{
"code": null,
"e": 47786,
"s": 47776,
"text": "code_rama"
},
{
"code": null,
"e": 47800,
"s": 47786,
"text": "divyesh072019"
},
{
"code": null,
"e": 47809,
"s": 47800,
"text": "mukesh07"
},
{
"code": null,
"e": 47818,
"s": 47809,
"text": "rkbhola5"
},
{
"code": null,
"e": 47854,
"s": 47818,
"text": "Operating Systems-Memory Management"
},
{
"code": null,
"e": 47872,
"s": 47854,
"text": "Operating Systems"
},
{
"code": null,
"e": 47890,
"s": 47872,
"text": "Operating Systems"
},
{
"code": null,
"e": 47988,
"s": 47890,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 48026,
"s": 47988,
"text": "Memory Management in Operating System"
},
{
"code": null,
"e": 48050,
"s": 48026,
"text": "File Allocation Methods"
},
{
"code": null,
"e": 48099,
"s": 48050,
"text": "Logical and Physical Address in Operating System"
},
{
"code": null,
"e": 48154,
"s": 48099,
"text": "Difference between Internal and External fragmentation"
},
{
"code": null,
"e": 48194,
"s": 48154,
"text": "File Access Methods in Operating System"
},
{
"code": null,
"e": 48242,
"s": 48194,
"text": "Memory Hierarchy Design and its Characteristics"
},
{
"code": null,
"e": 48288,
"s": 48242,
"text": "Process Table and Process Control Block (PCB)"
},
{
"code": null,
"e": 48353,
"s": 48288,
"text": "Program for Least Recently Used (LRU) Page Replacement algorithm"
},
{
"code": null,
"e": 48394,
"s": 48353,
"text": "States of a Process in Operating Systems"
}
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.