title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
get_window_position driver method - Selenium Python - GeeksforGeeks
|
15 May, 2020
Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies. Selenium WebDriver offers various useful methods to control the session, or in other words, browser. For example, adding a cookie, pressing back button, navigating among tabs, etc.
This article revolves around get_window_position driver method in Selenium. get_window_position method gets the x, y position of the current window.
Syntax –
driver.get_window_position(windowHandle='current')
Example –Now one can use get_window_position method as a driver method as below –
diver.get("https://www.geeksforgeeks.org/")
driver.get_window_position(windowHandle='current')
To demonstrate, get_window_position method of WebDriver in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on driver object. Let’s get window position,
Program –
# import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/") # get window positionprint(driver.get_window_position(windowHandle ='current'))
Output –Screenshot added –
Terminal output –
Python-selenium
selenium
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
|
[
{
"code": null,
"e": 26073,
"s": 26045,
"text": "\n15 May, 2020"
},
{
"code": null,
"e": 26812,
"s": 26073,
"text": "Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies. Selenium WebDriver offers various useful methods to control the session, or in other words, browser. For example, adding a cookie, pressing back button, navigating among tabs, etc."
},
{
"code": null,
"e": 26961,
"s": 26812,
"text": "This article revolves around get_window_position driver method in Selenium. get_window_position method gets the x, y position of the current window."
},
{
"code": null,
"e": 26970,
"s": 26961,
"text": "Syntax –"
},
{
"code": null,
"e": 27021,
"s": 26970,
"text": "driver.get_window_position(windowHandle='current')"
},
{
"code": null,
"e": 27103,
"s": 27021,
"text": "Example –Now one can use get_window_position method as a driver method as below –"
},
{
"code": null,
"e": 27199,
"s": 27103,
"text": "diver.get(\"https://www.geeksforgeeks.org/\")\ndriver.get_window_position(windowHandle='current')\n"
},
{
"code": null,
"e": 27376,
"s": 27199,
"text": "To demonstrate, get_window_position method of WebDriver in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on driver object. Let’s get window position,"
},
{
"code": null,
"e": 27386,
"s": 27376,
"text": "Program –"
},
{
"code": "# import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get(\"https://www.geeksforgeeks.org/\") # get window positionprint(driver.get_window_position(windowHandle ='current'))",
"e": 27642,
"s": 27386,
"text": null
},
{
"code": null,
"e": 27669,
"s": 27642,
"text": "Output –Screenshot added –"
},
{
"code": null,
"e": 27687,
"s": 27669,
"text": "Terminal output –"
},
{
"code": null,
"e": 27703,
"s": 27687,
"text": "Python-selenium"
},
{
"code": null,
"e": 27712,
"s": 27703,
"text": "selenium"
},
{
"code": null,
"e": 27719,
"s": 27712,
"text": "Python"
},
{
"code": null,
"e": 27817,
"s": 27719,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27835,
"s": 27817,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27870,
"s": 27835,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27902,
"s": 27870,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27924,
"s": 27902,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27966,
"s": 27924,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27996,
"s": 27966,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 28022,
"s": 27996,
"text": "Python String | replace()"
},
{
"code": null,
"e": 28051,
"s": 28022,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 28095,
"s": 28051,
"text": "Reading and Writing to text files in Python"
}
] |
ArrayList toArray() method in Java with Examples - GeeksforGeeks
|
20 Dec, 2018
The toArray() method of ArrayList is used to return an array containing all the elements in ArrayList in the correct order.
Syntax:
public Object[] toArray()
or
public <T> T[] toArray(T[] a)
Parameters: This method either accepts no parameters or it takes an array T[] a as parameter which is the array into which the elements of the list are to be stored, if it is big enough; otherwise, a new array of the same runtime type is allocated for this purpose.
Return Value: The function returns an array containing all the elements in this list.
Exception: The first overload of this method throws no exceptions. However, the second overload throws following exceptions:
ArrayStoreException: if the runtime type of the specified array is not a supertype of the runtime type of every element in this list.
NullPointerException if the specified array is null
Below programs illustrate the ArrayList.toArray() method:
Program 1:
// Java Program to illustrate the// ArrayList toArray() method in Java import java.util.*; public class GFG { public static void main(String[] args) { // create object of ArrayList ArrayList<Integer> ArrLis = new ArrayList<Integer>(); // Add elements ArrLis.add(32); ArrLis.add(67); ArrLis.add(98); ArrLis.add(100); // print ArrayList System.out.println("ArrayList: " + ArrLis); // Get the array of the elements // of the ArrayList // using toArray() method Object[] arr = ArrLis.toArray(); System.out.println("Elements of ArrayList" + " as Array: " + Arrays.toString(arr)); }}
ArrayList: [32, 67, 98, 100]
Elements of ArrayList as Array: [32, 67, 98, 100]
Program 2:
// Java Program to illustrate the// ArrayList toArray(T[]) method in Java import java.util.*; public class GFG { public static void main(String[] args) { // create object of ArrayList ArrayList<Integer> ArrLis = new ArrayList<Integer>(); // Add elements ArrLis.add(32); ArrLis.add(67); ArrLis.add(98); ArrLis.add(100); // print ArrayList System.out.println("ArrayList: " + ArrLis); // Get the array of the elements // of the ArrayList // using toArray(T[]) method Integer arr[] = new Integer[ArrLis.size()]; arr = ArrLis.toArray(arr); System.out.println("Elements of ArrayList" + " as Array: " + Arrays.toString(arr)); }}
ArrayList: [32, 67, 98, 100]
Elements of ArrayList as Array: [32, 67, 98, 100]
Reference:
https://docs.oracle.com/javase/9/docs/api/java/util/ArrayList.html#toArray–
https://docs.oracle.com/javase/9/docs/api/java/util/ArrayList.html#toArray-T:A-
Java - util package
Java-ArrayList
Java-Arrays
Java-Collections
Java-Functions
Picked
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Stream In Java
Interfaces in Java
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Singleton Class in Java
Multidimensional Arrays in Java
|
[
{
"code": null,
"e": 26335,
"s": 26307,
"text": "\n20 Dec, 2018"
},
{
"code": null,
"e": 26459,
"s": 26335,
"text": "The toArray() method of ArrayList is used to return an array containing all the elements in ArrayList in the correct order."
},
{
"code": null,
"e": 26467,
"s": 26459,
"text": "Syntax:"
},
{
"code": null,
"e": 26537,
"s": 26467,
"text": "public Object[] toArray()\n or\npublic <T> T[] toArray(T[] a)"
},
{
"code": null,
"e": 26803,
"s": 26537,
"text": "Parameters: This method either accepts no parameters or it takes an array T[] a as parameter which is the array into which the elements of the list are to be stored, if it is big enough; otherwise, a new array of the same runtime type is allocated for this purpose."
},
{
"code": null,
"e": 26889,
"s": 26803,
"text": "Return Value: The function returns an array containing all the elements in this list."
},
{
"code": null,
"e": 27014,
"s": 26889,
"text": "Exception: The first overload of this method throws no exceptions. However, the second overload throws following exceptions:"
},
{
"code": null,
"e": 27148,
"s": 27014,
"text": "ArrayStoreException: if the runtime type of the specified array is not a supertype of the runtime type of every element in this list."
},
{
"code": null,
"e": 27200,
"s": 27148,
"text": "NullPointerException if the specified array is null"
},
{
"code": null,
"e": 27258,
"s": 27200,
"text": "Below programs illustrate the ArrayList.toArray() method:"
},
{
"code": null,
"e": 27269,
"s": 27258,
"text": "Program 1:"
},
{
"code": "// Java Program to illustrate the// ArrayList toArray() method in Java import java.util.*; public class GFG { public static void main(String[] args) { // create object of ArrayList ArrayList<Integer> ArrLis = new ArrayList<Integer>(); // Add elements ArrLis.add(32); ArrLis.add(67); ArrLis.add(98); ArrLis.add(100); // print ArrayList System.out.println(\"ArrayList: \" + ArrLis); // Get the array of the elements // of the ArrayList // using toArray() method Object[] arr = ArrLis.toArray(); System.out.println(\"Elements of ArrayList\" + \" as Array: \" + Arrays.toString(arr)); }}",
"e": 28055,
"s": 27269,
"text": null
},
{
"code": null,
"e": 28135,
"s": 28055,
"text": "ArrayList: [32, 67, 98, 100]\nElements of ArrayList as Array: [32, 67, 98, 100]\n"
},
{
"code": null,
"e": 28146,
"s": 28135,
"text": "Program 2:"
},
{
"code": "// Java Program to illustrate the// ArrayList toArray(T[]) method in Java import java.util.*; public class GFG { public static void main(String[] args) { // create object of ArrayList ArrayList<Integer> ArrLis = new ArrayList<Integer>(); // Add elements ArrLis.add(32); ArrLis.add(67); ArrLis.add(98); ArrLis.add(100); // print ArrayList System.out.println(\"ArrayList: \" + ArrLis); // Get the array of the elements // of the ArrayList // using toArray(T[]) method Integer arr[] = new Integer[ArrLis.size()]; arr = ArrLis.toArray(arr); System.out.println(\"Elements of ArrayList\" + \" as Array: \" + Arrays.toString(arr)); }}",
"e": 28983,
"s": 28146,
"text": null
},
{
"code": null,
"e": 29063,
"s": 28983,
"text": "ArrayList: [32, 67, 98, 100]\nElements of ArrayList as Array: [32, 67, 98, 100]\n"
},
{
"code": null,
"e": 29074,
"s": 29063,
"text": "Reference:"
},
{
"code": null,
"e": 29150,
"s": 29074,
"text": "https://docs.oracle.com/javase/9/docs/api/java/util/ArrayList.html#toArray–"
},
{
"code": null,
"e": 29230,
"s": 29150,
"text": "https://docs.oracle.com/javase/9/docs/api/java/util/ArrayList.html#toArray-T:A-"
},
{
"code": null,
"e": 29250,
"s": 29230,
"text": "Java - util package"
},
{
"code": null,
"e": 29265,
"s": 29250,
"text": "Java-ArrayList"
},
{
"code": null,
"e": 29277,
"s": 29265,
"text": "Java-Arrays"
},
{
"code": null,
"e": 29294,
"s": 29277,
"text": "Java-Collections"
},
{
"code": null,
"e": 29309,
"s": 29294,
"text": "Java-Functions"
},
{
"code": null,
"e": 29316,
"s": 29309,
"text": "Picked"
},
{
"code": null,
"e": 29321,
"s": 29316,
"text": "Java"
},
{
"code": null,
"e": 29326,
"s": 29321,
"text": "Java"
},
{
"code": null,
"e": 29343,
"s": 29326,
"text": "Java-Collections"
},
{
"code": null,
"e": 29441,
"s": 29343,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29492,
"s": 29441,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 29522,
"s": 29492,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 29537,
"s": 29522,
"text": "Stream In Java"
},
{
"code": null,
"e": 29556,
"s": 29537,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 29587,
"s": 29556,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 29605,
"s": 29587,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 29637,
"s": 29605,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 29657,
"s": 29637,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 29681,
"s": 29657,
"text": "Singleton Class in Java"
}
] |
Splash Screen in Flutter
|
20 Jul, 2021
Splash Screen is the first screen that we see when we run our application. It is also known as Launch Screen. We will implement three basic methods to add a splash screen in our app.
In this method, we will create a splash screen with the help of the Timer() function.
How to Create a Splash Screen in Flutter App? | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersHow to Create a Splash Screen in Flutter App? | 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 / 14:21•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=XXISgdYHdYw" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
1. Create a new Flutter app using Command Prompt.
2. Delete the code from main.dart file and copy the below code.
main.dart
Dart
import 'dart:async';import 'package:flutter/material.dart';void main() { runApp(MyApp());} class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Splash Screen', theme: ThemeData( primarySwatch: Colors.green, ), home: MyHomePage(), debugShowCheckedModeBanner: false, ); }} class MyHomePage extends StatefulWidget { @override _MyHomePageState createState() => _MyHomePageState();}class _MyHomePageState extends State<MyHomePage> { @override void initState() { super.initState(); Timer(Duration(seconds: 3), ()=>Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) => SecondScreen() ) ) ); } @override Widget build(BuildContext context) { return Container( color: Colors.white, child:FlutterLogo(size:MediaQuery.of(context).size.height) ); }}class SecondScreen extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title:Text("GeeksForGeeks")), body: Center( child:Text("Home page",textScaleFactor: 2,) ), ); }}
Explanation of above code :
We have a main() function which calls runApp() by taking any widget as an argument to create the layout.
Then we have the home as MyHomePage() which is a stateful class(Mutable class).
MyHomePage() returns a Container which has a child as FlutterLogo(which will be shown initially when app starts).
Now, we have one most important method which is initState().
initState() method called once when the stateful widget is inserted in the widget tree.
initState() first call super.initState() and then Timer of duration 4 seconds(Timer function has 2 arguments,first is Duration and second is action to be performed). After 4 seconds,Current screen will be replaced by new Screen i.e. SecondScreen() .
We can also use Asset Image/Network Image instead of FlutterLogo.
Output:
In this method, we will create a splash screen using splashscreen package.
The constructor of the SplashScreen class :
SplashScreen({Color loaderColor,
int seconds,
double photoSize,
dynamic onClick,
dynamic navigateAfterSeconds,
Text title,
Color backgroundColor,
TextStyle styleTextUnderTheLoader,
Image image,
Text loadingText,
ImageProvider<dynamic> imageBackground,
Gradient gradientBackground})
Create a new Flutter Application.
Delete all the code from main.dart file for now.
Add the dependency to your pubspec.yaml file :
pubspec.yaml
Copy the below code :
main.dart
Dart
import 'dart:async';import 'package:flutter/material.dart';import 'package:splashscreen/splashscreen.dart';void main() { runApp(MyApp());} class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Splash Screen', theme: ThemeData( primarySwatch: Colors.green, ), home: Splash2(), debugShowCheckedModeBanner: false, ); }}class Splash2 extends StatelessWidget { @override Widget build(BuildContext context) { return SplashScreen( seconds: 6, navigateAfterSeconds: new SecondScreen(), title: new Text('GeeksForGeeks',textScaleFactor: 2,), image: new Image.network('https://www.geeksforgeeks.org/wp-content/uploads/gfg_200X200.png'), loadingText: Text("Loading"), photoSize: 100.0, loaderColor: Colors.blue, ); }}class SecondScreen extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title:Text("GeeksForGeeks")), body: Center( child:Text("Home page",textScaleFactor: 2,) ), ); }}
Explanation of above code :
We have home as Splash2() which is StatelessWidget class(Immutable class).
It return SplashScreen class which has so many properties like title, image,gradientBackground etc.
After completion of 6 seconds, it will navigate to a new screen i.e SecondScreen().
Output:
In this method, we will add a splash screen from the android folder.
1. Create a new flutter application.
2. Delete all the code from main.dart file and write your own code. For example purpose, we will use the below code :
main.dart
Dart
import 'dart:async';import 'package:flutter/material.dart';void main() { runApp(MyApp());} class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Splash Screen', theme: ThemeData( primarySwatch: Colors.green, ), home: Splash3(), debugShowCheckedModeBanner: false, ); }}class Splash3 extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title:Text("GeeksForGeeks")), body: Center( child:Text("Home page",textScaleFactor: 2,) ), ); }}
3. Currently, we have no splash screen.
4. Now, to add splash screen, go to android -> app -> src -> main -> res
5. Paste your asset image in a drawable folder for splash screen.
6. Open drawable folder and open launch_background.xml file.
7. Uncomment the item tag and add your asset image(android:src=”@drawable/YOUR_ASSET_IMAGE“) or you can copy the below code :
launch_background.xml
<?xml version="1.0" encoding="utf-8"?>
<!-- Modify this file to customize your launch splash screen -->
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@color/green" />
<!-- You can insert your own image assets here -->
<item>
<bitmap
android:gravity="center"
android:src="@drawable/bg" />
<!-- bg is asset image for splash screen -->
</item>
</layer-list>
Now, go to the values folder and modify styles.xml file. Delete the style tag with name=”NormalTheme“.After that,styles.xml file looks like this:
styles.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- Theme applied to the Android Window while the process is starting -->
<style name="LaunchTheme" parent="@android:style/Theme.Black.NoTitleBar">
<item name="android:windowBackground">@drawable/launch_background</item>
</style>
</resources>
8. Create a new file in the values folder with the name “color.xml”.
9. Paste the below code:
color.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name = "green">#808080</color>
</resources>
10. Now, the last step is to modify the content in AndroidManifest.xml file because we have made so many changes.
My app name is splash_screen so my package name is “com.example.splash_screen” and android:label=”splash_screen” . So make sure you have your correct package name and android:label in AndroidManifest.xml.
AndroidManifest.xml :
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.splash_screen">
<application
android:name="io.flutter.app.FlutterApplication"
android:label="splash_screen"
android:icon="@mipmap/ic_launcher">
<activity
android:name=".MainActivity"
android:launchMode="singleTop"
android:theme="@style/LaunchTheme"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
<meta-data
android:name="io.flutter.app.android.SplashScreenUntilFirstFrame"
android:value="true" />
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>
11. We have made all the necessary changes. Now, run the app to see the output :
Output:
Dart
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Flutter - Custom Bottom Navigation Bar
Flutter - Checkbox Widget
ListView Class in Flutter
Flutter - Stack Widget
Flutter - Search Bar
Flutter - FutureBuilder Widget
Flutter - Flexible Widget
Operators in Dart
Flutter - ListTile Widget
Flutter - Dialogs
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n20 Jul, 2021"
},
{
"code": null,
"e": 235,
"s": 52,
"text": "Splash Screen is the first screen that we see when we run our application. It is also known as Launch Screen. We will implement three basic methods to add a splash screen in our app."
},
{
"code": null,
"e": 321,
"s": 235,
"text": "In this method, we will create a splash screen with the help of the Timer() function."
},
{
"code": null,
"e": 1230,
"s": 321,
"text": "How to Create a Splash Screen in Flutter App? | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersHow to Create a Splash Screen in Flutter App? | 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 / 14:21•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=XXISgdYHdYw\" 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": 1280,
"s": 1230,
"text": "1. Create a new Flutter app using Command Prompt."
},
{
"code": null,
"e": 1344,
"s": 1280,
"text": "2. Delete the code from main.dart file and copy the below code."
},
{
"code": null,
"e": 1354,
"s": 1344,
"text": "main.dart"
},
{
"code": null,
"e": 1359,
"s": 1354,
"text": "Dart"
},
{
"code": "import 'dart:async';import 'package:flutter/material.dart';void main() { runApp(MyApp());} class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Splash Screen', theme: ThemeData( primarySwatch: Colors.green, ), home: MyHomePage(), debugShowCheckedModeBanner: false, ); }} class MyHomePage extends StatefulWidget { @override _MyHomePageState createState() => _MyHomePageState();}class _MyHomePageState extends State<MyHomePage> { @override void initState() { super.initState(); Timer(Duration(seconds: 3), ()=>Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) => SecondScreen() ) ) ); } @override Widget build(BuildContext context) { return Container( color: Colors.white, child:FlutterLogo(size:MediaQuery.of(context).size.height) ); }}class SecondScreen extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title:Text(\"GeeksForGeeks\")), body: Center( child:Text(\"Home page\",textScaleFactor: 2,) ), ); }}",
"e": 2767,
"s": 1359,
"text": null
},
{
"code": null,
"e": 2795,
"s": 2767,
"text": "Explanation of above code :"
},
{
"code": null,
"e": 2900,
"s": 2795,
"text": "We have a main() function which calls runApp() by taking any widget as an argument to create the layout."
},
{
"code": null,
"e": 2980,
"s": 2900,
"text": "Then we have the home as MyHomePage() which is a stateful class(Mutable class)."
},
{
"code": null,
"e": 3094,
"s": 2980,
"text": "MyHomePage() returns a Container which has a child as FlutterLogo(which will be shown initially when app starts)."
},
{
"code": null,
"e": 3155,
"s": 3094,
"text": "Now, we have one most important method which is initState()."
},
{
"code": null,
"e": 3243,
"s": 3155,
"text": "initState() method called once when the stateful widget is inserted in the widget tree."
},
{
"code": null,
"e": 3493,
"s": 3243,
"text": "initState() first call super.initState() and then Timer of duration 4 seconds(Timer function has 2 arguments,first is Duration and second is action to be performed). After 4 seconds,Current screen will be replaced by new Screen i.e. SecondScreen() ."
},
{
"code": null,
"e": 3559,
"s": 3493,
"text": "We can also use Asset Image/Network Image instead of FlutterLogo."
},
{
"code": null,
"e": 3567,
"s": 3559,
"text": "Output:"
},
{
"code": null,
"e": 3642,
"s": 3567,
"text": "In this method, we will create a splash screen using splashscreen package."
},
{
"code": null,
"e": 3686,
"s": 3642,
"text": "The constructor of the SplashScreen class :"
},
{
"code": null,
"e": 3979,
"s": 3686,
"text": "SplashScreen({Color loaderColor,\nint seconds, \ndouble photoSize, \ndynamic onClick, \ndynamic navigateAfterSeconds, \nText title, \nColor backgroundColor, \nTextStyle styleTextUnderTheLoader, \nImage image, \nText loadingText, \nImageProvider<dynamic> imageBackground, \nGradient gradientBackground})\n"
},
{
"code": null,
"e": 4013,
"s": 3979,
"text": "Create a new Flutter Application."
},
{
"code": null,
"e": 4062,
"s": 4013,
"text": "Delete all the code from main.dart file for now."
},
{
"code": null,
"e": 4109,
"s": 4062,
"text": "Add the dependency to your pubspec.yaml file :"
},
{
"code": null,
"e": 4122,
"s": 4109,
"text": "pubspec.yaml"
},
{
"code": null,
"e": 4144,
"s": 4122,
"text": "Copy the below code :"
},
{
"code": null,
"e": 4154,
"s": 4144,
"text": "main.dart"
},
{
"code": null,
"e": 4159,
"s": 4154,
"text": "Dart"
},
{
"code": "import 'dart:async';import 'package:flutter/material.dart';import 'package:splashscreen/splashscreen.dart';void main() { runApp(MyApp());} class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Splash Screen', theme: ThemeData( primarySwatch: Colors.green, ), home: Splash2(), debugShowCheckedModeBanner: false, ); }}class Splash2 extends StatelessWidget { @override Widget build(BuildContext context) { return SplashScreen( seconds: 6, navigateAfterSeconds: new SecondScreen(), title: new Text('GeeksForGeeks',textScaleFactor: 2,), image: new Image.network('https://www.geeksforgeeks.org/wp-content/uploads/gfg_200X200.png'), loadingText: Text(\"Loading\"), photoSize: 100.0, loaderColor: Colors.blue, ); }}class SecondScreen extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title:Text(\"GeeksForGeeks\")), body: Center( child:Text(\"Home page\",textScaleFactor: 2,) ), ); }}",
"e": 5262,
"s": 4159,
"text": null
},
{
"code": null,
"e": 5290,
"s": 5262,
"text": "Explanation of above code :"
},
{
"code": null,
"e": 5365,
"s": 5290,
"text": "We have home as Splash2() which is StatelessWidget class(Immutable class)."
},
{
"code": null,
"e": 5465,
"s": 5365,
"text": "It return SplashScreen class which has so many properties like title, image,gradientBackground etc."
},
{
"code": null,
"e": 5549,
"s": 5465,
"text": "After completion of 6 seconds, it will navigate to a new screen i.e SecondScreen()."
},
{
"code": null,
"e": 5557,
"s": 5549,
"text": "Output:"
},
{
"code": null,
"e": 5626,
"s": 5557,
"text": "In this method, we will add a splash screen from the android folder."
},
{
"code": null,
"e": 5663,
"s": 5626,
"text": "1. Create a new flutter application."
},
{
"code": null,
"e": 5781,
"s": 5663,
"text": "2. Delete all the code from main.dart file and write your own code. For example purpose, we will use the below code :"
},
{
"code": null,
"e": 5791,
"s": 5781,
"text": "main.dart"
},
{
"code": null,
"e": 5796,
"s": 5791,
"text": "Dart"
},
{
"code": "import 'dart:async';import 'package:flutter/material.dart';void main() { runApp(MyApp());} class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Splash Screen', theme: ThemeData( primarySwatch: Colors.green, ), home: Splash3(), debugShowCheckedModeBanner: false, ); }}class Splash3 extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title:Text(\"GeeksForGeeks\")), body: Center( child:Text(\"Home page\",textScaleFactor: 2,) ), ); }}",
"e": 6413,
"s": 5796,
"text": null
},
{
"code": null,
"e": 6453,
"s": 6413,
"text": "3. Currently, we have no splash screen."
},
{
"code": null,
"e": 6526,
"s": 6453,
"text": "4. Now, to add splash screen, go to android -> app -> src -> main -> res"
},
{
"code": null,
"e": 6592,
"s": 6526,
"text": "5. Paste your asset image in a drawable folder for splash screen."
},
{
"code": null,
"e": 6654,
"s": 6592,
"text": "6. Open drawable folder and open launch_background.xml file. "
},
{
"code": null,
"e": 6780,
"s": 6654,
"text": "7. Uncomment the item tag and add your asset image(android:src=”@drawable/YOUR_ASSET_IMAGE“) or you can copy the below code :"
},
{
"code": null,
"e": 6802,
"s": 6780,
"text": "launch_background.xml"
},
{
"code": null,
"e": 7262,
"s": 6802,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<!-- Modify this file to customize your launch splash screen -->\n<layer-list xmlns:android=\"http://schemas.android.com/apk/res/android\">\n <item android:drawable=\"@color/green\" />\n\n <!-- You can insert your own image assets here -->\n <item>\n <bitmap\n android:gravity=\"center\"\n android:src=\"@drawable/bg\" />\n <!-- bg is asset image for splash screen -->\n </item>\n</layer-list>\n\n"
},
{
"code": null,
"e": 7408,
"s": 7262,
"text": "Now, go to the values folder and modify styles.xml file. Delete the style tag with name=”NormalTheme“.After that,styles.xml file looks like this:"
},
{
"code": null,
"e": 7419,
"s": 7408,
"text": "styles.xml"
},
{
"code": null,
"e": 7736,
"s": 7419,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<resources>\n <!-- Theme applied to the Android Window while the process is starting -->\n <style name=\"LaunchTheme\" parent=\"@android:style/Theme.Black.NoTitleBar\">\n <item name=\"android:windowBackground\">@drawable/launch_background</item>\n </style>\n</resources>\n\n"
},
{
"code": null,
"e": 7805,
"s": 7736,
"text": "8. Create a new file in the values folder with the name “color.xml”."
},
{
"code": null,
"e": 7830,
"s": 7805,
"text": "9. Paste the below code:"
},
{
"code": null,
"e": 7840,
"s": 7830,
"text": "color.xml"
},
{
"code": null,
"e": 7943,
"s": 7840,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<resources>\n<color name = \"green\">#808080</color>\n</resources>\n"
},
{
"code": null,
"e": 8057,
"s": 7943,
"text": "10. Now, the last step is to modify the content in AndroidManifest.xml file because we have made so many changes."
},
{
"code": null,
"e": 8262,
"s": 8057,
"text": "My app name is splash_screen so my package name is “com.example.splash_screen” and android:label=”splash_screen” . So make sure you have your correct package name and android:label in AndroidManifest.xml."
},
{
"code": null,
"e": 8284,
"s": 8262,
"text": "AndroidManifest.xml :"
},
{
"code": null,
"e": 9364,
"s": 8284,
"text": "<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"com.example.splash_screen\">\n <application\n android:name=\"io.flutter.app.FlutterApplication\"\n android:label=\"splash_screen\"\n android:icon=\"@mipmap/ic_launcher\">\n <activity\n android:name=\".MainActivity\"\n android:launchMode=\"singleTop\"\n android:theme=\"@style/LaunchTheme\"\n android:configChanges=\"orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode\"\n android:hardwareAccelerated=\"true\"\n android:windowSoftInputMode=\"adjustResize\">\n <meta-data\n android:name=\"io.flutter.app.android.SplashScreenUntilFirstFrame\"\n android:value=\"true\" />\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\n"
},
{
"code": null,
"e": 9445,
"s": 9364,
"text": "11. We have made all the necessary changes. Now, run the app to see the output :"
},
{
"code": null,
"e": 9453,
"s": 9445,
"text": "Output:"
},
{
"code": null,
"e": 9458,
"s": 9453,
"text": "Dart"
},
{
"code": null,
"e": 9556,
"s": 9458,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9595,
"s": 9556,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 9621,
"s": 9595,
"text": "Flutter - Checkbox Widget"
},
{
"code": null,
"e": 9647,
"s": 9621,
"text": "ListView Class in Flutter"
},
{
"code": null,
"e": 9670,
"s": 9647,
"text": "Flutter - Stack Widget"
},
{
"code": null,
"e": 9691,
"s": 9670,
"text": "Flutter - Search Bar"
},
{
"code": null,
"e": 9722,
"s": 9691,
"text": "Flutter - FutureBuilder Widget"
},
{
"code": null,
"e": 9748,
"s": 9722,
"text": "Flutter - Flexible Widget"
},
{
"code": null,
"e": 9766,
"s": 9748,
"text": "Operators in Dart"
},
{
"code": null,
"e": 9792,
"s": 9766,
"text": "Flutter - ListTile Widget"
}
] |
Python | Pandas Series.str.pad()
|
17 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 provide a method to add padding (whitespaces or other characters) to every string element in a series. .str has to be prefixed every time before calling this method to differentiate it from the Python’s default function otherwise, it will throw error.
Syntax: Series.str.pad(width, side=’left’, fillchar=’ ‘)
Parameters:width: Minimum width of resulting string.
If width is less than or equal to length of string, no padding is added.
If width is more than the string length, the extra space is filled with whitespaces or passed character.
side: string input ( ‘left’, ‘right’ or ‘both’). Default is ‘left’. Padding will be added equally on respective side.fillchar: Character to be padded. Default is ‘ ‘(White space).
Return Type: Series with added spaces/characters on the passed side of string
To download the CSV used in code, click here.
In the following examples, the data frame used contains data of some NBA players. str.pad() method will be used to add padding to the text. The image of data frame before any operations is shown below:
Example #1: Left padding
In this example, a minimum length of string is set at 15 and whitespaces are added to left side of string in Team column using the str.pad() method. Since white spaces can’t be seen, they are compared with custom input string and the result is checked if it’s True or not for team name “Boston Celtics” only.
# importing pandas moduleimport pandas as pd # making data frame from csv at urldata = pd.read_csv("https://media.geeksforgeeks.org/wp-content/upload/nba.csv") # removing null values to avoid errorsdata.dropna(how ='all', inplace = True) # adding white spaces to left sidedata["Team"]= data["Team"].str.pad(15, side ='left') # custom stringstring =' Boston Celtics' # checking if same or notdata["Team"]== string
Output:As shown in the output image, the condition is True for team name Boston Celtics which means spaces were added successfully. Similarly the other strings are also padded according to their length.
Example #2: Right padding
In this example, a minimum length of string is set at 15 and ‘_’ are added to right side of string in Team column using the str.pad() method. ‘_’ is passed to fillchar parameters to add it instead of default whitespaces.
# importing pandas moduleimport pandas as pd # making data framedata = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv") # removing null values to avoid errorsdata.dropna(how ='all', inplace = True) # adding white spaces to left sidedata["Team"]= data["Team"].str.pad(15, side ='right', fillchar ='_') # output displaydata
Output:As shown in the output image, ‘_’ has been added to right side of string depending upon length of the string. After padding, the length of each string is 15.
Example 3: Both side padding
In this example, ‘+’ has been added to both side of string using fillchar parameter in str.pad(). The width parameter is set to 20, so that the length of each string after padding becomes same.
# importing pandas moduleimport pandas as pd # making data framedata = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv") # removing null values to avoid errorsdata.dropna(how ='all', inplace = True) # adding white spaces to left sidedata["Name"]= data["Name"].str.pad(20, side ='both', fillchar ='+') # outputdata
Output:As shown in the output image, ‘+’ was added to both side of the string. The number of ‘+’ sign in each string may differ, but after padding the length of each string is 20.
Note: As it can be seen in the image, if the string has odd number of places left (width – length), then the priority is given to right side. Hence, the one left character will be added to the right side.
As in the first row of name column, Length of string was 13. So 20-13 = 7. Hence 3 ‘+’ are added to left side and ‘4’ to the right.
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
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": 28,
"s": 0,
"text": "\n17 Sep, 2018"
},
{
"code": null,
"e": 242,
"s": 28,
"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": 501,
"s": 242,
"text": "Pandas provide a method to add padding (whitespaces or other characters) to every string element in a series. .str has to be prefixed every time before calling this method to differentiate it from the Python’s default function otherwise, it will throw error."
},
{
"code": null,
"e": 558,
"s": 501,
"text": "Syntax: Series.str.pad(width, side=’left’, fillchar=’ ‘)"
},
{
"code": null,
"e": 611,
"s": 558,
"text": "Parameters:width: Minimum width of resulting string."
},
{
"code": null,
"e": 684,
"s": 611,
"text": "If width is less than or equal to length of string, no padding is added."
},
{
"code": null,
"e": 789,
"s": 684,
"text": "If width is more than the string length, the extra space is filled with whitespaces or passed character."
},
{
"code": null,
"e": 969,
"s": 789,
"text": "side: string input ( ‘left’, ‘right’ or ‘both’). Default is ‘left’. Padding will be added equally on respective side.fillchar: Character to be padded. Default is ‘ ‘(White space)."
},
{
"code": null,
"e": 1047,
"s": 969,
"text": "Return Type: Series with added spaces/characters on the passed side of string"
},
{
"code": null,
"e": 1093,
"s": 1047,
"text": "To download the CSV used in code, click here."
},
{
"code": null,
"e": 1295,
"s": 1093,
"text": "In the following examples, the data frame used contains data of some NBA players. str.pad() method will be used to add padding to the text. The image of data frame before any operations is shown below:"
},
{
"code": null,
"e": 1322,
"s": 1297,
"text": "Example #1: Left padding"
},
{
"code": null,
"e": 1631,
"s": 1322,
"text": "In this example, a minimum length of string is set at 15 and whitespaces are added to left side of string in Team column using the str.pad() method. Since white spaces can’t be seen, they are compared with custom input string and the result is checked if it’s True or not for team name “Boston Celtics” only."
},
{
"code": "# importing pandas moduleimport pandas as pd # making data frame from csv at urldata = pd.read_csv(\"https://media.geeksforgeeks.org/wp-content/upload/nba.csv\") # removing null values to avoid errorsdata.dropna(how ='all', inplace = True) # adding white spaces to left sidedata[\"Team\"]= data[\"Team\"].str.pad(15, side ='left') # custom stringstring =' Boston Celtics' # checking if same or notdata[\"Team\"]== string",
"e": 2049,
"s": 1631,
"text": null
},
{
"code": null,
"e": 2252,
"s": 2049,
"text": "Output:As shown in the output image, the condition is True for team name Boston Celtics which means spaces were added successfully. Similarly the other strings are also padded according to their length."
},
{
"code": null,
"e": 2279,
"s": 2252,
"text": " Example #2: Right padding"
},
{
"code": null,
"e": 2500,
"s": 2279,
"text": "In this example, a minimum length of string is set at 15 and ‘_’ are added to right side of string in Team column using the str.pad() method. ‘_’ is passed to fillchar parameters to add it instead of default whitespaces."
},
{
"code": "# importing pandas moduleimport pandas as pd # making data framedata = pd.read_csv(\"https://media.geeksforgeeks.org/wp-content/uploads/nba.csv\") # removing null values to avoid errorsdata.dropna(how ='all', inplace = True) # adding white spaces to left sidedata[\"Team\"]= data[\"Team\"].str.pad(15, side ='right', fillchar ='_') # output displaydata",
"e": 2851,
"s": 2500,
"text": null
},
{
"code": null,
"e": 3016,
"s": 2851,
"text": "Output:As shown in the output image, ‘_’ has been added to right side of string depending upon length of the string. After padding, the length of each string is 15."
},
{
"code": null,
"e": 3046,
"s": 3016,
"text": " Example 3: Both side padding"
},
{
"code": null,
"e": 3240,
"s": 3046,
"text": "In this example, ‘+’ has been added to both side of string using fillchar parameter in str.pad(). The width parameter is set to 20, so that the length of each string after padding becomes same."
},
{
"code": "# importing pandas moduleimport pandas as pd # making data framedata = pd.read_csv(\"https://media.geeksforgeeks.org/wp-content/uploads/nba.csv\") # removing null values to avoid errorsdata.dropna(how ='all', inplace = True) # adding white spaces to left sidedata[\"Name\"]= data[\"Name\"].str.pad(20, side ='both', fillchar ='+') # outputdata",
"e": 3582,
"s": 3240,
"text": null
},
{
"code": null,
"e": 3762,
"s": 3582,
"text": "Output:As shown in the output image, ‘+’ was added to both side of the string. The number of ‘+’ sign in each string may differ, but after padding the length of each string is 20."
},
{
"code": null,
"e": 3967,
"s": 3762,
"text": "Note: As it can be seen in the image, if the string has odd number of places left (width – length), then the priority is given to right side. Hence, the one left character will be added to the right side."
},
{
"code": null,
"e": 4099,
"s": 3967,
"text": "As in the first row of name column, Length of string was 13. So 20-13 = 7. Hence 3 ‘+’ are added to left side and ‘4’ to the right."
},
{
"code": null,
"e": 4120,
"s": 4099,
"text": "Python pandas-series"
},
{
"code": null,
"e": 4149,
"s": 4120,
"text": "Python pandas-series-methods"
},
{
"code": null,
"e": 4163,
"s": 4149,
"text": "Python-pandas"
},
{
"code": null,
"e": 4170,
"s": 4163,
"text": "Python"
},
{
"code": null,
"e": 4268,
"s": 4170,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4300,
"s": 4268,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 4327,
"s": 4300,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 4348,
"s": 4327,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 4371,
"s": 4348,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 4427,
"s": 4371,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 4458,
"s": 4427,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 4500,
"s": 4458,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 4542,
"s": 4500,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 4581,
"s": 4542,
"text": "Python | Get unique values from a list"
}
] |
What Are the Tidyverse Packages in R Language?
|
03 Dec, 2021
When dealing with Data Science in R, the Tidyverse packages are your best friends! These Tidyverse packages were specially designed for Data Science with a common design philosophy. They include all the packages required in the data science workflow, ranging from data exploration to data visualization. For example, readr is for data importing, tibble and tidyr help in tidying the data, dplyr and stringr contribute to data transformation and ggplot2 is vital for data visualization.
There are eight core Tidyverse packages namely ggplot2, dplyr, tidyr, readr, purrr, tibble, stringr, and forcats that are mentioned in this article. All of these packages are loaded automatically at once with the install.packages(“tidyverse”) command. In addition to these packages, Tidyverse also has some specialized packages that are not loaded automatically but need their own call. These include the DBI for relational databases. httr for web APIs, rvest for web scraping, etc. Now, let’s see the core Tidyverse packages and learn more about them.
Data Visualization and Explorationggplot2Data Wrangling and TransformationdplyrtidyrstringrforcatsData Import and ManagementtibblereadrFunctional Programmingpurrr
Data Visualization and Explorationggplot2
ggplot2
Data Wrangling and Transformationdplyrtidyrstringrforcats
dplyr
tidyr
stringr
forcats
Data Import and Managementtibblereadr
tibble
readr
Functional Programmingpurrr
purrr
ggplot2 is an R data visualization library that is based on The Grammar of Graphics. ggplot2 can create data visualizations such as bar charts, pie charts, histograms, scatterplots, error charts, etc. using high-level API. It also allows you to add different types of data visualization components or layers in a single visualization. Once ggplot2 has been told which variables to map to which aesthetics in the plot, it does the rest of the work so that the user can focus on interpreting the visualizations and take less time in creating them. But this also means that it is not possible to create highly customized graphics in ggplot2. But there are a lot of resources in the RStudio community and Stack Overflow which can provide help in ggplot2 when needed.
If you want to install ggplot2, the best method is to install the tidyverse using:
install.packages("tidyverse")
Or you can just install ggplot2 using:
install.packages("ggplot2")
You can also install the development version from GitHub using:
devtools::install_github("tidyverse/ggplot2")
Example:
We will be using 6 different data points for the bar plot and then with the help of the fill argument within the aes function, we will be applying the default colors to the barplot in the R programming language.
R
# load the librarylibrary("ggplot2") # create the dataframe with letters and numbersgfg < -data.frame( x=c('A', 'B', 'C', 'D', 'E', 'F'), y=c(4, 6, 2, 9, 7, 3)) # display the barggplot(gfg, aes(x, y, fill=x)) + geom_bar(stat="identity")
Output:
dplyr is a very popular data manipulation library in R. It has five important functions that are combined naturally with the group_by() function that can help in performing these functions in groups. These functions include the mutate() function which can add new variables that are functions of existing variables, select() function that selects the variables based on their names, filter() function that picks selects the variables based on their values, summarise() function that reduces multiple values into a summary, and the arrange() function that arranges the arranges the row orderings. If you want to install dplyr, the best method is to install the tidyverse using:
install.packages("tidyverse")
Or you can just install dplyr using:
install.packages("dplyr")
You can also install the development version from GitHub using:
devtools::install_github("tidyverse/dplyr")
Example:
R
library(dplyr) print(starwars %>% filter(species == "Droid"))
Output:
# A tibble: 6 x 14
name height mass hair_color skin_color eye_color birth_year sex gender
<chr> <int> <dbl> <chr> <chr> <chr> <dbl> <chr> <chr>
1 C-3PO 167 75 <NA> gold yellow 112 none masculi~
2 R2-D2 96 32 <NA> white, blue red 33 none masculi~
3 R5-D4 97 32 <NA> white, red red NA none masculi~
4 IG-88 200 140 none metal red 15 none masculi~
5 R4-P17 96 NA none silver, red red, blue NA none feminine
6 BB8 NA NA none none black NA none masculi~
# ... with 5 more variables: homeworld <chr>, species <chr>, films <list>,
# vehicles <list>, starships <list>
tidyr is a data cleaning library in R which helps to create tidy data. Tidy data means that all the data cells have a single value with each of the data columns being a variable and the data rows being an observation. This tidy data is a staple in the tidyverse and it ensures that more time is spent on data analysis and to obtain value from data rather than cleaning the data continuously and modifying the tools to handle untidy data. The functions in tidyr broadly fall into five categories namely, Pivoting which changes the data between long and wide forms, Nesting which changes grouped data so that a group is a single row with a nested data frame, Splitting character columns and then combining them, Rectangling which converts nested lists into tidy tibbles and converting implicit missing values into explicit values. If you want to install tidyr, the best method is to install the tidyverse using:
install.packages("tidyverse")
Or you can just install tidyr using:
install.packages("tidyr")
You can also install the development version from GitHub using:
devtools::install_github("tidyverse/tidyr")
Example:
The gather() function in tidr will take multiple columns and collapse them into key-value pairs, duplicating all other columns as needed.
R
# load the tidyr packagelibrary(tidyr) n = 10# creating a data frametidy_dataframe = data.frame( S.No = c(1:n), Group.1 = c(23, 345, 76, 212, 88, 199, 72, 35, 90, 265), Group.2 = c(117, 89, 66, 334, 90, 101, 178, 233, 45, 200), Group.3 = c(29, 101, 239, 289, 176, 320, 89, 109, 199, 56)) # print the elements of the data frameprint(head(tidy_dataframe)) # using gather() function on tidy_dataframelong <- tidy_dataframe %>% gather(Group, Frequency, Group.1:Group.3) # print the data frame in a long formatprint(head(long))
Output:
S.No Group.1 Group.2 Group.3
1 1 23 117 29
2 2 345 89 101
3 3 76 66 239
4 4 212 334 289
5 5 88 90 176
6 6 199 101 320
S.No Group Frequency
1 1 Group.1 23
2 2 Group.1 345
3 3 Group.1 76
4 4 Group.1 212
5 5 Group.1 88
6 6 Group.1 199
stringr is a library that has many functions used for data cleaning and data preparation tasks. It is also designed for working with strings and has many functions that make this an easy process. stringr is built on top of stringi, which is an International Components for Unicode C library. So if there are any functions that you want to use but cannot find in stringr, then the best place to look for them is stringi. This also means that once you master stringr, stringi is not that difficult to use as both of these packages have similar conventions. All of the functions in stringr start with str and they take a string vector as their first argument. Some of these functions include str_detect(), str_extract(), str_match(), str_count(), str_replace(), str_subset(), etc. If you want to install stringr, the best method is to install the tidyverse using:
install.packages("tidyverse")
Or you can just install stringr from CRAN using:
install.packages("stringr")
You can also install the development version from GitHub using:
devtools::install_github("tidyverse/stringr")
Example:
R
# R program for finding length of string # Importing packagelibrary(stringr) # Calculating length of string str_length("hello")
Output:
5
forcats is a R library that is concerned with handling problems associated with vectors. These vectors are variables that have a fixed set of possible values they can take which is already known in advance. So forecats deals with issues like changes the orders of values in vectors, reordering the vectors, etc. Some of the functions in forcats are fct_relevel() that reorders a vectors by hand, fct_reorder() that reorders a factor using another variable, fct_infreq() that reorders a factorby frequency values etc. If you want to install forcats, the best method is to install the tidyverse using:
install.packages("tidyverse")
Or you can just install forcats from using:
install.packages("forcats")
You can also install the development version from GitHub using:
devtools::install_github("tidyverse/forcats")
Example:
R
library(forcats)library(dplyr)library(ggplot2) print(head(starwars %>% filter(!is.na(species)) %>% count(species, sort = TRUE)))
Output:
# A tibble: 6 x 2
species n
<chr> <int>
1 Human 35
2 Droid 6
3 Gungan 3
4 Kaminoan 2
5 Mirialan 2
6 Twi'lek 2
This library provides a simple and speedy method to read rectangular data such as that with file formats tsv, csv, delim, fwf, etc. readr can parse many different types of data using a function that parses the total file and another that focuses on the specific column. This column specification defines the method to convert the data in the column from a character vector to the data type that is most suited. This is done automatically by readr in most cases. readr can read different kinds of file formats using different functions, namely read_csv() for comma-separated files, read_tsv() for tab-separated files, read_table() for tabular files, read_fwf() for fixed-width files, read_delim() for delimited files, and, read_log() for web log files. If you want to install readr, the best method is to install the tidyverse using:
install.packages("tidyverse").
Or you can just install readr using:
install.packages("readr").
You can also install the development version from GitHub using:
devtools::install_github("tidyverse/readr")
Example:
Reading file with readr library.
R
# R program to read text file# using readr package # Import the readr librarylibrary(readr) # Use read_tsv() to read text filemyData = read_tsv("geeksforgeeks.txt", col_names = FALSE)print(myData)
Output:
# A tibble: 1 x 1
X1
1 A computer science portal for geeks.
A tibble is a form of a data.frame which includes the useful parts of it and discards the parts that are not so important. So tibbles don’t change variables names or types like data.frames nor do they do partial matching but they bring problems to the forefront much sooner such as when a variable does not exist. So a code with tibbles is much cleaner and effective than before. Tibbles is also easier to use with larger datasets that contain more complex objects, in part before an enhanced print() method. You can create new tibbles from column vectors using the tibble() function and you can also create a tibble row-by-row using a tribble() function. If you want to install tibble, the best method is to install the tidyverse using:
install.packages("tidyverse"):
Or you can just install tibble using:
install.packages("tibble")
You can also install the development version from GitHub using:
devtools::install_github("tidyverse/tibble")
Example:
R
library(tibble)data <- data.frame(a = 1:3, b = letters[1:3], c = Sys.Date() - 1:3)print(data)
Output:
a b c
1 1 a 2021-11-24
2 2 b 2021-11-23
3 3 c 2021-11-22
Purrr is a detailed set of tools for functions and vectors and it is mainly used to manage the functional programming in R. A good example of this is the map() functions that are used to replace multiple for loops that complicate and mess up the code inro simpler code that is easy to read. In addition to that, all purrr functions are type-stable which means they either return the advertised output type and if that is not possible, then the give an error. If you want to install purrr, the best method is to install the tidyverse using:
install.packages("tidyverse")
Or you can just install purrr using:
install.packages("purrr")
You can also install the development version from GitHub using:
devtools::install_github("tidyverse/purrr")
Example:
R
library(purrr) mtcars %>% split(.$cyl) %>% # from base R map(~ lm(mpg ~ wt, data = .)) %>% map(summary) %>% map_dbl("r.squared")
Output:
4
0.50863259632314
6
0.464510150550548
8
0.422965536496112
anikakapoor
kumar_satyam
GBlog
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DSA Sheet by Love Babbar
Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ...
GEEK-O-LYMPICS 2022 - May The Geeks Force Be With You!
Geek Streak - 24 Days POTD Challenge
Practice for cracking any coding interview
Change column name of a given DataFrame in R
Filter data by multiple conditions in R using Dplyr
How to Replace specific values in column in R DataFrame ?
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n03 Dec, 2021"
},
{
"code": null,
"e": 514,
"s": 28,
"text": "When dealing with Data Science in R, the Tidyverse packages are your best friends! These Tidyverse packages were specially designed for Data Science with a common design philosophy. They include all the packages required in the data science workflow, ranging from data exploration to data visualization. For example, readr is for data importing, tibble and tidyr help in tidying the data, dplyr and stringr contribute to data transformation and ggplot2 is vital for data visualization."
},
{
"code": null,
"e": 1067,
"s": 514,
"text": "There are eight core Tidyverse packages namely ggplot2, dplyr, tidyr, readr, purrr, tibble, stringr, and forcats that are mentioned in this article. All of these packages are loaded automatically at once with the install.packages(“tidyverse”) command. In addition to these packages, Tidyverse also has some specialized packages that are not loaded automatically but need their own call. These include the DBI for relational databases. httr for web APIs, rvest for web scraping, etc. Now, let’s see the core Tidyverse packages and learn more about them."
},
{
"code": null,
"e": 1230,
"s": 1067,
"text": "Data Visualization and Explorationggplot2Data Wrangling and TransformationdplyrtidyrstringrforcatsData Import and ManagementtibblereadrFunctional Programmingpurrr"
},
{
"code": null,
"e": 1272,
"s": 1230,
"text": "Data Visualization and Explorationggplot2"
},
{
"code": null,
"e": 1280,
"s": 1272,
"text": "ggplot2"
},
{
"code": null,
"e": 1338,
"s": 1280,
"text": "Data Wrangling and Transformationdplyrtidyrstringrforcats"
},
{
"code": null,
"e": 1344,
"s": 1338,
"text": "dplyr"
},
{
"code": null,
"e": 1350,
"s": 1344,
"text": "tidyr"
},
{
"code": null,
"e": 1358,
"s": 1350,
"text": "stringr"
},
{
"code": null,
"e": 1366,
"s": 1358,
"text": "forcats"
},
{
"code": null,
"e": 1404,
"s": 1366,
"text": "Data Import and Managementtibblereadr"
},
{
"code": null,
"e": 1411,
"s": 1404,
"text": "tibble"
},
{
"code": null,
"e": 1417,
"s": 1411,
"text": "readr"
},
{
"code": null,
"e": 1445,
"s": 1417,
"text": "Functional Programmingpurrr"
},
{
"code": null,
"e": 1451,
"s": 1445,
"text": "purrr"
},
{
"code": null,
"e": 2215,
"s": 1451,
"text": "ggplot2 is an R data visualization library that is based on The Grammar of Graphics. ggplot2 can create data visualizations such as bar charts, pie charts, histograms, scatterplots, error charts, etc. using high-level API. It also allows you to add different types of data visualization components or layers in a single visualization. Once ggplot2 has been told which variables to map to which aesthetics in the plot, it does the rest of the work so that the user can focus on interpreting the visualizations and take less time in creating them. But this also means that it is not possible to create highly customized graphics in ggplot2. But there are a lot of resources in the RStudio community and Stack Overflow which can provide help in ggplot2 when needed. "
},
{
"code": null,
"e": 2298,
"s": 2215,
"text": "If you want to install ggplot2, the best method is to install the tidyverse using:"
},
{
"code": null,
"e": 2328,
"s": 2298,
"text": "install.packages(\"tidyverse\")"
},
{
"code": null,
"e": 2367,
"s": 2328,
"text": "Or you can just install ggplot2 using:"
},
{
"code": null,
"e": 2395,
"s": 2367,
"text": "install.packages(\"ggplot2\")"
},
{
"code": null,
"e": 2459,
"s": 2395,
"text": "You can also install the development version from GitHub using:"
},
{
"code": null,
"e": 2505,
"s": 2459,
"text": "devtools::install_github(\"tidyverse/ggplot2\")"
},
{
"code": null,
"e": 2514,
"s": 2505,
"text": "Example:"
},
{
"code": null,
"e": 2726,
"s": 2514,
"text": "We will be using 6 different data points for the bar plot and then with the help of the fill argument within the aes function, we will be applying the default colors to the barplot in the R programming language."
},
{
"code": null,
"e": 2728,
"s": 2726,
"text": "R"
},
{
"code": "# load the librarylibrary(\"ggplot2\") # create the dataframe with letters and numbersgfg < -data.frame( x=c('A', 'B', 'C', 'D', 'E', 'F'), y=c(4, 6, 2, 9, 7, 3)) # display the barggplot(gfg, aes(x, y, fill=x)) + geom_bar(stat=\"identity\")",
"e": 2971,
"s": 2728,
"text": null
},
{
"code": null,
"e": 2979,
"s": 2971,
"text": "Output:"
},
{
"code": null,
"e": 3657,
"s": 2979,
"text": "dplyr is a very popular data manipulation library in R. It has five important functions that are combined naturally with the group_by() function that can help in performing these functions in groups. These functions include the mutate() function which can add new variables that are functions of existing variables, select() function that selects the variables based on their names, filter() function that picks selects the variables based on their values, summarise() function that reduces multiple values into a summary, and the arrange() function that arranges the arranges the row orderings. If you want to install dplyr, the best method is to install the tidyverse using:"
},
{
"code": null,
"e": 3687,
"s": 3657,
"text": "install.packages(\"tidyverse\")"
},
{
"code": null,
"e": 3724,
"s": 3687,
"text": "Or you can just install dplyr using:"
},
{
"code": null,
"e": 3750,
"s": 3724,
"text": "install.packages(\"dplyr\")"
},
{
"code": null,
"e": 3814,
"s": 3750,
"text": "You can also install the development version from GitHub using:"
},
{
"code": null,
"e": 3858,
"s": 3814,
"text": "devtools::install_github(\"tidyverse/dplyr\")"
},
{
"code": null,
"e": 3867,
"s": 3858,
"text": "Example:"
},
{
"code": null,
"e": 3869,
"s": 3867,
"text": "R"
},
{
"code": "library(dplyr) print(starwars %>% filter(species == \"Droid\"))",
"e": 3931,
"s": 3869,
"text": null
},
{
"code": null,
"e": 3939,
"s": 3931,
"text": "Output:"
},
{
"code": null,
"e": 4719,
"s": 3939,
"text": "# A tibble: 6 x 14\n name height mass hair_color skin_color eye_color birth_year sex gender \n <chr> <int> <dbl> <chr> <chr> <chr> <dbl> <chr> <chr> \n1 C-3PO 167 75 <NA> gold yellow 112 none masculi~\n2 R2-D2 96 32 <NA> white, blue red 33 none masculi~\n3 R5-D4 97 32 <NA> white, red red NA none masculi~\n4 IG-88 200 140 none metal red 15 none masculi~\n5 R4-P17 96 NA none silver, red red, blue NA none feminine\n6 BB8 NA NA none none black NA none masculi~\n# ... with 5 more variables: homeworld <chr>, species <chr>, films <list>,\n# vehicles <list>, starships <list>"
},
{
"code": null,
"e": 5630,
"s": 4719,
"text": "tidyr is a data cleaning library in R which helps to create tidy data. Tidy data means that all the data cells have a single value with each of the data columns being a variable and the data rows being an observation. This tidy data is a staple in the tidyverse and it ensures that more time is spent on data analysis and to obtain value from data rather than cleaning the data continuously and modifying the tools to handle untidy data. The functions in tidyr broadly fall into five categories namely, Pivoting which changes the data between long and wide forms, Nesting which changes grouped data so that a group is a single row with a nested data frame, Splitting character columns and then combining them, Rectangling which converts nested lists into tidy tibbles and converting implicit missing values into explicit values. If you want to install tidyr, the best method is to install the tidyverse using: "
},
{
"code": null,
"e": 5660,
"s": 5630,
"text": "install.packages(\"tidyverse\")"
},
{
"code": null,
"e": 5697,
"s": 5660,
"text": "Or you can just install tidyr using:"
},
{
"code": null,
"e": 5723,
"s": 5697,
"text": "install.packages(\"tidyr\")"
},
{
"code": null,
"e": 5787,
"s": 5723,
"text": "You can also install the development version from GitHub using:"
},
{
"code": null,
"e": 5831,
"s": 5787,
"text": "devtools::install_github(\"tidyverse/tidyr\")"
},
{
"code": null,
"e": 5840,
"s": 5831,
"text": "Example:"
},
{
"code": null,
"e": 5978,
"s": 5840,
"text": "The gather() function in tidr will take multiple columns and collapse them into key-value pairs, duplicating all other columns as needed."
},
{
"code": null,
"e": 5980,
"s": 5978,
"text": "R"
},
{
"code": "# load the tidyr packagelibrary(tidyr) n = 10# creating a data frametidy_dataframe = data.frame( S.No = c(1:n), Group.1 = c(23, 345, 76, 212, 88, 199, 72, 35, 90, 265), Group.2 = c(117, 89, 66, 334, 90, 101, 178, 233, 45, 200), Group.3 = c(29, 101, 239, 289, 176, 320, 89, 109, 199, 56)) # print the elements of the data frameprint(head(tidy_dataframe)) # using gather() function on tidy_dataframelong <- tidy_dataframe %>% gather(Group, Frequency, Group.1:Group.3) # print the data frame in a long formatprint(head(long))",
"e": 6695,
"s": 5980,
"text": null
},
{
"code": null,
"e": 6703,
"s": 6695,
"text": "Output:"
},
{
"code": null,
"e": 7095,
"s": 6703,
"text": " S.No Group.1 Group.2 Group.3\n1 1 23 117 29\n2 2 345 89 101\n3 3 76 66 239\n4 4 212 334 289\n5 5 88 90 176\n6 6 199 101 320\n S.No Group Frequency\n1 1 Group.1 23\n2 2 Group.1 345\n3 3 Group.1 76\n4 4 Group.1 212\n5 5 Group.1 88\n6 6 Group.1 199"
},
{
"code": null,
"e": 7957,
"s": 7095,
"text": "stringr is a library that has many functions used for data cleaning and data preparation tasks. It is also designed for working with strings and has many functions that make this an easy process. stringr is built on top of stringi, which is an International Components for Unicode C library. So if there are any functions that you want to use but cannot find in stringr, then the best place to look for them is stringi. This also means that once you master stringr, stringi is not that difficult to use as both of these packages have similar conventions. All of the functions in stringr start with str and they take a string vector as their first argument. Some of these functions include str_detect(), str_extract(), str_match(), str_count(), str_replace(), str_subset(), etc. If you want to install stringr, the best method is to install the tidyverse using:"
},
{
"code": null,
"e": 7987,
"s": 7957,
"text": "install.packages(\"tidyverse\")"
},
{
"code": null,
"e": 8036,
"s": 7987,
"text": "Or you can just install stringr from CRAN using:"
},
{
"code": null,
"e": 8064,
"s": 8036,
"text": "install.packages(\"stringr\")"
},
{
"code": null,
"e": 8128,
"s": 8064,
"text": "You can also install the development version from GitHub using:"
},
{
"code": null,
"e": 8174,
"s": 8128,
"text": "devtools::install_github(\"tidyverse/stringr\")"
},
{
"code": null,
"e": 8183,
"s": 8174,
"text": "Example:"
},
{
"code": null,
"e": 8185,
"s": 8183,
"text": "R"
},
{
"code": "# R program for finding length of string # Importing packagelibrary(stringr) # Calculating length of string str_length(\"hello\")",
"e": 8315,
"s": 8185,
"text": null
},
{
"code": null,
"e": 8323,
"s": 8315,
"text": "Output:"
},
{
"code": null,
"e": 8325,
"s": 8323,
"text": "5"
},
{
"code": null,
"e": 8925,
"s": 8325,
"text": "forcats is a R library that is concerned with handling problems associated with vectors. These vectors are variables that have a fixed set of possible values they can take which is already known in advance. So forecats deals with issues like changes the orders of values in vectors, reordering the vectors, etc. Some of the functions in forcats are fct_relevel() that reorders a vectors by hand, fct_reorder() that reorders a factor using another variable, fct_infreq() that reorders a factorby frequency values etc. If you want to install forcats, the best method is to install the tidyverse using:"
},
{
"code": null,
"e": 8955,
"s": 8925,
"text": "install.packages(\"tidyverse\")"
},
{
"code": null,
"e": 8999,
"s": 8955,
"text": "Or you can just install forcats from using:"
},
{
"code": null,
"e": 9027,
"s": 8999,
"text": "install.packages(\"forcats\")"
},
{
"code": null,
"e": 9091,
"s": 9027,
"text": "You can also install the development version from GitHub using:"
},
{
"code": null,
"e": 9137,
"s": 9091,
"text": "devtools::install_github(\"tidyverse/forcats\")"
},
{
"code": null,
"e": 9146,
"s": 9137,
"text": "Example:"
},
{
"code": null,
"e": 9148,
"s": 9146,
"text": "R"
},
{
"code": "library(forcats)library(dplyr)library(ggplot2) print(head(starwars %>% filter(!is.na(species)) %>% count(species, sort = TRUE)))",
"e": 9287,
"s": 9148,
"text": null
},
{
"code": null,
"e": 9295,
"s": 9287,
"text": "Output:"
},
{
"code": null,
"e": 9449,
"s": 9295,
"text": "# A tibble: 6 x 2\n species n\n <chr> <int>\n1 Human 35\n2 Droid 6\n3 Gungan 3\n4 Kaminoan 2\n5 Mirialan 2\n6 Twi'lek 2"
},
{
"code": null,
"e": 10282,
"s": 9449,
"text": "This library provides a simple and speedy method to read rectangular data such as that with file formats tsv, csv, delim, fwf, etc. readr can parse many different types of data using a function that parses the total file and another that focuses on the specific column. This column specification defines the method to convert the data in the column from a character vector to the data type that is most suited. This is done automatically by readr in most cases. readr can read different kinds of file formats using different functions, namely read_csv() for comma-separated files, read_tsv() for tab-separated files, read_table() for tabular files, read_fwf() for fixed-width files, read_delim() for delimited files, and, read_log() for web log files. If you want to install readr, the best method is to install the tidyverse using:"
},
{
"code": null,
"e": 10314,
"s": 10282,
"text": "install.packages(\"tidyverse\"). "
},
{
"code": null,
"e": 10351,
"s": 10314,
"text": "Or you can just install readr using:"
},
{
"code": null,
"e": 10378,
"s": 10351,
"text": "install.packages(\"readr\")."
},
{
"code": null,
"e": 10442,
"s": 10378,
"text": "You can also install the development version from GitHub using:"
},
{
"code": null,
"e": 10486,
"s": 10442,
"text": "devtools::install_github(\"tidyverse/readr\")"
},
{
"code": null,
"e": 10495,
"s": 10486,
"text": "Example:"
},
{
"code": null,
"e": 10528,
"s": 10495,
"text": "Reading file with readr library."
},
{
"code": null,
"e": 10530,
"s": 10528,
"text": "R"
},
{
"code": "# R program to read text file# using readr package # Import the readr librarylibrary(readr) # Use read_tsv() to read text filemyData = read_tsv(\"geeksforgeeks.txt\", col_names = FALSE)print(myData)",
"e": 10727,
"s": 10530,
"text": null
},
{
"code": null,
"e": 10735,
"s": 10727,
"text": "Output:"
},
{
"code": null,
"e": 10865,
"s": 10735,
"text": "# A tibble: 1 x 1\n X1 \n \n1 A computer science portal for geeks."
},
{
"code": null,
"e": 11603,
"s": 10865,
"text": "A tibble is a form of a data.frame which includes the useful parts of it and discards the parts that are not so important. So tibbles don’t change variables names or types like data.frames nor do they do partial matching but they bring problems to the forefront much sooner such as when a variable does not exist. So a code with tibbles is much cleaner and effective than before. Tibbles is also easier to use with larger datasets that contain more complex objects, in part before an enhanced print() method. You can create new tibbles from column vectors using the tibble() function and you can also create a tibble row-by-row using a tribble() function. If you want to install tibble, the best method is to install the tidyverse using:"
},
{
"code": null,
"e": 11634,
"s": 11603,
"text": "install.packages(\"tidyverse\"):"
},
{
"code": null,
"e": 11672,
"s": 11634,
"text": "Or you can just install tibble using:"
},
{
"code": null,
"e": 11699,
"s": 11672,
"text": "install.packages(\"tibble\")"
},
{
"code": null,
"e": 11763,
"s": 11699,
"text": "You can also install the development version from GitHub using:"
},
{
"code": null,
"e": 11808,
"s": 11763,
"text": "devtools::install_github(\"tidyverse/tibble\")"
},
{
"code": null,
"e": 11817,
"s": 11808,
"text": "Example:"
},
{
"code": null,
"e": 11819,
"s": 11817,
"text": "R"
},
{
"code": "library(tibble)data <- data.frame(a = 1:3, b = letters[1:3], c = Sys.Date() - 1:3)print(data)",
"e": 11931,
"s": 11819,
"text": null
},
{
"code": null,
"e": 11939,
"s": 11931,
"text": "Output:"
},
{
"code": null,
"e": 12007,
"s": 11939,
"text": " a b c\n1 1 a 2021-11-24\n2 2 b 2021-11-23\n3 3 c 2021-11-22"
},
{
"code": null,
"e": 12547,
"s": 12007,
"text": "Purrr is a detailed set of tools for functions and vectors and it is mainly used to manage the functional programming in R. A good example of this is the map() functions that are used to replace multiple for loops that complicate and mess up the code inro simpler code that is easy to read. In addition to that, all purrr functions are type-stable which means they either return the advertised output type and if that is not possible, then the give an error. If you want to install purrr, the best method is to install the tidyverse using:"
},
{
"code": null,
"e": 12577,
"s": 12547,
"text": "install.packages(\"tidyverse\")"
},
{
"code": null,
"e": 12614,
"s": 12577,
"text": "Or you can just install purrr using:"
},
{
"code": null,
"e": 12640,
"s": 12614,
"text": "install.packages(\"purrr\")"
},
{
"code": null,
"e": 12704,
"s": 12640,
"text": "You can also install the development version from GitHub using:"
},
{
"code": null,
"e": 12748,
"s": 12704,
"text": "devtools::install_github(\"tidyverse/purrr\")"
},
{
"code": null,
"e": 12757,
"s": 12748,
"text": "Example:"
},
{
"code": null,
"e": 12759,
"s": 12757,
"text": "R"
},
{
"code": "library(purrr) mtcars %>% split(.$cyl) %>% # from base R map(~ lm(mpg ~ wt, data = .)) %>% map(summary) %>% map_dbl(\"r.squared\")",
"e": 12892,
"s": 12759,
"text": null
},
{
"code": null,
"e": 12900,
"s": 12892,
"text": "Output:"
},
{
"code": null,
"e": 12959,
"s": 12900,
"text": "4\n0.50863259632314\n6\n0.464510150550548\n8\n0.422965536496112"
},
{
"code": null,
"e": 12971,
"s": 12959,
"text": "anikakapoor"
},
{
"code": null,
"e": 12984,
"s": 12971,
"text": "kumar_satyam"
},
{
"code": null,
"e": 12990,
"s": 12984,
"text": "GBlog"
},
{
"code": null,
"e": 13001,
"s": 12990,
"text": "R Language"
},
{
"code": null,
"e": 13099,
"s": 13001,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 13124,
"s": 13099,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 13198,
"s": 13124,
"text": "Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ..."
},
{
"code": null,
"e": 13253,
"s": 13198,
"text": "GEEK-O-LYMPICS 2022 - May The Geeks Force Be With You!"
},
{
"code": null,
"e": 13290,
"s": 13253,
"text": "Geek Streak - 24 Days POTD Challenge"
},
{
"code": null,
"e": 13333,
"s": 13290,
"text": "Practice for cracking any coding interview"
},
{
"code": null,
"e": 13378,
"s": 13333,
"text": "Change column name of a given DataFrame in R"
},
{
"code": null,
"e": 13430,
"s": 13378,
"text": "Filter data by multiple conditions in R using Dplyr"
},
{
"code": null,
"e": 13488,
"s": 13430,
"text": "How to Replace specific values in column in R DataFrame ?"
},
{
"code": null,
"e": 13540,
"s": 13488,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
}
] |
PostgreSQL – Import CSV File Into Table
|
28 Aug, 2020
In this article, we will discuss the process of importing a .csv file into a PostgreSQL table.
To do so we will require a table which can be obtained using the below command:
CREATE TABLE persons
(
id serial NOT NULL,
first_name character varying(50),
last_name character varying(50),
dob date,
email character varying(255),
CONSTRAINT persons_pkey PRIMARY KEY (id)
);
Now we create a .csv file in our sheet manager (eg: MS Excel or notepad) as shown below:
Our file is located as persons.csv at C:\Users\RajuExample :To import this CSV file into the persons table, you use COPY statement as follows:
COPY persons(first_name, last_name, dob, email)
FROM 'C:\Users\Raju' DELIMITER ', ' CSV HEADER;
Now, let us check the person table as follows:
SELECT * FROM persons;
It will lead to the below Output:
It is important to put the CSV file path after the FROM keyword. Because CSV file format is used, you need to mention the DELIMITER as well as ‘CSV’ keywords. The HEADER keyword indicates that the CSV file comprises a header line with column names. When importing data, PostgreSQL neglects the first line as they are the header line of the file.
The file must be read directly by the PostgreSQL server and not by the client application. Therefore, it must be accessible to the PostgreSQL server machine. Also, you can execute the COPY statement successfully if you have superusers access.
postgreSQL-utilities
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Aug, 2020"
},
{
"code": null,
"e": 123,
"s": 28,
"text": "In this article, we will discuss the process of importing a .csv file into a PostgreSQL table."
},
{
"code": null,
"e": 203,
"s": 123,
"text": "To do so we will require a table which can be obtained using the below command:"
},
{
"code": null,
"e": 409,
"s": 203,
"text": "CREATE TABLE persons\n(\n id serial NOT NULL,\n first_name character varying(50),\n last_name character varying(50),\n dob date,\n email character varying(255),\n CONSTRAINT persons_pkey PRIMARY KEY (id)\n);"
},
{
"code": null,
"e": 498,
"s": 409,
"text": "Now we create a .csv file in our sheet manager (eg: MS Excel or notepad) as shown below:"
},
{
"code": null,
"e": 641,
"s": 498,
"text": "Our file is located as persons.csv at C:\\Users\\RajuExample :To import this CSV file into the persons table, you use COPY statement as follows:"
},
{
"code": null,
"e": 738,
"s": 641,
"text": "COPY persons(first_name, last_name, dob, email) \nFROM 'C:\\Users\\Raju' DELIMITER ', ' CSV HEADER;"
},
{
"code": null,
"e": 785,
"s": 738,
"text": "Now, let us check the person table as follows:"
},
{
"code": null,
"e": 808,
"s": 785,
"text": "SELECT * FROM persons;"
},
{
"code": null,
"e": 842,
"s": 808,
"text": "It will lead to the below Output:"
},
{
"code": null,
"e": 1188,
"s": 842,
"text": "It is important to put the CSV file path after the FROM keyword. Because CSV file format is used, you need to mention the DELIMITER as well as ‘CSV’ keywords. The HEADER keyword indicates that the CSV file comprises a header line with column names. When importing data, PostgreSQL neglects the first line as they are the header line of the file."
},
{
"code": null,
"e": 1431,
"s": 1188,
"text": "The file must be read directly by the PostgreSQL server and not by the client application. Therefore, it must be accessible to the PostgreSQL server machine. Also, you can execute the COPY statement successfully if you have superusers access."
},
{
"code": null,
"e": 1452,
"s": 1431,
"text": "postgreSQL-utilities"
},
{
"code": null,
"e": 1463,
"s": 1452,
"text": "PostgreSQL"
}
] |
SQL Query to Compare Two Dates
|
26 Sep, 2021
In SQL, dates are complicated for newbies, since while working with the database, the format of the date in the table must be matched with the input date in order to insert. In various scenarios instead of date, DateTime (time is also involved with date) is used. Here we will see, SQL Query to compare two dates. This can be easily done using equals to(=), less than(<), and greater than(>) operators. In SQL, the date value has DATE datatype which accepts date in ‘yyyy-mm-dd’ format. To compare two dates, we will declare two dates and compare them using the IF-ELSE statement.
Syntax:
IF Boolean_expression
{ sql_statement | statement_block }
[ ELSE
{ sql_statement | statement_block } ]
We can declare variables easily by using the keyword DECLARE before the variable name. By default, the local variable starts with @.
Syntax:
DECLARE @variable_name datatype;
Set values to the variable: We can assign values to the variables using the SET keyword.
Syntax:
SET @variable_name;
Now we take different cases to demonstrate of comparison between dates.
Query 1:
DECLARE @date1 DATE, @date2 DATE;
SET @date1='2021-01-01';
SET @date2='2021-02-02';
IF @date1=@date2
SELECT 'equal date'
ELSE
IF @date1<@date2 SELECT 'date2 is greater'
ELSE SELECT 'date1 is greater';
Output:
Query 2:
DECLARE @date1 DATE, @date2 VARCHAR(20);
SET @date1='2021-01-01';
SET @date2='2021-01-01';
IF @date1=@date2
SELECT 'equal date'
ELSE
IF @date1<@date2 SELECT 'date2 is greater'
ELSE SELECT 'date1 is greater';
Output:
Query 3:
DECLARE @date1 DATE, @date2 VARCHAR(20);
SET @date1='2022-01-01';
SET @date2='2021-01-01';
IF @date1=@date2
SELECT 'equal date'
ELSE
IF @date1<@date2 SELECT 'date2 is greater'
ELSE SELECT 'date1 is greater';
Output:
Picked
SQL-Query
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CTE in SQL
How to Update Multiple Columns in Single Update Statement in SQL?
SQL Interview Questions
SQL | Views
Difference between DELETE, DROP and TRUNCATE
MySQL | Group_CONCAT() Function
Window functions in SQL
SQL | GROUP BY
Difference between DDL and DML in DBMS
Difference between DELETE and TRUNCATE
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Sep, 2021"
},
{
"code": null,
"e": 609,
"s": 28,
"text": "In SQL, dates are complicated for newbies, since while working with the database, the format of the date in the table must be matched with the input date in order to insert. In various scenarios instead of date, DateTime (time is also involved with date) is used. Here we will see, SQL Query to compare two dates. This can be easily done using equals to(=), less than(<), and greater than(>) operators. In SQL, the date value has DATE datatype which accepts date in ‘yyyy-mm-dd’ format. To compare two dates, we will declare two dates and compare them using the IF-ELSE statement."
},
{
"code": null,
"e": 617,
"s": 609,
"text": "Syntax:"
},
{
"code": null,
"e": 644,
"s": 617,
"text": " IF Boolean_expression "
},
{
"code": null,
"e": 685,
"s": 644,
"text": " { sql_statement | statement_block } "
},
{
"code": null,
"e": 696,
"s": 685,
"text": "[ ELSE "
},
{
"code": null,
"e": 739,
"s": 696,
"text": " { sql_statement | statement_block } ] "
},
{
"code": null,
"e": 872,
"s": 739,
"text": "We can declare variables easily by using the keyword DECLARE before the variable name. By default, the local variable starts with @."
},
{
"code": null,
"e": 880,
"s": 872,
"text": "Syntax:"
},
{
"code": null,
"e": 913,
"s": 880,
"text": "DECLARE @variable_name datatype;"
},
{
"code": null,
"e": 1002,
"s": 913,
"text": "Set values to the variable: We can assign values to the variables using the SET keyword."
},
{
"code": null,
"e": 1010,
"s": 1002,
"text": "Syntax:"
},
{
"code": null,
"e": 1030,
"s": 1010,
"text": "SET @variable_name;"
},
{
"code": null,
"e": 1102,
"s": 1030,
"text": "Now we take different cases to demonstrate of comparison between dates."
},
{
"code": null,
"e": 1111,
"s": 1102,
"text": "Query 1:"
},
{
"code": null,
"e": 1469,
"s": 1111,
"text": "DECLARE @date1 DATE, @date2 DATE; \nSET @date1='2021-01-01';\nSET @date2='2021-02-02'; \nIF @date1=@date2 \nSELECT 'equal date'\nELSE\nIF @date1<@date2 SELECT 'date2 is greater' \nELSE SELECT 'date1 is greater'; "
},
{
"code": null,
"e": 1477,
"s": 1469,
"text": "Output:"
},
{
"code": null,
"e": 1487,
"s": 1477,
"text": "Query 2: "
},
{
"code": null,
"e": 1695,
"s": 1487,
"text": "DECLARE @date1 DATE, @date2 VARCHAR(20);\nSET @date1='2021-01-01';\nSET @date2='2021-01-01';\nIF @date1=@date2\nSELECT 'equal date'\nELSE\nIF @date1<@date2 SELECT 'date2 is greater'\nELSE SELECT 'date1 is greater';"
},
{
"code": null,
"e": 1703,
"s": 1695,
"text": "Output:"
},
{
"code": null,
"e": 1712,
"s": 1703,
"text": "Query 3:"
},
{
"code": null,
"e": 1920,
"s": 1712,
"text": "DECLARE @date1 DATE, @date2 VARCHAR(20);\nSET @date1='2022-01-01';\nSET @date2='2021-01-01';\nIF @date1=@date2\nSELECT 'equal date'\nELSE\nIF @date1<@date2 SELECT 'date2 is greater'\nELSE SELECT 'date1 is greater';"
},
{
"code": null,
"e": 1928,
"s": 1920,
"text": "Output:"
},
{
"code": null,
"e": 1935,
"s": 1928,
"text": "Picked"
},
{
"code": null,
"e": 1945,
"s": 1935,
"text": "SQL-Query"
},
{
"code": null,
"e": 1956,
"s": 1945,
"text": "SQL-Server"
},
{
"code": null,
"e": 1960,
"s": 1956,
"text": "SQL"
},
{
"code": null,
"e": 1964,
"s": 1960,
"text": "SQL"
},
{
"code": null,
"e": 2062,
"s": 1964,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2073,
"s": 2062,
"text": "CTE in SQL"
},
{
"code": null,
"e": 2139,
"s": 2073,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 2163,
"s": 2139,
"text": "SQL Interview Questions"
},
{
"code": null,
"e": 2175,
"s": 2163,
"text": "SQL | Views"
},
{
"code": null,
"e": 2220,
"s": 2175,
"text": "Difference between DELETE, DROP and TRUNCATE"
},
{
"code": null,
"e": 2252,
"s": 2220,
"text": "MySQL | Group_CONCAT() Function"
},
{
"code": null,
"e": 2276,
"s": 2252,
"text": "Window functions in SQL"
},
{
"code": null,
"e": 2291,
"s": 2276,
"text": "SQL | GROUP BY"
},
{
"code": null,
"e": 2330,
"s": 2291,
"text": "Difference between DDL and DML in DBMS"
}
] |
Partitioning a linked list around a given value and keeping the original order
|
06 Jul, 2022
Given a linked list and a value x, partition it such that all nodes less than x come first, then all nodes with a value equal to x, and finally nodes with a value greater than or equal to x. The original relative order of the nodes in each of the three partitions should be preserved. The partition must work in place.
Examples:
Input : 1->4->3->2->5->2->3,
x = 3
Output: 1->2->2->3->3->4->5
Input : 1->4->2->10
x = 3
Output: 1->2->4->10
Input : 10->4->20->10->3
x = 3
Output: 3->10->4->20->10
To solve this problem we can use partition method of Quick Sort but this would not preserve the original relative order of the nodes in each of the two partitions.
Below is the algorithm to solve this problem :
Initialize first and last nodes of below three linked lists as NULL. Linked list of values smaller than x.Linked list of values equal to x.Linked list of values greater than x.
Linked list of values smaller than x.Linked list of values equal to x.Linked list of values greater than x.
Linked list of values smaller than x.
Linked list of values equal to x.
Linked list of values greater than x.
Now iterate through the original linked list. If a node’s value is less than x then append it at the end of the smaller list. If the value is equal to x, then at the end of the equal list. And if a value is greater, then at the end of the greater list.
Now concatenate three lists.
Below is the implementation of the above idea.
C++
C
Java
Python3
C#
Javascript
// C++ program to partition a linked list around a// given value.#include <bits/stdc++.h>using namespace std; /* Link list Node */struct Node { int data; struct Node* next;}; // A utility function to create a new nodeNode* newNode(int data){ struct Node* new_node = new Node; new_node->data = data; new_node->next = NULL; return new_node;} // Function to make two separate lists and return// head after concatenatingstruct Node* partition(struct Node* head, int x){ /* Let us initialize first and last nodes of three linked lists 1) Linked list of values smaller than x. 2) Linked list of values equal to x. 3) Linked list of values greater than x.*/ struct Node *smallerHead = NULL, *smallerLast = NULL; struct Node *greaterLast = NULL, *greaterHead = NULL; struct Node *equalHead = NULL, *equalLast = NULL; // Now iterate original list and connect nodes // of appropriate linked lists. while (head != NULL) { // If current node is equal to x, append it // to the list of x values if (head->data == x) { if (equalHead == NULL) equalHead = equalLast = head; else { equalLast->next = head; equalLast = equalLast->next; } } // If current node is less than X, append // it to the list of smaller values else if (head->data < x) { if (smallerHead == NULL) smallerLast = smallerHead = head; else { smallerLast->next = head; smallerLast = head; } } else // Append to the list of greater values { if (greaterHead == NULL) greaterLast = greaterHead = head; else { greaterLast->next = head; greaterLast = head; } } head = head->next; } // Fix end of greater linked list to NULL if this // list has some nodes if (greaterLast != NULL) greaterLast->next = NULL; // Connect three lists // If smaller list is empty if (smallerHead == NULL) { if (equalHead == NULL) return greaterHead; equalLast->next = greaterHead; return equalHead; } // If smaller list is not empty and equal list is empty if (equalHead == NULL) { smallerLast->next = greaterHead; return smallerHead; } // If both smaller and equal list are non-empty smallerLast->next = equalHead; equalLast->next = greaterHead; return smallerHead;} /* Function to print linked list */void printList(struct Node* head){ struct Node* temp = head; while (temp != NULL) { printf("%d ", temp->data); temp = temp->next; }} // Driver program to run the caseint main(){ /* Start with the empty list */ struct Node* head = newNode(10); head->next = newNode(4); head->next->next = newNode(5); head->next->next->next = newNode(30); head->next->next->next->next = newNode(2); head->next->next->next->next->next = newNode(50); int x = 3; head = partition(head, x); printList(head); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)
// C++ program to partition a linked list around a// given value.#include <stdio.h>#include <stdlib.h> /* Link list Node */typedef struct Node { int data; struct Node* next;} Node; // A utility function to create a new nodeNode* newNode(int data){ Node* new_node = (Node*)malloc(sizeof(Node)); new_node->data = data; new_node->next = NULL; return new_node;} // Function to make two separate lists and return// head after concatenatingNode* partition(Node* head, int x){ /* Let us initialize first and last nodes of three linked lists 1) Linked list of values smaller than x. 2) Linked list of values equal to x. 3) Linked list of values greater than x.*/ Node *smallerHead = NULL, *smallerLast = NULL; Node *greaterLast = NULL, *greaterHead = NULL; Node *equalHead = NULL, *equalLast = NULL; // Now iterate original list and connect nodes // of appropriate linked lists. while (head != NULL) { // If current node is equal to x, append it // to the list of x values if (head->data == x) { if (equalHead == NULL) equalHead = equalLast = head; else { equalLast->next = head; equalLast = equalLast->next; } } // If current node is less than X, append // it to the list of smaller values else if (head->data < x) { if (smallerHead == NULL) smallerLast = smallerHead = head; else { smallerLast->next = head; smallerLast = head; } } else // Append to the list of greater values { if (greaterHead == NULL) greaterLast = greaterHead = head; else { greaterLast->next = head; greaterLast = head; } } head = head->next; } // Fix end of greater linked list to NULL if this // list has some nodes if (greaterLast != NULL) greaterLast->next = NULL; // Connect three lists // If smaller list is empty if (smallerHead == NULL) { if (equalHead == NULL) return greaterHead; equalLast->next = greaterHead; return equalHead; } // If smaller list is not empty and equal list is empty if (equalHead == NULL) { smallerLast->next = greaterHead; return smallerHead; } // If both smaller and equal list are non-empty smallerLast->next = equalHead; equalLast->next = greaterHead; return smallerHead;} /* Function to print linked list */void printList(Node* head){ Node* temp = head; while (temp != NULL) { printf("%d ", temp->data); temp = temp->next; }} // Driver program to run the caseint main(){ /* Start with the empty list */ Node* head = newNode(10); head->next = newNode(4); head->next->next = newNode(5); head->next->next->next = newNode(30); head->next->next->next->next = newNode(2); head->next->next->next->next->next = newNode(50); int x = 3; head = partition(head, x); printList(head); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)
// Java program to partition a// linked list around a given value.class GfG { /* Link list Node */ static class Node { int data; Node next; } // A utility function to create a new node static Node newNode(int data) { Node new_node = new Node(); new_node.data = data; new_node.next = null; return new_node; } // Function to make two separate lists and return // head after concatenating static Node partition(Node head, int x) { /* Let us initialize first and last nodes of three linked lists 1) Linked list of values smaller than x. 2) Linked list of values equal to x. 3) Linked list of values greater than x.*/ Node smallerHead = null, smallerLast = null; Node greaterLast = null, greaterHead = null; Node equalHead = null, equalLast = null; // Now iterate original list and connect nodes // of appropriate linked lists. while (head != null) { // If current node is equal to x, append it // to the list of x values if (head.data == x) { if (equalHead == null) equalHead = equalLast = head; else { equalLast.next = head; equalLast = equalLast.next; } } // If current node is less than X, append // it to the list of smaller values else if (head.data < x) { if (smallerHead == null) smallerLast = smallerHead = head; else { smallerLast.next = head; smallerLast = head; } } else // Append to the list of greater values { if (greaterHead == null) greaterLast = greaterHead = head; else { greaterLast.next = head; greaterLast = head; } } head = head.next; } // Fix end of greater linked list to NULL if this // list has some nodes if (greaterLast != null) greaterLast.next = null; // Connect three lists // If smaller list is empty if (smallerHead == null) { if (equalHead == null) return greaterHead; equalLast.next = greaterHead; return equalHead; } // If smaller list is not empty // and equal list is empty if (equalHead == null) { smallerLast.next = greaterHead; return smallerHead; } // If both smaller and equal list // are non-empty smallerLast.next = equalHead; equalLast.next = greaterHead; return smallerHead; } /* Function to print linked list */ static void printList(Node head) { Node temp = head; while (temp != null) { System.out.print(temp.data + " "); temp = temp.next; } } // Driver code public static void main(String[] args) { /* Start with the empty list */ Node head = newNode(10); head.next = newNode(4); head.next.next = newNode(5); head.next.next.next = newNode(30); head.next.next.next.next = newNode(2); head.next.next.next.next.next = newNode(50); int x = 3; head = partition(head, x); printList(head); }} // This code is contributed by Aditya Kumar (adityakumar129)
# Python3 program to partition a# linked list around a given value. # Link list Nodeclass Node: def __init__(self): self.data = 0 self.next = None # A utility function to create a new nodedef newNode( data): new_node = Node() new_node.data = data new_node.next = None return new_node # Function to make two separate lists and return# head after concatenatingdef partition( head, x) : # Let us initialize first and last nodes of # three linked lists # 1) Linked list of values smaller than x. # 2) Linked list of values equal to x. # 3) Linked list of values greater than x. smallerHead = None smallerLast = None greaterLast = None greaterHead = None equalHead = None equalLast = None # Now iterate original list and connect nodes # of appropriate linked lists. while (head != None) : # If current node is equal to x, append it # to the list of x values if (head.data == x): if (equalHead == None): equalHead = equalLast = head else: equalLast.next = head equalLast = equalLast.next # If current node is less than X, append # it to the list of smaller values else if (head.data < x): if (smallerHead == None): smallerLast = smallerHead = head else: smallerLast.next = head smallerLast = head else : # Append to the list of greater values if (greaterHead == None) : greaterLast = greaterHead = head else: greaterLast.next = head greaterLast = head head = head.next # Fix end of greater linked list to None if this # list has some nodes if (greaterLast != None) : greaterLast.next = None # Connect three lists # If smaller list is empty if (smallerHead == None) : if (equalHead == None) : return greaterHead equalLast.next = greaterHead return equalHead # If smaller list is not empty # and equal list is empty if (equalHead == None) : smallerLast.next = greaterHead return smallerHead # If both smaller and equal list # are non-empty smallerLast.next = equalHead equalLast.next = greaterHead return smallerHead # Function to print linked listdef printList(head) : temp = head while (temp != None): print(temp.data ,end= " ") temp = temp.next # Driver code # Start with the empty listhead = newNode(10)head.next = newNode(4)head.next.next = newNode(5)head.next.next.next = newNode(30)head.next.next.next.next = newNode(2)head.next.next.next.next.next = newNode(50) x = 3head = partition(head, x)printList(head) # This code is contributed by Arnab Kundu.
// C# program to partition a// linked list around a given value.using System; public class GfG{ /* Link list Node */public class Node{ public int data; public Node next;} // A utility function to create a new nodestatic Node newNode(int data){ Node new_node = new Node(); new_node.data = data; new_node.next = null; return new_node;} // Function to make two separate lists and return// head after concatenatingstatic Node partition(Node head, int x){ /* Let us initialize first and last nodes of three linked lists 1) Linked list of values smaller than x. 2) Linked list of values equal to x. 3) Linked list of values greater than x.*/ Node smallerHead = null, smallerLast = null; Node greaterLast = null, greaterHead = null; Node equalHead = null, equalLast =null; // Now iterate original list and connect nodes // of appropriate linked lists. while (head != null) { // If current node is equal to x, append it // to the list of x values if (head.data == x) { if (equalHead == null) equalHead = equalLast = head; else { equalLast.next = head; equalLast = equalLast.next; } } // If current node is less than X, append // it to the list of smaller values else if (head.data < x) { if (smallerHead == null) smallerLast = smallerHead = head; else { smallerLast.next = head; smallerLast = head; } } else // Append to the list of greater values { if (greaterHead == null) greaterLast = greaterHead = head; else { greaterLast.next = head; greaterLast = head; } } head = head.next; } // Fix end of greater linked list to NULL if this // list has some nodes if (greaterLast != null) greaterLast.next = null; // Connect three lists // If smaller list is empty if (smallerHead == null) { if (equalHead == null) return greaterHead; equalLast.next = greaterHead; return equalHead; } // If smaller list is not empty // and equal list is empty if (equalHead == null) { smallerLast.next = greaterHead; return smallerHead; } // If both smaller and equal list // are non-empty smallerLast.next = equalHead; equalLast.next = greaterHead; return smallerHead;} /* Function to print linked list */static void printList(Node head){ Node temp = head; while (temp != null) { Console.Write(temp.data + " "); temp = temp.next; }} // Driver codepublic static void Main(){ /* Start with the empty list */ Node head = newNode(10); head.next = newNode(4); head.next.next = newNode(5); head.next.next.next = newNode(30); head.next.next.next.next = newNode(2); head.next.next.next.next.next = newNode(50); int x = 3; head = partition(head, x); printList(head);}} /* This code contributed by PrinciRaj1992 */
<script> // Javascript program to partition a// linked list around a given value. /* Link list Node */ class Node { constructor() { this.data = 0; this.next = null; } } // A utility function to create a new node function newNode(data) {var new_node = new Node(); new_node.data = data; new_node.next = null; return new_node; } // Function to make two separate lists and return // head after concatenating function partition(head , x) { /* Let us initialize first and last nodes of three linked lists 1) Linked list of values smaller than x. 2) Linked list of values equal to x. 3) Linked list of values greater than x. */ var smallerHead = null, smallerLast = null;var greaterLast = null, greaterHead = null;var equalHead = null, equalLast = null; // Now iterate original list and connect nodes // of appropriate linked lists. while (head != null) { // If current node is equal to x, append it // to the list of x values if (head.data == x) { if (equalHead == null) equalHead = equalLast = head; else { equalLast.next = head; equalLast = equalLast.next; } } // If current node is less than X, append // it to the list of smaller values else if (head.data < x) { if (smallerHead == null) smallerLast = smallerHead = head; else { smallerLast.next = head; smallerLast = head; } } else // Append to the list of greater values { if (greaterHead == null) greaterLast = greaterHead = head; else { greaterLast.next = head; greaterLast = head; } } head = head.next; } // Fix end of greater linked list to NULL if this // list has some nodes if (greaterLast != null) greaterLast.next = null; // Connect three lists // If smaller list is empty if (smallerHead == null) { if (equalHead == null) return greaterHead; equalLast.next = greaterHead; return equalHead; } // If smaller list is not empty // and equal list is empty if (equalHead == null) { smallerLast.next = greaterHead; return smallerHead; } // If both smaller and equal list // are non-empty smallerLast.next = equalHead; equalLast.next = greaterHead; return smallerHead; } /* Function to print linked list */ function printList(head) {var temp = head; while (temp != null) { document.write(temp.data + " "); temp = temp.next; } } // Driver code /* Start with the empty list */ var head = newNode(10); head.next = newNode(4); head.next.next = newNode(5); head.next.next.next = newNode(30); head.next.next.next.next = newNode(2); head.next.next.next.next.next = newNode(50); var x = 3; head = partition(head, x); printList(head); // This code contributed by aashish1995 </script>
2 10 4 5 30 50
Time complexity: O(n) where n is the size of the linked listAuxiliary Space: O(1)
This article is contributed by Shashank Mishra ( Gullu ). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
prerna saini
princiraj1992
andrew1234
aashish1995
gabaa406
Kirti_Mangal
surinderdawra388
adityakumar129
polymatir3j
hardikkoriintern
Linked List
Linked List
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
Merge two sorted linked lists
Find the middle of a given linked list
What is Data Structure: Types, Classifications and Applications
Linked List vs Array
Merge Sort for Linked Lists
Implementing a Linked List in Java using Class
Add two numbers represented by linked lists | Set 1
Queue - Linked List Implementation
Detect and Remove Loop in a Linked List
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n06 Jul, 2022"
},
{
"code": null,
"e": 371,
"s": 52,
"text": "Given a linked list and a value x, partition it such that all nodes less than x come first, then all nodes with a value equal to x, and finally nodes with a value greater than or equal to x. The original relative order of the nodes in each of the three partitions should be preserved. The partition must work in place."
},
{
"code": null,
"e": 382,
"s": 371,
"text": "Examples: "
},
{
"code": null,
"e": 577,
"s": 382,
"text": "Input : 1->4->3->2->5->2->3, \n x = 3\nOutput: 1->2->2->3->3->4->5\n\nInput : 1->4->2->10 \n x = 3\nOutput: 1->2->4->10\n\nInput : 10->4->20->10->3 \n x = 3\nOutput: 3->10->4->20->10 "
},
{
"code": null,
"e": 741,
"s": 577,
"text": "To solve this problem we can use partition method of Quick Sort but this would not preserve the original relative order of the nodes in each of the two partitions."
},
{
"code": null,
"e": 789,
"s": 741,
"text": "Below is the algorithm to solve this problem : "
},
{
"code": null,
"e": 966,
"s": 789,
"text": "Initialize first and last nodes of below three linked lists as NULL. Linked list of values smaller than x.Linked list of values equal to x.Linked list of values greater than x."
},
{
"code": null,
"e": 1074,
"s": 966,
"text": "Linked list of values smaller than x.Linked list of values equal to x.Linked list of values greater than x."
},
{
"code": null,
"e": 1112,
"s": 1074,
"text": "Linked list of values smaller than x."
},
{
"code": null,
"e": 1146,
"s": 1112,
"text": "Linked list of values equal to x."
},
{
"code": null,
"e": 1184,
"s": 1146,
"text": "Linked list of values greater than x."
},
{
"code": null,
"e": 1437,
"s": 1184,
"text": "Now iterate through the original linked list. If a node’s value is less than x then append it at the end of the smaller list. If the value is equal to x, then at the end of the equal list. And if a value is greater, then at the end of the greater list."
},
{
"code": null,
"e": 1466,
"s": 1437,
"text": "Now concatenate three lists."
},
{
"code": null,
"e": 1514,
"s": 1466,
"text": "Below is the implementation of the above idea. "
},
{
"code": null,
"e": 1518,
"s": 1514,
"text": "C++"
},
{
"code": null,
"e": 1520,
"s": 1518,
"text": "C"
},
{
"code": null,
"e": 1525,
"s": 1520,
"text": "Java"
},
{
"code": null,
"e": 1533,
"s": 1525,
"text": "Python3"
},
{
"code": null,
"e": 1536,
"s": 1533,
"text": "C#"
},
{
"code": null,
"e": 1547,
"s": 1536,
"text": "Javascript"
},
{
"code": "// C++ program to partition a linked list around a// given value.#include <bits/stdc++.h>using namespace std; /* Link list Node */struct Node { int data; struct Node* next;}; // A utility function to create a new nodeNode* newNode(int data){ struct Node* new_node = new Node; new_node->data = data; new_node->next = NULL; return new_node;} // Function to make two separate lists and return// head after concatenatingstruct Node* partition(struct Node* head, int x){ /* Let us initialize first and last nodes of three linked lists 1) Linked list of values smaller than x. 2) Linked list of values equal to x. 3) Linked list of values greater than x.*/ struct Node *smallerHead = NULL, *smallerLast = NULL; struct Node *greaterLast = NULL, *greaterHead = NULL; struct Node *equalHead = NULL, *equalLast = NULL; // Now iterate original list and connect nodes // of appropriate linked lists. while (head != NULL) { // If current node is equal to x, append it // to the list of x values if (head->data == x) { if (equalHead == NULL) equalHead = equalLast = head; else { equalLast->next = head; equalLast = equalLast->next; } } // If current node is less than X, append // it to the list of smaller values else if (head->data < x) { if (smallerHead == NULL) smallerLast = smallerHead = head; else { smallerLast->next = head; smallerLast = head; } } else // Append to the list of greater values { if (greaterHead == NULL) greaterLast = greaterHead = head; else { greaterLast->next = head; greaterLast = head; } } head = head->next; } // Fix end of greater linked list to NULL if this // list has some nodes if (greaterLast != NULL) greaterLast->next = NULL; // Connect three lists // If smaller list is empty if (smallerHead == NULL) { if (equalHead == NULL) return greaterHead; equalLast->next = greaterHead; return equalHead; } // If smaller list is not empty and equal list is empty if (equalHead == NULL) { smallerLast->next = greaterHead; return smallerHead; } // If both smaller and equal list are non-empty smallerLast->next = equalHead; equalLast->next = greaterHead; return smallerHead;} /* Function to print linked list */void printList(struct Node* head){ struct Node* temp = head; while (temp != NULL) { printf(\"%d \", temp->data); temp = temp->next; }} // Driver program to run the caseint main(){ /* Start with the empty list */ struct Node* head = newNode(10); head->next = newNode(4); head->next->next = newNode(5); head->next->next->next = newNode(30); head->next->next->next->next = newNode(2); head->next->next->next->next->next = newNode(50); int x = 3; head = partition(head, x); printList(head); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 4776,
"s": 1547,
"text": null
},
{
"code": "// C++ program to partition a linked list around a// given value.#include <stdio.h>#include <stdlib.h> /* Link list Node */typedef struct Node { int data; struct Node* next;} Node; // A utility function to create a new nodeNode* newNode(int data){ Node* new_node = (Node*)malloc(sizeof(Node)); new_node->data = data; new_node->next = NULL; return new_node;} // Function to make two separate lists and return// head after concatenatingNode* partition(Node* head, int x){ /* Let us initialize first and last nodes of three linked lists 1) Linked list of values smaller than x. 2) Linked list of values equal to x. 3) Linked list of values greater than x.*/ Node *smallerHead = NULL, *smallerLast = NULL; Node *greaterLast = NULL, *greaterHead = NULL; Node *equalHead = NULL, *equalLast = NULL; // Now iterate original list and connect nodes // of appropriate linked lists. while (head != NULL) { // If current node is equal to x, append it // to the list of x values if (head->data == x) { if (equalHead == NULL) equalHead = equalLast = head; else { equalLast->next = head; equalLast = equalLast->next; } } // If current node is less than X, append // it to the list of smaller values else if (head->data < x) { if (smallerHead == NULL) smallerLast = smallerHead = head; else { smallerLast->next = head; smallerLast = head; } } else // Append to the list of greater values { if (greaterHead == NULL) greaterLast = greaterHead = head; else { greaterLast->next = head; greaterLast = head; } } head = head->next; } // Fix end of greater linked list to NULL if this // list has some nodes if (greaterLast != NULL) greaterLast->next = NULL; // Connect three lists // If smaller list is empty if (smallerHead == NULL) { if (equalHead == NULL) return greaterHead; equalLast->next = greaterHead; return equalHead; } // If smaller list is not empty and equal list is empty if (equalHead == NULL) { smallerLast->next = greaterHead; return smallerHead; } // If both smaller and equal list are non-empty smallerLast->next = equalHead; equalLast->next = greaterHead; return smallerHead;} /* Function to print linked list */void printList(Node* head){ Node* temp = head; while (temp != NULL) { printf(\"%d \", temp->data); temp = temp->next; }} // Driver program to run the caseint main(){ /* Start with the empty list */ Node* head = newNode(10); head->next = newNode(4); head->next->next = newNode(5); head->next->next->next = newNode(30); head->next->next->next->next = newNode(2); head->next->next->next->next->next = newNode(50); int x = 3; head = partition(head, x); printList(head); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 7967,
"s": 4776,
"text": null
},
{
"code": "// Java program to partition a// linked list around a given value.class GfG { /* Link list Node */ static class Node { int data; Node next; } // A utility function to create a new node static Node newNode(int data) { Node new_node = new Node(); new_node.data = data; new_node.next = null; return new_node; } // Function to make two separate lists and return // head after concatenating static Node partition(Node head, int x) { /* Let us initialize first and last nodes of three linked lists 1) Linked list of values smaller than x. 2) Linked list of values equal to x. 3) Linked list of values greater than x.*/ Node smallerHead = null, smallerLast = null; Node greaterLast = null, greaterHead = null; Node equalHead = null, equalLast = null; // Now iterate original list and connect nodes // of appropriate linked lists. while (head != null) { // If current node is equal to x, append it // to the list of x values if (head.data == x) { if (equalHead == null) equalHead = equalLast = head; else { equalLast.next = head; equalLast = equalLast.next; } } // If current node is less than X, append // it to the list of smaller values else if (head.data < x) { if (smallerHead == null) smallerLast = smallerHead = head; else { smallerLast.next = head; smallerLast = head; } } else // Append to the list of greater values { if (greaterHead == null) greaterLast = greaterHead = head; else { greaterLast.next = head; greaterLast = head; } } head = head.next; } // Fix end of greater linked list to NULL if this // list has some nodes if (greaterLast != null) greaterLast.next = null; // Connect three lists // If smaller list is empty if (smallerHead == null) { if (equalHead == null) return greaterHead; equalLast.next = greaterHead; return equalHead; } // If smaller list is not empty // and equal list is empty if (equalHead == null) { smallerLast.next = greaterHead; return smallerHead; } // If both smaller and equal list // are non-empty smallerLast.next = equalHead; equalLast.next = greaterHead; return smallerHead; } /* Function to print linked list */ static void printList(Node head) { Node temp = head; while (temp != null) { System.out.print(temp.data + \" \"); temp = temp.next; } } // Driver code public static void main(String[] args) { /* Start with the empty list */ Node head = newNode(10); head.next = newNode(4); head.next.next = newNode(5); head.next.next.next = newNode(30); head.next.next.next.next = newNode(2); head.next.next.next.next.next = newNode(50); int x = 3; head = partition(head, x); printList(head); }} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 11516,
"s": 7967,
"text": null
},
{
"code": "# Python3 program to partition a# linked list around a given value. # Link list Nodeclass Node: def __init__(self): self.data = 0 self.next = None # A utility function to create a new nodedef newNode( data): new_node = Node() new_node.data = data new_node.next = None return new_node # Function to make two separate lists and return# head after concatenatingdef partition( head, x) : # Let us initialize first and last nodes of # three linked lists # 1) Linked list of values smaller than x. # 2) Linked list of values equal to x. # 3) Linked list of values greater than x. smallerHead = None smallerLast = None greaterLast = None greaterHead = None equalHead = None equalLast = None # Now iterate original list and connect nodes # of appropriate linked lists. while (head != None) : # If current node is equal to x, append it # to the list of x values if (head.data == x): if (equalHead == None): equalHead = equalLast = head else: equalLast.next = head equalLast = equalLast.next # If current node is less than X, append # it to the list of smaller values else if (head.data < x): if (smallerHead == None): smallerLast = smallerHead = head else: smallerLast.next = head smallerLast = head else : # Append to the list of greater values if (greaterHead == None) : greaterLast = greaterHead = head else: greaterLast.next = head greaterLast = head head = head.next # Fix end of greater linked list to None if this # list has some nodes if (greaterLast != None) : greaterLast.next = None # Connect three lists # If smaller list is empty if (smallerHead == None) : if (equalHead == None) : return greaterHead equalLast.next = greaterHead return equalHead # If smaller list is not empty # and equal list is empty if (equalHead == None) : smallerLast.next = greaterHead return smallerHead # If both smaller and equal list # are non-empty smallerLast.next = equalHead equalLast.next = greaterHead return smallerHead # Function to print linked listdef printList(head) : temp = head while (temp != None): print(temp.data ,end= \" \") temp = temp.next # Driver code # Start with the empty listhead = newNode(10)head.next = newNode(4)head.next.next = newNode(5)head.next.next.next = newNode(30)head.next.next.next.next = newNode(2)head.next.next.next.next.next = newNode(50) x = 3head = partition(head, x)printList(head) # This code is contributed by Arnab Kundu.",
"e": 14463,
"s": 11516,
"text": null
},
{
"code": "// C# program to partition a// linked list around a given value.using System; public class GfG{ /* Link list Node */public class Node{ public int data; public Node next;} // A utility function to create a new nodestatic Node newNode(int data){ Node new_node = new Node(); new_node.data = data; new_node.next = null; return new_node;} // Function to make two separate lists and return// head after concatenatingstatic Node partition(Node head, int x){ /* Let us initialize first and last nodes of three linked lists 1) Linked list of values smaller than x. 2) Linked list of values equal to x. 3) Linked list of values greater than x.*/ Node smallerHead = null, smallerLast = null; Node greaterLast = null, greaterHead = null; Node equalHead = null, equalLast =null; // Now iterate original list and connect nodes // of appropriate linked lists. while (head != null) { // If current node is equal to x, append it // to the list of x values if (head.data == x) { if (equalHead == null) equalHead = equalLast = head; else { equalLast.next = head; equalLast = equalLast.next; } } // If current node is less than X, append // it to the list of smaller values else if (head.data < x) { if (smallerHead == null) smallerLast = smallerHead = head; else { smallerLast.next = head; smallerLast = head; } } else // Append to the list of greater values { if (greaterHead == null) greaterLast = greaterHead = head; else { greaterLast.next = head; greaterLast = head; } } head = head.next; } // Fix end of greater linked list to NULL if this // list has some nodes if (greaterLast != null) greaterLast.next = null; // Connect three lists // If smaller list is empty if (smallerHead == null) { if (equalHead == null) return greaterHead; equalLast.next = greaterHead; return equalHead; } // If smaller list is not empty // and equal list is empty if (equalHead == null) { smallerLast.next = greaterHead; return smallerHead; } // If both smaller and equal list // are non-empty smallerLast.next = equalHead; equalLast.next = greaterHead; return smallerHead;} /* Function to print linked list */static void printList(Node head){ Node temp = head; while (temp != null) { Console.Write(temp.data + \" \"); temp = temp.next; }} // Driver codepublic static void Main(){ /* Start with the empty list */ Node head = newNode(10); head.next = newNode(4); head.next.next = newNode(5); head.next.next.next = newNode(30); head.next.next.next.next = newNode(2); head.next.next.next.next.next = newNode(50); int x = 3; head = partition(head, x); printList(head);}} /* This code contributed by PrinciRaj1992 */",
"e": 17649,
"s": 14463,
"text": null
},
{
"code": "<script> // Javascript program to partition a// linked list around a given value. /* Link list Node */ class Node { constructor() { this.data = 0; this.next = null; } } // A utility function to create a new node function newNode(data) {var new_node = new Node(); new_node.data = data; new_node.next = null; return new_node; } // Function to make two separate lists and return // head after concatenating function partition(head , x) { /* Let us initialize first and last nodes of three linked lists 1) Linked list of values smaller than x. 2) Linked list of values equal to x. 3) Linked list of values greater than x. */ var smallerHead = null, smallerLast = null;var greaterLast = null, greaterHead = null;var equalHead = null, equalLast = null; // Now iterate original list and connect nodes // of appropriate linked lists. while (head != null) { // If current node is equal to x, append it // to the list of x values if (head.data == x) { if (equalHead == null) equalHead = equalLast = head; else { equalLast.next = head; equalLast = equalLast.next; } } // If current node is less than X, append // it to the list of smaller values else if (head.data < x) { if (smallerHead == null) smallerLast = smallerHead = head; else { smallerLast.next = head; smallerLast = head; } } else // Append to the list of greater values { if (greaterHead == null) greaterLast = greaterHead = head; else { greaterLast.next = head; greaterLast = head; } } head = head.next; } // Fix end of greater linked list to NULL if this // list has some nodes if (greaterLast != null) greaterLast.next = null; // Connect three lists // If smaller list is empty if (smallerHead == null) { if (equalHead == null) return greaterHead; equalLast.next = greaterHead; return equalHead; } // If smaller list is not empty // and equal list is empty if (equalHead == null) { smallerLast.next = greaterHead; return smallerHead; } // If both smaller and equal list // are non-empty smallerLast.next = equalHead; equalLast.next = greaterHead; return smallerHead; } /* Function to print linked list */ function printList(head) {var temp = head; while (temp != null) { document.write(temp.data + \" \"); temp = temp.next; } } // Driver code /* Start with the empty list */ var head = newNode(10); head.next = newNode(4); head.next.next = newNode(5); head.next.next.next = newNode(30); head.next.next.next.next = newNode(2); head.next.next.next.next.next = newNode(50); var x = 3; head = partition(head, x); printList(head); // This code contributed by aashish1995 </script>",
"e": 21140,
"s": 17649,
"text": null
},
{
"code": null,
"e": 21162,
"s": 21140,
"text": "2 10 4 5 30 50 "
},
{
"code": null,
"e": 21244,
"s": 21162,
"text": "Time complexity: O(n) where n is the size of the linked listAuxiliary Space: O(1)"
},
{
"code": null,
"e": 21554,
"s": 21244,
"text": "This article is contributed by Shashank Mishra ( Gullu ). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. "
},
{
"code": null,
"e": 21567,
"s": 21554,
"text": "prerna saini"
},
{
"code": null,
"e": 21581,
"s": 21567,
"text": "princiraj1992"
},
{
"code": null,
"e": 21592,
"s": 21581,
"text": "andrew1234"
},
{
"code": null,
"e": 21604,
"s": 21592,
"text": "aashish1995"
},
{
"code": null,
"e": 21613,
"s": 21604,
"text": "gabaa406"
},
{
"code": null,
"e": 21626,
"s": 21613,
"text": "Kirti_Mangal"
},
{
"code": null,
"e": 21643,
"s": 21626,
"text": "surinderdawra388"
},
{
"code": null,
"e": 21658,
"s": 21643,
"text": "adityakumar129"
},
{
"code": null,
"e": 21670,
"s": 21658,
"text": "polymatir3j"
},
{
"code": null,
"e": 21687,
"s": 21670,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 21699,
"s": 21687,
"text": "Linked List"
},
{
"code": null,
"e": 21711,
"s": 21699,
"text": "Linked List"
},
{
"code": null,
"e": 21809,
"s": 21711,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 21841,
"s": 21809,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 21871,
"s": 21841,
"text": "Merge two sorted linked lists"
},
{
"code": null,
"e": 21910,
"s": 21871,
"text": "Find the middle of a given linked list"
},
{
"code": null,
"e": 21974,
"s": 21910,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 21995,
"s": 21974,
"text": "Linked List vs Array"
},
{
"code": null,
"e": 22023,
"s": 21995,
"text": "Merge Sort for Linked Lists"
},
{
"code": null,
"e": 22070,
"s": 22023,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 22122,
"s": 22070,
"text": "Add two numbers represented by linked lists | Set 1"
},
{
"code": null,
"e": 22157,
"s": 22122,
"text": "Queue - Linked List Implementation"
}
] |
Chain Rules - Solved Examples
|
Q 1 - If 15 dolls cost Rs 35, what do 39 dolls cost?
A - Rs 71
B - Rs 81
C - Rs 91
D - Rs 101
Answer - C
Explanation
Let the required cost be Rs x.
More dolls, more cost (direct)
∴ 15 : 39:: 35 : x ⇒15 *x = (39 *35)
⇒ x= (39 *35)/15 = 91.
∴ Cost of 39 dolls = Rs 91
Q 2 - If 36 men can do a piece of work in 25 days, in how many days will 15 men do it?
A - 30
B - 40
C - 50
D - 60
Answer - D
Explanation
Let the required number of days be x.
Less men, more days (indirect)
∴ 15: 36:: 25 : x ⇒ 15 *x = (36 * 25)
⇒ x= (36 *25 ) / 15 = 60.
∴ Required number of days = 60.
Q 3 - If 20 men can build a wall 112m long in 6 days, what length of a similar wall can be built by 25 men in days?
A - 40m
B - 50m
C - 60m
D - 70m
Answer - D
Explanation
Let the required length be x metres.
More men, more length built (direct)
Less days, less length built (direct)
Men 20 : 25 :: 112 : x
Days 6:3
∴ (20 * 6 *x ) = ( 25 * 3 *112) ⇒ x= (25 * 3 * 112) / (20 * 6 ) = 70.
Required length 70m.
Q 4 - If 8 men working 9 hours a days can built a wall 18m long, 2 m broad and 12m high in 10 days, how many men will be required to build a wall 32m long , 3m broad and 9m high by working 6 hours a days, in 8 days?
A - 20
B - 30
C - 40
D - 50
Answer - A
Explanation
let the required number of men be x.
More length, more men (Direct)
More breadth, more men (Direct)
Less height, less men (Direct)
Less hours per day, more men (Indirect)
Less days, more men (Indirect)
Length 18:32
Breadth 2:3
Height 12:9 :: 8 : x
Hrs / Day 6: 9
Days 8:10
∴ ( 18 * 2 * 12 * 6 * 8 * x) = ( 32 * 3 * 9 * 9 * 10) ⇒ x= 32*3*9*9*10 /
18*2*12*6*8 =30.
Q 5 - A contract was to be completed in 56 days and 104 men were set to works, Each working 8 hours per days. After 30 days , 2/5 of the work is completed. How many additional men may be employed so that the work may be completed in time, each man now working 9 hours a day?
A - 36
B - 46
C - 56
D - 66
Answer - C
Explanation
Remaining work = (1- 2/5 ) = 3/5 , Remaining period = (56 – 30) =26 days.
Let the additional men employed be x.
More work , more men (direct)
More days , less men (indirect)
More hrs/ day, less men (indirect)
Work 2/5 : 3/5
Days 26: 30 :: 104 : (104 + x)
Hrs/ day 9:8
∴ 2/5 *26 * 9 * (104 +x ) = 3/5 *30 * 8 * 104
⇒ (104 +x) = 3 * 30 * 8 * 104 / 2* 26 * 9 = 160 ⇒ x = (160 – 104) = 56.
Additional men to be employed = 56.
Q 6 - 5 men or 9 women can do a piece of work in 19 days. In how many days will 3 men and 6 women do it?
A - 12
B - 13
C - 14
D - 15
Answer - D
Explanation
9 women = 5 men ⇒ 1 women = 5/9 men
⇒ 6 women = (5/9 * 6) men = 10/3 men.
3 men +6 women = (3+ 10/3 ) men = 19/3 men.
Let the required number of days be x.
More men, less days
19/3 : 5 :: 19 : x ⇒ 19 /3 *x = (5 *19)
⇒ x= (5* 19 * 3 /19 ) = 15.
∴ Required number of days = 15.
Q 7 - 8 women can complete the work in 10 days and 10 children take 16 days to complete the same work. How many days will 10 women and 12 children take to complete the work ?
A - 8
B - 7
C - 6
D - 5
Answer - D
Explanation
1 women can complete the work in (10 * 8) days= 80 days.
1 child can complete the work in (16 * 10) days= 160 days.
1 women 1 days work = 1/80 , 1 child 1 days work= 1/160.
(10 women +12 children) 1 days work = ( 10 * 1/80 +12 * 1/160)
= ( 1/8 + 3/40 ) = 8/ 40 = 1 /5.
∴ 10 women and 12 children will finish the work in 5 days.
Q 8 - If 6 engines consume 15 metric tonnes of coal when each is running 9 hours a days , how much coal will be required for 8 engines, each running 12 hours a days, it being given that 3 engines of former type consume as much as 4 engines of latter type?
A - 17 tonnes
B - 18 tonnes
C - 19 tonnes
D - 20 tonnes
Answer - D
Explanation
Let the required quantity of coal consumed be x tones.
More engines, more coal consumption (direct)
More hours, more coal consumption (direct)
Less rate of consumption, less consumption (direct)
Engines 6:8
Working Hrs 9:12 :: 15 : x
Rate of consumption 1/3 : 1/4
∴ (6 * 9 * 1/3 * x) = (8 * 12 * 1/4 * 15 ⇒ 18x = 360 ⇒ x = 20.
Quantity of coal consumed = 20 tonnes.
Q 9 - If 22.5 m of a uniform rod weighs 85.5 kg , what will be the weight of 6m of the same rod?
A - 22.8 kg
B - 25.6 kg
C - 26.5 kg
D - 28kg
Answer - A
Explanation
Let the required weight be x kg.
Less length, less weight (direct)
22.5: 6 :: 85.5 :x ⇒ 22.5x = (6 * 85.5) ⇒ x= (6 * 85.5) / 22.5 = (6 *885 / 225) = 22.8 kg.
Required weight = 22.8 kg.
Q 10 - On a scale of map 1.5cm represents 24km. If the distance between two points on the map is 76.5 cm, the distance between these points is:
A - 1071 km
B - 1224 km
C - 1377 km
D - None of these
Answer - B
Explanation
Let the actual distance be x km.
More distance on the map, more is actual distance (direct)
1.5 : 76.5 :: 24 : x ⇒ 1.5x = (76.5 * 24) ⇒ x = (76.5 * 24) / 1.5 = 1224 km.
Required distance= 1224km.
Q 11 - 6 dozen eggs are bought for Rs 48. How much will 132 eggs cost?
A - Rs 78
B - Rs 80
C - Rs 82
D - Rs 88
Answer - D
Explanation
Let the required cost be Rs x.
More eggs, more cost ( direct)
72: 132 :: 48 : x ⇒ 72 x = (132 * 48) ⇒ x= (132 *48) / 72 = 88.
∴ Required cost = Rs 88.
Q 12 - In a race, Raghu cover 5 km in 20 minutes, how much distance will he cover in 50 minutes?
A - 10.5 km
B - 12 km
C - 12.5 km
D - 13 km
Answer - A
Explanation
Let the required distance be x km.
More time , more distance covered ( direct)
20: 50: :: 5 : x ⇒ 20x = (50 * 5 ) ⇒ x= (50 * 5) / 20 = 12.5 km.
Required distance = 12.5 km.
|
[
{
"code": null,
"e": 4079,
"s": 4026,
"text": "Q 1 - If 15 dolls cost Rs 35, what do 39 dolls cost?"
},
{
"code": null,
"e": 4089,
"s": 4079,
"text": "A - Rs 71"
},
{
"code": null,
"e": 4100,
"s": 4089,
"text": "B - Rs 81 "
},
{
"code": null,
"e": 4110,
"s": 4100,
"text": "C - Rs 91"
},
{
"code": null,
"e": 4122,
"s": 4110,
"text": "D - Rs 101 "
},
{
"code": null,
"e": 4133,
"s": 4122,
"text": "Answer - C"
},
{
"code": null,
"e": 4145,
"s": 4133,
"text": "Explanation"
},
{
"code": null,
"e": 4297,
"s": 4145,
"text": "Let the required cost be Rs x.\nMore dolls, more cost (direct)\n∴ 15 : 39:: 35 : x ⇒15 *x = (39 *35)\n⇒ x= (39 *35)/15 = 91.\n∴ Cost of 39 dolls = Rs 91\n"
},
{
"code": null,
"e": 4384,
"s": 4297,
"text": "Q 2 - If 36 men can do a piece of work in 25 days, in how many days will 15 men do it?"
},
{
"code": null,
"e": 4392,
"s": 4384,
"text": "A - 30 "
},
{
"code": null,
"e": 4400,
"s": 4392,
"text": "B - 40 "
},
{
"code": null,
"e": 4408,
"s": 4400,
"text": "C - 50 "
},
{
"code": null,
"e": 4416,
"s": 4408,
"text": "D - 60 "
},
{
"code": null,
"e": 4427,
"s": 4416,
"text": "Answer - D"
},
{
"code": null,
"e": 4439,
"s": 4427,
"text": "Explanation"
},
{
"code": null,
"e": 4605,
"s": 4439,
"text": "Let the required number of days be x.\nLess men, more days (indirect)\n∴ 15: 36:: 25 : x ⇒ 15 *x = (36 * 25)\n⇒ x= (36 *25 ) / 15 = 60.\n∴ Required number of days = 60.\n"
},
{
"code": null,
"e": 4721,
"s": 4605,
"text": "Q 3 - If 20 men can build a wall 112m long in 6 days, what length of a similar wall can be built by 25 men in days?"
},
{
"code": null,
"e": 4730,
"s": 4721,
"text": "A - 40m "
},
{
"code": null,
"e": 4739,
"s": 4730,
"text": "B - 50m "
},
{
"code": null,
"e": 4748,
"s": 4739,
"text": "C - 60m "
},
{
"code": null,
"e": 4756,
"s": 4748,
"text": "D - 70m"
},
{
"code": null,
"e": 4767,
"s": 4756,
"text": "Answer - D"
},
{
"code": null,
"e": 4779,
"s": 4767,
"text": "Explanation"
},
{
"code": null,
"e": 5029,
"s": 4779,
"text": "Let the required length be x metres.\nMore men, more length built (direct)\nLess days, less length built (direct)\nMen 20 : 25 :: 112 : x \nDays 6:3 \n∴ (20 * 6 *x ) = ( 25 * 3 *112) ⇒ x= (25 * 3 * 112) / (20 * 6 ) = 70.\nRequired length 70m.\n"
},
{
"code": null,
"e": 5245,
"s": 5029,
"text": "Q 4 - If 8 men working 9 hours a days can built a wall 18m long, 2 m broad and 12m high in 10 days, how many men will be required to build a wall 32m long , 3m broad and 9m high by working 6 hours a days, in 8 days?"
},
{
"code": null,
"e": 5253,
"s": 5245,
"text": "A - 20 "
},
{
"code": null,
"e": 5261,
"s": 5253,
"text": "B - 30 "
},
{
"code": null,
"e": 5269,
"s": 5261,
"text": "C - 40 "
},
{
"code": null,
"e": 5276,
"s": 5269,
"text": "D - 50"
},
{
"code": null,
"e": 5287,
"s": 5276,
"text": "Answer - A"
},
{
"code": null,
"e": 5299,
"s": 5287,
"text": "Explanation"
},
{
"code": null,
"e": 5713,
"s": 5299,
"text": "let the required number of men be x.\nMore length, more men (Direct)\nMore breadth, more men (Direct)\nLess height, less men (Direct)\nLess hours per day, more men (Indirect)\nLess days, more men (Indirect) \nLength 18:32\nBreadth 2:3\nHeight 12:9 :: 8 : x\nHrs / Day 6: 9\nDays 8:10\n∴ ( 18 * 2 * 12 * 6 * 8 * x) = ( 32 * 3 * 9 * 9 * 10) ⇒ x= 32*3*9*9*10 / \n18*2*12*6*8 =30.\n"
},
{
"code": null,
"e": 5989,
"s": 5713,
"text": "Q 5 - A contract was to be completed in 56 days and 104 men were set to works, Each working 8 hours per days. After 30 days , 2/5 of the work is completed. How many additional men may be employed so that the work may be completed in time, each man now working 9 hours a day?"
},
{
"code": null,
"e": 5997,
"s": 5989,
"text": "A - 36 "
},
{
"code": null,
"e": 6005,
"s": 5997,
"text": "B - 46 "
},
{
"code": null,
"e": 6012,
"s": 6005,
"text": "C - 56"
},
{
"code": null,
"e": 6020,
"s": 6012,
"text": "D - 66 "
},
{
"code": null,
"e": 6031,
"s": 6020,
"text": "Answer - C"
},
{
"code": null,
"e": 6043,
"s": 6031,
"text": "Explanation"
},
{
"code": null,
"e": 6491,
"s": 6043,
"text": "Remaining work = (1- 2/5 ) = 3/5 , Remaining period = (56 – 30) =26 days.\nLet the additional men employed be x.\nMore work , more men (direct)\nMore days , less men (indirect)\nMore hrs/ day, less men (indirect)\nWork 2/5 : 3/5\nDays 26: 30 :: 104 : (104 + x)\nHrs/ day 9:8\n∴ 2/5 *26 * 9 * (104 +x ) = 3/5 *30 * 8 * 104\n⇒ (104 +x) = 3 * 30 * 8 * 104 / 2* 26 * 9 = 160 ⇒ x = (160 – 104) = 56.\nAdditional men to be employed = 56.\n"
},
{
"code": null,
"e": 6597,
"s": 6491,
"text": "Q 6 - 5 men or 9 women can do a piece of work in 19 days. In how many days will 3 men and 6 women do it?"
},
{
"code": null,
"e": 6604,
"s": 6597,
"text": "A - 12"
},
{
"code": null,
"e": 6611,
"s": 6604,
"text": "B - 13"
},
{
"code": null,
"e": 6618,
"s": 6611,
"text": "C - 14"
},
{
"code": null,
"e": 6625,
"s": 6618,
"text": "D - 15"
},
{
"code": null,
"e": 6636,
"s": 6625,
"text": "Answer - D"
},
{
"code": null,
"e": 6648,
"s": 6636,
"text": "Explanation"
},
{
"code": null,
"e": 6926,
"s": 6648,
"text": "9 women = 5 men ⇒ 1 women = 5/9 men\n⇒ 6 women = (5/9 * 6) men = 10/3 men.\n3 men +6 women = (3+ 10/3 ) men = 19/3 men.\nLet the required number of days be x.\nMore men, less days\n19/3 : 5 :: 19 : x ⇒ 19 /3 *x = (5 *19)\n⇒ x= (5* 19 * 3 /19 ) = 15.\n∴ Required number of days = 15.\n"
},
{
"code": null,
"e": 7104,
"s": 6926,
"text": "Q 7 - 8 women can complete the work in 10 days and 10 children take 16 days to complete the same work. How many days will 10 women and 12 children take to complete the work ?\n"
},
{
"code": null,
"e": 7110,
"s": 7104,
"text": "A - 8"
},
{
"code": null,
"e": 7116,
"s": 7110,
"text": "B - 7"
},
{
"code": null,
"e": 7122,
"s": 7116,
"text": "C - 6"
},
{
"code": null,
"e": 7128,
"s": 7122,
"text": "D - 5"
},
{
"code": null,
"e": 7139,
"s": 7128,
"text": "Answer - D"
},
{
"code": null,
"e": 7151,
"s": 7139,
"text": "Explanation"
},
{
"code": null,
"e": 7484,
"s": 7151,
"text": "1 women can complete the work in (10 * 8) days= 80 days.\n1 child can complete the work in (16 * 10) days= 160 days.\n1 women 1 days work = 1/80 , 1 child 1 days work= 1/160.\n(10 women +12 children) 1 days work = ( 10 * 1/80 +12 * 1/160)\n= ( 1/8 + 3/40 ) = 8/ 40 = 1 /5.\n∴ 10 women and 12 children will finish the work in 5 days.\n"
},
{
"code": null,
"e": 7740,
"s": 7484,
"text": "Q 8 - If 6 engines consume 15 metric tonnes of coal when each is running 9 hours a days , how much coal will be required for 8 engines, each running 12 hours a days, it being given that 3 engines of former type consume as much as 4 engines of latter type?"
},
{
"code": null,
"e": 7754,
"s": 7740,
"text": "A - 17 tonnes"
},
{
"code": null,
"e": 7768,
"s": 7754,
"text": "B - 18 tonnes"
},
{
"code": null,
"e": 7782,
"s": 7768,
"text": "C - 19 tonnes"
},
{
"code": null,
"e": 7796,
"s": 7782,
"text": "D - 20 tonnes"
},
{
"code": null,
"e": 7807,
"s": 7796,
"text": "Answer - D"
},
{
"code": null,
"e": 7819,
"s": 7807,
"text": "Explanation"
},
{
"code": null,
"e": 8199,
"s": 7819,
"text": "Let the required quantity of coal consumed be x tones.\nMore engines, more coal consumption (direct)\nMore hours, more coal consumption (direct)\nLess rate of consumption, less consumption (direct)\nEngines 6:8\nWorking Hrs 9:12 :: 15 : x\nRate of consumption 1/3 : 1/4\n∴ (6 * 9 * 1/3 * x) = (8 * 12 * 1/4 * 15 ⇒ 18x = 360 ⇒ x = 20.\nQuantity of coal consumed = 20 tonnes.\n"
},
{
"code": null,
"e": 8298,
"s": 8199,
"text": "Q 9 - If 22.5 m of a uniform rod weighs 85.5 kg , what will be the weight of 6m of the same rod?"
},
{
"code": null,
"e": 8311,
"s": 8298,
"text": "A - 22.8 kg "
},
{
"code": null,
"e": 8324,
"s": 8311,
"text": "B - 25.6 kg "
},
{
"code": null,
"e": 8337,
"s": 8324,
"text": "C - 26.5 kg "
},
{
"code": null,
"e": 8347,
"s": 8337,
"text": "D - 28kg "
},
{
"code": null,
"e": 8358,
"s": 8347,
"text": "Answer - A"
},
{
"code": null,
"e": 8370,
"s": 8358,
"text": "Explanation"
},
{
"code": null,
"e": 8559,
"s": 8370,
"text": "Let the required weight be x kg.\nLess length, less weight (direct)\n22.5: 6 :: 85.5 :x ⇒ 22.5x = (6 * 85.5) ⇒ x= (6 * 85.5) / 22.5 = (6 *885 / 225) = 22.8 kg.\nRequired weight = 22.8 kg.\n"
},
{
"code": null,
"e": 8705,
"s": 8559,
"text": "Q 10 - On a scale of map 1.5cm represents 24km. If the distance between two points on the map is 76.5 cm, the distance between these points is:"
},
{
"code": null,
"e": 8719,
"s": 8705,
"text": "A - 1071 km "
},
{
"code": null,
"e": 8735,
"s": 8719,
"text": "B - 1224 km "
},
{
"code": null,
"e": 8749,
"s": 8735,
"text": "C - 1377 km "
},
{
"code": null,
"e": 8767,
"s": 8749,
"text": "D - None of these"
},
{
"code": null,
"e": 8778,
"s": 8767,
"text": "Answer - B"
},
{
"code": null,
"e": 8790,
"s": 8778,
"text": "Explanation"
},
{
"code": null,
"e": 8998,
"s": 8790,
"text": "Let the actual distance be x km.\nMore distance on the map, more is actual distance (direct)\n1.5 : 76.5 :: 24 : x ⇒ 1.5x = (76.5 * 24) ⇒ x = (76.5 * 24) / 1.5 = 1224 km.\nRequired distance= 1224km.\n"
},
{
"code": null,
"e": 9070,
"s": 8998,
"text": "Q 11 - 6 dozen eggs are bought for Rs 48. How much will 132 eggs cost?"
},
{
"code": null,
"e": 9080,
"s": 9070,
"text": "A - Rs 78"
},
{
"code": null,
"e": 9090,
"s": 9080,
"text": "B - Rs 80"
},
{
"code": null,
"e": 9100,
"s": 9090,
"text": "C - Rs 82"
},
{
"code": null,
"e": 9110,
"s": 9100,
"text": "D - Rs 88"
},
{
"code": null,
"e": 9121,
"s": 9110,
"text": "Answer - D"
},
{
"code": null,
"e": 9133,
"s": 9121,
"text": "Explanation"
},
{
"code": null,
"e": 9297,
"s": 9133,
"text": "Let the required cost be Rs x. \nMore eggs, more cost ( direct)\n72: 132 :: 48 : x ⇒ 72 x = (132 * 48) ⇒ x= (132 *48) / 72 = 88.\n∴ Required cost = Rs 88.\n"
},
{
"code": null,
"e": 9394,
"s": 9297,
"text": "Q 12 - In a race, Raghu cover 5 km in 20 minutes, how much distance will he cover in 50 minutes?"
},
{
"code": null,
"e": 9406,
"s": 9394,
"text": "A - 10.5 km"
},
{
"code": null,
"e": 9416,
"s": 9406,
"text": "B - 12 km"
},
{
"code": null,
"e": 9428,
"s": 9416,
"text": "C - 12.5 km"
},
{
"code": null,
"e": 9438,
"s": 9428,
"text": "D - 13 km"
},
{
"code": null,
"e": 9449,
"s": 9438,
"text": "Answer - A"
},
{
"code": null,
"e": 9461,
"s": 9449,
"text": "Explanation"
}
] |
How we can put two divisions <div> side by side in HTML?
|
With CSS properties, you can easily put two <div> side by side in HTML. Use the CSS property float to achieve this.
With that, add height:100px and set margin.
You can try to run the following code to place two <div> side by side
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>HTML div</title>
</head>
<body>
<div style="width: 100px; float:left; height:100px; background:gray; margin:10px">
First DIV
</div>
<div style="width: 100px; float:left; height:100px; background:yellow; margin:10px">
Second DIV
</div>
</body>
</html>
|
[
{
"code": null,
"e": 1303,
"s": 1187,
"text": "With CSS properties, you can easily put two <div> side by side in HTML. Use the CSS property float to achieve this."
},
{
"code": null,
"e": 1347,
"s": 1303,
"text": "With that, add height:100px and set margin."
},
{
"code": null,
"e": 1417,
"s": 1347,
"text": "You can try to run the following code to place two <div> side by side"
},
{
"code": null,
"e": 1427,
"s": 1417,
"text": "Live Demo"
},
{
"code": null,
"e": 1775,
"s": 1427,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>HTML div</title>\n </head>\n <body>\n <div style=\"width: 100px; float:left; height:100px; background:gray; margin:10px\">\n First DIV\n </div>\n <div style=\"width: 100px; float:left; height:100px; background:yellow; margin:10px\">\n Second DIV\n </div>\n </body>\n</html>"
}
] |
SQL general functions | NVL, NVL2, DECODE, COALESCE, NULLIF, LNNVL and NANVL
|
18 Dec, 2019
In this article, we’ll be discussing some powerful SQL general functions, which are – NVL, NVL2, DECODE, COALESCE, NULLIF, LNNVL and NANVL.
These functions work with any data type and pertain to the use of null values in the expression list. These are all single row function i.e. provide one result per row.
NVL(expr1, expr2) : In SQL, NVL() converts a null value to an actual value. Data types that can be used are date, character and number. Data type must match with each other i.e. expr1 and expr2 must of same data type.Syntax –NVL (expr1, expr2)
expr1 is the source value or expression that may contain a null.expr2 is the target value for converting the null.Example –SELECT salary, NVL(commission_pct, 0),
(salary*12) + (salary*12*NVL(commission_pct, 0))
annual_salary FROM employees;
Output :
NVL (expr1, expr2)
expr1 is the source value or expression that may contain a null.expr2 is the target value for converting the null.
Example –
SELECT salary, NVL(commission_pct, 0),
(salary*12) + (salary*12*NVL(commission_pct, 0))
annual_salary FROM employees;
Output :
NVL2(expr1, expr2, expr3) : The NVL2 function examines the first expression. If the first expression is not null, then the NVL2 function returns the second expression. If the first expression is null, then the third expression is returned i.e. If expr1 is not null, NVL2 returns expr2. If expr1 is null, NVL2 returns expr3. The argument expr1 can have any data type.Syntax –NVL2 (expr1, expr2, expr3)
expr1 is the source value or expression that may contain nullexpr2 is the value returned if expr1 is not nullexpr3 is the value returned if expr1 is nullExample –SELECT last_name, salary, commission_pct,
NVL2(commission_pct, ’SAL+COMM’, ’SAL’)
income FROM employees;
Output :
Syntax –
NVL2 (expr1, expr2, expr3)
expr1 is the source value or expression that may contain nullexpr2 is the value returned if expr1 is not nullexpr3 is the value returned if expr1 is null
Example –
SELECT last_name, salary, commission_pct,
NVL2(commission_pct, ’SAL+COMM’, ’SAL’)
income FROM employees;
Output :
DECODE() : Facilitates conditional inquiries by doing the work of a CASE or IF-THEN-ELSE statement.The DECODE function decodes an expression in a way similar to the IF-THEN-ELSE logic used in various languages. The DECODE function decodes expression after comparing it to each search value. If the expression is the same as search, result is returned.If the default value is omitted, a null value is returned where a search value does not match any of the result values.Syntax –DECODE(col|expression, search1, result1
[, search2, result2,...,][, default])
Example –SELECT last_name, job_id, salary,
DECODE(job_id, ’IT_PROG’, 1.10*salary,
’ST_CLERK’, 1.15*salary,
’SA_REP’, 1.20*salary,salary)
REVISED_SALARY FROM employees;
Output :
Syntax –
DECODE(col|expression, search1, result1
[, search2, result2,...,][, default])
Example –
SELECT last_name, job_id, salary,
DECODE(job_id, ’IT_PROG’, 1.10*salary,
’ST_CLERK’, 1.15*salary,
’SA_REP’, 1.20*salary,salary)
REVISED_SALARY FROM employees;
Output :
COALESCE() : The COALESCE() function examines the first expression, if the first expression is not null, it returns that expression; Otherwise, it does a COALESCE of the remaining expressions.The advantage of the COALESCE() function over the NVL() function is that the COALESCE function can take multiple alternate values. In simple words COALESCE() function returns the first non-null expression in the list.Syntax –COALESCE (expr_1, expr_2, ... expr_n)
Examples –SELECT last_name,
COALESCE(commission_pct, salary, 10) comm
FROM employees ORDER BY commission_pct;
Output :
Syntax –
COALESCE (expr_1, expr_2, ... expr_n)
Examples –
SELECT last_name,
COALESCE(commission_pct, salary, 10) comm
FROM employees ORDER BY commission_pct;
Output :
NULLIF() : The NULLIF function compares two expressions. If they are equal, the function returns null. If they are not equal, the function returns the first expression. You cannot specify the literal NULL for first expression.Syntax –NULLIF (expr_1, expr_2)
Examples –SELECT LENGTH(first_name) "expr1",
LENGTH(last_name) "expr2",
NULLIF(LENGTH(first_name),LENGTH(last_name))
result FROM employees;
Output :
Syntax –
NULLIF (expr_1, expr_2)
Examples –
SELECT LENGTH(first_name) "expr1",
LENGTH(last_name) "expr2",
NULLIF(LENGTH(first_name),LENGTH(last_name))
result FROM employees;
Output :
LNNVL() : LNNVL evaluate a condition when one or both operands of the condition may be null. The function can be used only in the WHERE clause of a query. It takes as an argument a condition and returns TRUE if the condition is FALSE or UNKNOWN and FALSE if the condition is TRUE.Syntax –LNNVL( condition(s) )
Examples –SELECT COUNT(*) FROM employees
WHERE commission_pct < .2;
Output :
Syntax –
LNNVL( condition(s) )
Examples –
SELECT COUNT(*) FROM employees
WHERE commission_pct < .2;
Output :
Now the above examples does not considered those employees who have no commission at all.To include them as well we use LNNVL()
SELECT COUNT(*) FROM employees
WHERE LNNVL(commission_pct >= .2);
Output :
NANVL() : The NANVL function is useful only for floating-point numbers of type BINARY_FLOAT or BINARY_DOUBLE. It instructs the Database to return an alternative value n2 if the input value n1 is NaN (not a number). If n1 is not NaN, then database returns n1. This function is useful for mapping NaN values to NULL.Syntax –NANVL( n1 , n2 )Consider the following table named nanvl_demo :Example –SELECT bin_float, NANVL(bin_float,0)
FROM nanvl_demo;
Output :
Syntax –
NANVL( n1 , n2 )
Consider the following table named nanvl_demo :
Example –
SELECT bin_float, NANVL(bin_float,0)
FROM nanvl_demo;
Output :
Reference: Introduction to Oracle9i SQL(Volume-1 Book)
PAWANLAKHOTIA
SQL-Functions
SQL
Technical Scripter
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
SQL | Sub queries in From Clause
MySQL | Group_CONCAT() Function
SQL Correlated Subqueries
Window functions in SQL
MySQL | Regular expressions (Regexp)
What is Temporary Table in SQL?
Difference between Where and Having Clause in SQL
SQL | DDL, DML, TCL and DCL
SQL using Python
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n18 Dec, 2019"
},
{
"code": null,
"e": 192,
"s": 52,
"text": "In this article, we’ll be discussing some powerful SQL general functions, which are – NVL, NVL2, DECODE, COALESCE, NULLIF, LNNVL and NANVL."
},
{
"code": null,
"e": 361,
"s": 192,
"text": "These functions work with any data type and pertain to the use of null values in the expression list. These are all single row function i.e. provide one result per row."
},
{
"code": null,
"e": 866,
"s": 361,
"text": "NVL(expr1, expr2) : In SQL, NVL() converts a null value to an actual value. Data types that can be used are date, character and number. Data type must match with each other i.e. expr1 and expr2 must of same data type.Syntax –NVL (expr1, expr2)\nexpr1 is the source value or expression that may contain a null.expr2 is the target value for converting the null.Example –SELECT salary, NVL(commission_pct, 0),\n (salary*12) + (salary*12*NVL(commission_pct, 0))\n annual_salary FROM employees;\nOutput :"
},
{
"code": null,
"e": 886,
"s": 866,
"text": "NVL (expr1, expr2)\n"
},
{
"code": null,
"e": 1001,
"s": 886,
"text": "expr1 is the source value or expression that may contain a null.expr2 is the target value for converting the null."
},
{
"code": null,
"e": 1011,
"s": 1001,
"text": "Example –"
},
{
"code": null,
"e": 1141,
"s": 1011,
"text": "SELECT salary, NVL(commission_pct, 0),\n (salary*12) + (salary*12*NVL(commission_pct, 0))\n annual_salary FROM employees;\n"
},
{
"code": null,
"e": 1150,
"s": 1141,
"text": "Output :"
},
{
"code": null,
"e": 1829,
"s": 1150,
"text": "NVL2(expr1, expr2, expr3) : The NVL2 function examines the first expression. If the first expression is not null, then the NVL2 function returns the second expression. If the first expression is null, then the third expression is returned i.e. If expr1 is not null, NVL2 returns expr2. If expr1 is null, NVL2 returns expr3. The argument expr1 can have any data type.Syntax –NVL2 (expr1, expr2, expr3)\nexpr1 is the source value or expression that may contain nullexpr2 is the value returned if expr1 is not nullexpr3 is the value returned if expr1 is nullExample –SELECT last_name, salary, commission_pct,\n NVL2(commission_pct, ’SAL+COMM’, ’SAL’)\n income FROM employees;\nOutput :"
},
{
"code": null,
"e": 1838,
"s": 1829,
"text": "Syntax –"
},
{
"code": null,
"e": 1866,
"s": 1838,
"text": "NVL2 (expr1, expr2, expr3)\n"
},
{
"code": null,
"e": 2020,
"s": 1866,
"text": "expr1 is the source value or expression that may contain nullexpr2 is the value returned if expr1 is not nullexpr3 is the value returned if expr1 is null"
},
{
"code": null,
"e": 2030,
"s": 2020,
"text": "Example –"
},
{
"code": null,
"e": 2138,
"s": 2030,
"text": "SELECT last_name, salary, commission_pct,\n NVL2(commission_pct, ’SAL+COMM’, ’SAL’)\n income FROM employees;\n"
},
{
"code": null,
"e": 2147,
"s": 2138,
"text": "Output :"
},
{
"code": null,
"e": 2899,
"s": 2147,
"text": "DECODE() : Facilitates conditional inquiries by doing the work of a CASE or IF-THEN-ELSE statement.The DECODE function decodes an expression in a way similar to the IF-THEN-ELSE logic used in various languages. The DECODE function decodes expression after comparing it to each search value. If the expression is the same as search, result is returned.If the default value is omitted, a null value is returned where a search value does not match any of the result values.Syntax –DECODE(col|expression, search1, result1 \n [, search2, result2,...,][, default])\nExample –SELECT last_name, job_id, salary,\n DECODE(job_id, ’IT_PROG’, 1.10*salary,\n ’ST_CLERK’, 1.15*salary,\n ’SA_REP’, 1.20*salary,salary) \n REVISED_SALARY FROM employees;\nOutput :"
},
{
"code": null,
"e": 2908,
"s": 2899,
"text": "Syntax –"
},
{
"code": null,
"e": 2989,
"s": 2908,
"text": "DECODE(col|expression, search1, result1 \n [, search2, result2,...,][, default])\n"
},
{
"code": null,
"e": 2999,
"s": 2989,
"text": "Example –"
},
{
"code": null,
"e": 3176,
"s": 2999,
"text": "SELECT last_name, job_id, salary,\n DECODE(job_id, ’IT_PROG’, 1.10*salary,\n ’ST_CLERK’, 1.15*salary,\n ’SA_REP’, 1.20*salary,salary) \n REVISED_SALARY FROM employees;\n"
},
{
"code": null,
"e": 3185,
"s": 3176,
"text": "Output :"
},
{
"code": null,
"e": 3768,
"s": 3185,
"text": "COALESCE() : The COALESCE() function examines the first expression, if the first expression is not null, it returns that expression; Otherwise, it does a COALESCE of the remaining expressions.The advantage of the COALESCE() function over the NVL() function is that the COALESCE function can take multiple alternate values. In simple words COALESCE() function returns the first non-null expression in the list.Syntax –COALESCE (expr_1, expr_2, ... expr_n)\nExamples –SELECT last_name, \n COALESCE(commission_pct, salary, 10) comm\n FROM employees ORDER BY commission_pct;\nOutput :"
},
{
"code": null,
"e": 3777,
"s": 3768,
"text": "Syntax –"
},
{
"code": null,
"e": 3816,
"s": 3777,
"text": "COALESCE (expr_1, expr_2, ... expr_n)\n"
},
{
"code": null,
"e": 3827,
"s": 3816,
"text": "Examples –"
},
{
"code": null,
"e": 3937,
"s": 3827,
"text": "SELECT last_name, \n COALESCE(commission_pct, salary, 10) comm\n FROM employees ORDER BY commission_pct;\n"
},
{
"code": null,
"e": 3946,
"s": 3937,
"text": "Output :"
},
{
"code": null,
"e": 4363,
"s": 3946,
"text": "NULLIF() : The NULLIF function compares two expressions. If they are equal, the function returns null. If they are not equal, the function returns the first expression. You cannot specify the literal NULL for first expression.Syntax –NULLIF (expr_1, expr_2)\nExamples –SELECT LENGTH(first_name) \"expr1\",\n LENGTH(last_name) \"expr2\",\n NULLIF(LENGTH(first_name),LENGTH(last_name))\n result FROM employees;\nOutput :"
},
{
"code": null,
"e": 4372,
"s": 4363,
"text": "Syntax –"
},
{
"code": null,
"e": 4397,
"s": 4372,
"text": "NULLIF (expr_1, expr_2)\n"
},
{
"code": null,
"e": 4408,
"s": 4397,
"text": "Examples –"
},
{
"code": null,
"e": 4549,
"s": 4408,
"text": "SELECT LENGTH(first_name) \"expr1\",\n LENGTH(last_name) \"expr2\",\n NULLIF(LENGTH(first_name),LENGTH(last_name))\n result FROM employees;\n"
},
{
"code": null,
"e": 4558,
"s": 4549,
"text": "Output :"
},
{
"code": null,
"e": 4953,
"s": 4558,
"text": "LNNVL() : LNNVL evaluate a condition when one or both operands of the condition may be null. The function can be used only in the WHERE clause of a query. It takes as an argument a condition and returns TRUE if the condition is FALSE or UNKNOWN and FALSE if the condition is TRUE.Syntax –LNNVL( condition(s) )\nExamples –SELECT COUNT(*) FROM employees \n WHERE commission_pct < .2; \nOutput :"
},
{
"code": null,
"e": 4962,
"s": 4953,
"text": "Syntax –"
},
{
"code": null,
"e": 4985,
"s": 4962,
"text": "LNNVL( condition(s) )\n"
},
{
"code": null,
"e": 4996,
"s": 4985,
"text": "Examples –"
},
{
"code": null,
"e": 5063,
"s": 4996,
"text": "SELECT COUNT(*) FROM employees \n WHERE commission_pct < .2; \n"
},
{
"code": null,
"e": 5072,
"s": 5063,
"text": "Output :"
},
{
"code": null,
"e": 5200,
"s": 5072,
"text": "Now the above examples does not considered those employees who have no commission at all.To include them as well we use LNNVL()"
},
{
"code": null,
"e": 5271,
"s": 5200,
"text": "SELECT COUNT(*) FROM employees \n WHERE LNNVL(commission_pct >= .2); \n"
},
{
"code": null,
"e": 5280,
"s": 5271,
"text": "Output :"
},
{
"code": null,
"e": 5739,
"s": 5280,
"text": "NANVL() : The NANVL function is useful only for floating-point numbers of type BINARY_FLOAT or BINARY_DOUBLE. It instructs the Database to return an alternative value n2 if the input value n1 is NaN (not a number). If n1 is not NaN, then database returns n1. This function is useful for mapping NaN values to NULL.Syntax –NANVL( n1 , n2 )Consider the following table named nanvl_demo :Example –SELECT bin_float, NANVL(bin_float,0)\n FROM nanvl_demo;\nOutput :"
},
{
"code": null,
"e": 5748,
"s": 5739,
"text": "Syntax –"
},
{
"code": null,
"e": 5765,
"s": 5748,
"text": "NANVL( n1 , n2 )"
},
{
"code": null,
"e": 5813,
"s": 5765,
"text": "Consider the following table named nanvl_demo :"
},
{
"code": null,
"e": 5823,
"s": 5813,
"text": "Example –"
},
{
"code": null,
"e": 5880,
"s": 5823,
"text": "SELECT bin_float, NANVL(bin_float,0)\n FROM nanvl_demo;\n"
},
{
"code": null,
"e": 5889,
"s": 5880,
"text": "Output :"
},
{
"code": null,
"e": 5944,
"s": 5889,
"text": "Reference: Introduction to Oracle9i SQL(Volume-1 Book)"
},
{
"code": null,
"e": 5958,
"s": 5944,
"text": "PAWANLAKHOTIA"
},
{
"code": null,
"e": 5972,
"s": 5958,
"text": "SQL-Functions"
},
{
"code": null,
"e": 5976,
"s": 5972,
"text": "SQL"
},
{
"code": null,
"e": 5995,
"s": 5976,
"text": "Technical Scripter"
},
{
"code": null,
"e": 5999,
"s": 5995,
"text": "SQL"
},
{
"code": null,
"e": 6097,
"s": 5999,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6163,
"s": 6097,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 6196,
"s": 6163,
"text": "SQL | Sub queries in From Clause"
},
{
"code": null,
"e": 6228,
"s": 6196,
"text": "MySQL | Group_CONCAT() Function"
},
{
"code": null,
"e": 6254,
"s": 6228,
"text": "SQL Correlated Subqueries"
},
{
"code": null,
"e": 6278,
"s": 6254,
"text": "Window functions in SQL"
},
{
"code": null,
"e": 6315,
"s": 6278,
"text": "MySQL | Regular expressions (Regexp)"
},
{
"code": null,
"e": 6347,
"s": 6315,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 6397,
"s": 6347,
"text": "Difference between Where and Having Clause in SQL"
},
{
"code": null,
"e": 6425,
"s": 6397,
"text": "SQL | DDL, DML, TCL and DCL"
}
] |
Rock Paper and Scissor Game Using Tkinter
|
13 Sep, 2021
Prerequisite: Tkinter, random
Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter is the fastest and easiest way to create GUI applications.
In this article, we will see how we can create a rock paper and scissor game using Tkinter. Rock paper scissor is a hand game usually played between two people, in which each player simultaneously forms one of three shapes with an outstretched hand. These shapes are “rock”, “paper”, and “scissors”.
Game Winner Condition:
Paper and Scissor =>Scissor win
Rock and Scissor =>Rock win
Paper and Rock =>Paper win
Rock Paper and Scissor Game Using Python Tkinter | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersRock Paper and Scissor Game Using Python Tkinter | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 1:01:38•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=NLxw-1VhiKI" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Below is what the GUI looks like:-
GUI Implementation Steps (Add Button, Label, Frame)
Create a head label that will show the title of the game, set its font and properties
Below the head, label create a user label that will show the hand sign selected by the user
Create a computer label that will show hand sign picked by the computer
In between the user and the computer label create a label to show the text “vs”
Create a result label to show the result set font and other properties to it
Create three pushbuttons for rock, paper, and scissor respectively
Create a reset button to reset the game
Backend Implementation Steps:
We will create five functions; one is for reset the game, the second is for disabling the button and the other are for game winners
Below is the Implementation:-
Python3
# Import Required Libraryfrom tkinter import *import random # Create Objectroot = Tk() # Set geometryroot.geometry("300x300") # Set titleroot.title("Rock Paper Scissor Game") # Computer Valuecomputer_value = { "0":"Rock", "1":"Paper", "2":"Scissor"} # Reset The Gamedef reset_game(): b1["state"] = "active" b2["state"] = "active" b3["state"] = "active" l1.config(text = "Player ") l3.config(text = "Computer") l4.config(text = "") # Disable the Buttondef button_disable(): b1["state"] = "disable" b2["state"] = "disable" b3["state"] = "disable" # If player selected rockdef isrock(): c_v = computer_value[str(random.randint(0,2))] if c_v == "Rock": match_result = "Match Draw" elif c_v=="Scissor": match_result = "Player Win" else: match_result = "Computer Win" l4.config(text = match_result) l1.config(text = "Rock ") l3.config(text = c_v) button_disable() # If player selected paperdef ispaper(): c_v = computer_value[str(random.randint(0, 2))] if c_v == "Paper": match_result = "Match Draw" elif c_v=="Scissor": match_result = "Computer Win" else: match_result = "Player Win" l4.config(text = match_result) l1.config(text = "Paper ") l3.config(text = c_v) button_disable() # If player selected scissordef isscissor(): c_v = computer_value[str(random.randint(0,2))] if c_v == "Rock": match_result = "Computer Win" elif c_v == "Scissor": match_result = "Match Draw" else: match_result = "Player Win" l4.config(text = match_result) l1.config(text = "Scissor ") l3.config(text = c_v) button_disable() # Add Labels, Frames and ButtonLabel(root, text = "Rock Paper Scissor", font = "normal 20 bold", fg = "blue").pack(pady = 20) frame = Frame(root)frame.pack() l1 = Label(frame, text = "Player ", font = 10) l2 = Label(frame, text = "VS ", font = "normal 10 bold") l3 = Label(frame, text = "Computer", font = 10) l1.pack(side = LEFT)l2.pack(side = LEFT)l3.pack() l4 = Label(root, text = "", font = "normal 20 bold", bg = "white", width = 15 , borderwidth = 2, relief = "solid")l4.pack(pady = 20) frame1 = Frame(root)frame1.pack() b1 = Button(frame1, text = "Rock", font = 10, width = 7, command = isrock) b2 = Button(frame1, text = "Paper ", font = 10, width = 7, command = ispaper) b3 = Button(frame1, text = "Scissor", font = 10, width = 7, command = isscissor) b1.pack(side = LEFT, padx = 10)b2.pack(side = LEFT,padx = 10)b3.pack(padx = 10) Button(root, text = "Reset Game", font = 10, fg = "red", bg = "black", command = reset_game).pack(pady = 20) # Execute Tkinterroot.mainloop()
Output:
ruhelaa48
Python Tkinter-exercises
Python Tkinter-projects
Python-tkinter
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
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 Sep, 2021"
},
{
"code": null,
"e": 58,
"s": 28,
"text": "Prerequisite: Tkinter, random"
},
{
"code": null,
"e": 364,
"s": 58,
"text": "Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter is the fastest and easiest way to create GUI applications."
},
{
"code": null,
"e": 664,
"s": 364,
"text": "In this article, we will see how we can create a rock paper and scissor game using Tkinter. Rock paper scissor is a hand game usually played between two people, in which each player simultaneously forms one of three shapes with an outstretched hand. These shapes are “rock”, “paper”, and “scissors”."
},
{
"code": null,
"e": 687,
"s": 664,
"text": "Game Winner Condition:"
},
{
"code": null,
"e": 719,
"s": 687,
"text": "Paper and Scissor =>Scissor win"
},
{
"code": null,
"e": 747,
"s": 719,
"text": "Rock and Scissor =>Rock win"
},
{
"code": null,
"e": 774,
"s": 747,
"text": "Paper and Rock =>Paper win"
},
{
"code": null,
"e": 1691,
"s": 774,
"text": "Rock Paper and Scissor Game Using Python Tkinter | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersRock Paper and Scissor Game Using Python Tkinter | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 1:01:38•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=NLxw-1VhiKI\" 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": 1726,
"s": 1691,
"text": "Below is what the GUI looks like:-"
},
{
"code": null,
"e": 1778,
"s": 1726,
"text": "GUI Implementation Steps (Add Button, Label, Frame)"
},
{
"code": null,
"e": 1864,
"s": 1778,
"text": "Create a head label that will show the title of the game, set its font and properties"
},
{
"code": null,
"e": 1956,
"s": 1864,
"text": "Below the head, label create a user label that will show the hand sign selected by the user"
},
{
"code": null,
"e": 2028,
"s": 1956,
"text": "Create a computer label that will show hand sign picked by the computer"
},
{
"code": null,
"e": 2108,
"s": 2028,
"text": "In between the user and the computer label create a label to show the text “vs”"
},
{
"code": null,
"e": 2185,
"s": 2108,
"text": "Create a result label to show the result set font and other properties to it"
},
{
"code": null,
"e": 2252,
"s": 2185,
"text": "Create three pushbuttons for rock, paper, and scissor respectively"
},
{
"code": null,
"e": 2292,
"s": 2252,
"text": "Create a reset button to reset the game"
},
{
"code": null,
"e": 2322,
"s": 2292,
"text": "Backend Implementation Steps:"
},
{
"code": null,
"e": 2454,
"s": 2322,
"text": "We will create five functions; one is for reset the game, the second is for disabling the button and the other are for game winners"
},
{
"code": null,
"e": 2484,
"s": 2454,
"text": "Below is the Implementation:-"
},
{
"code": null,
"e": 2492,
"s": 2484,
"text": "Python3"
},
{
"code": "# Import Required Libraryfrom tkinter import *import random # Create Objectroot = Tk() # Set geometryroot.geometry(\"300x300\") # Set titleroot.title(\"Rock Paper Scissor Game\") # Computer Valuecomputer_value = { \"0\":\"Rock\", \"1\":\"Paper\", \"2\":\"Scissor\"} # Reset The Gamedef reset_game(): b1[\"state\"] = \"active\" b2[\"state\"] = \"active\" b3[\"state\"] = \"active\" l1.config(text = \"Player \") l3.config(text = \"Computer\") l4.config(text = \"\") # Disable the Buttondef button_disable(): b1[\"state\"] = \"disable\" b2[\"state\"] = \"disable\" b3[\"state\"] = \"disable\" # If player selected rockdef isrock(): c_v = computer_value[str(random.randint(0,2))] if c_v == \"Rock\": match_result = \"Match Draw\" elif c_v==\"Scissor\": match_result = \"Player Win\" else: match_result = \"Computer Win\" l4.config(text = match_result) l1.config(text = \"Rock \") l3.config(text = c_v) button_disable() # If player selected paperdef ispaper(): c_v = computer_value[str(random.randint(0, 2))] if c_v == \"Paper\": match_result = \"Match Draw\" elif c_v==\"Scissor\": match_result = \"Computer Win\" else: match_result = \"Player Win\" l4.config(text = match_result) l1.config(text = \"Paper \") l3.config(text = c_v) button_disable() # If player selected scissordef isscissor(): c_v = computer_value[str(random.randint(0,2))] if c_v == \"Rock\": match_result = \"Computer Win\" elif c_v == \"Scissor\": match_result = \"Match Draw\" else: match_result = \"Player Win\" l4.config(text = match_result) l1.config(text = \"Scissor \") l3.config(text = c_v) button_disable() # Add Labels, Frames and ButtonLabel(root, text = \"Rock Paper Scissor\", font = \"normal 20 bold\", fg = \"blue\").pack(pady = 20) frame = Frame(root)frame.pack() l1 = Label(frame, text = \"Player \", font = 10) l2 = Label(frame, text = \"VS \", font = \"normal 10 bold\") l3 = Label(frame, text = \"Computer\", font = 10) l1.pack(side = LEFT)l2.pack(side = LEFT)l3.pack() l4 = Label(root, text = \"\", font = \"normal 20 bold\", bg = \"white\", width = 15 , borderwidth = 2, relief = \"solid\")l4.pack(pady = 20) frame1 = Frame(root)frame1.pack() b1 = Button(frame1, text = \"Rock\", font = 10, width = 7, command = isrock) b2 = Button(frame1, text = \"Paper \", font = 10, width = 7, command = ispaper) b3 = Button(frame1, text = \"Scissor\", font = 10, width = 7, command = isscissor) b1.pack(side = LEFT, padx = 10)b2.pack(side = LEFT,padx = 10)b3.pack(padx = 10) Button(root, text = \"Reset Game\", font = 10, fg = \"red\", bg = \"black\", command = reset_game).pack(pady = 20) # Execute Tkinterroot.mainloop()",
"e": 5406,
"s": 2492,
"text": null
},
{
"code": null,
"e": 5418,
"s": 5410,
"text": "Output:"
},
{
"code": null,
"e": 5432,
"s": 5422,
"text": "ruhelaa48"
},
{
"code": null,
"e": 5457,
"s": 5432,
"text": "Python Tkinter-exercises"
},
{
"code": null,
"e": 5481,
"s": 5457,
"text": "Python Tkinter-projects"
},
{
"code": null,
"e": 5496,
"s": 5481,
"text": "Python-tkinter"
},
{
"code": null,
"e": 5503,
"s": 5496,
"text": "Python"
},
{
"code": null,
"e": 5601,
"s": 5503,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5619,
"s": 5601,
"text": "Python Dictionary"
},
{
"code": null,
"e": 5661,
"s": 5619,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 5683,
"s": 5661,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 5718,
"s": 5683,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 5744,
"s": 5718,
"text": "Python String | replace()"
},
{
"code": null,
"e": 5776,
"s": 5744,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 5805,
"s": 5776,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 5832,
"s": 5805,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 5862,
"s": 5832,
"text": "Iterate over a list in Python"
}
] |
What does javascript:void(0) mean?
|
11 Oct, 2019
You might have occasionally came across “javascript:void(0)” in an HTML Document. It is often used when inserting an expression in a web page might produce some unwanted effect. To remove this effect, “javascript:void(0)” is used. This expression returns undefined primitive value.This is often used with hyperlinks.Sometimes, you will decide to call some JavaScript from inside a link. Normally, when you click a link, the browser loads a brand new page or refreshes the same page (depending on the URL specified).But you most likely don’t desire this to happen if you have hooked up some JavaScript thereto link.
To prevent the page from refreshing, you could use void(0).
Using “#” in anchor tag: When writing the following code in the editor, the web page is refreshed after the alert message is shown.Example:
<!DOCTYPE html><html> <head> <title>without JavaScript:void(0)</title></head> <body> <center> <h1 style="color:green">GeksforGeeks</h1> <h3>without JavaScript:void(0)</h3> <a href="#" ondblclick="alert('Welcome to Geeks for Geeks')"> Double click on me </a> </center></body> </html>
Output:
Using “javascript:void(0);” in anchor tag: Writing “javascript:void(0);” in anchor tag can prevent the page to reload and JavaScript functions can be called on single or double clicks easily.Example:
<!DOCTYPE html><html> <head> <title>JavaScript:void(0)</title></head> <body> <center> <h1 style="color:green">GeksforGeeks</h1> <h3>JavaScript:void(0)</h3> <a href="javascript:void(0);" ondblclick="alert('Welcome to Geeks for Geeks')">Double click on me </a> </center></body> </html>
Output:
JavaScript-Misc
Picked
JavaScript
Technical Scripter
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n11 Oct, 2019"
},
{
"code": null,
"e": 669,
"s": 54,
"text": "You might have occasionally came across “javascript:void(0)” in an HTML Document. It is often used when inserting an expression in a web page might produce some unwanted effect. To remove this effect, “javascript:void(0)” is used. This expression returns undefined primitive value.This is often used with hyperlinks.Sometimes, you will decide to call some JavaScript from inside a link. Normally, when you click a link, the browser loads a brand new page or refreshes the same page (depending on the URL specified).But you most likely don’t desire this to happen if you have hooked up some JavaScript thereto link."
},
{
"code": null,
"e": 729,
"s": 669,
"text": "To prevent the page from refreshing, you could use void(0)."
},
{
"code": null,
"e": 869,
"s": 729,
"text": "Using “#” in anchor tag: When writing the following code in the editor, the web page is refreshed after the alert message is shown.Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title>without JavaScript:void(0)</title></head> <body> <center> <h1 style=\"color:green\">GeksforGeeks</h1> <h3>without JavaScript:void(0)</h3> <a href=\"#\" ondblclick=\"alert('Welcome to Geeks for Geeks')\"> Double click on me </a> </center></body> </html>",
"e": 1196,
"s": 869,
"text": null
},
{
"code": null,
"e": 1204,
"s": 1196,
"text": "Output:"
},
{
"code": null,
"e": 1404,
"s": 1204,
"text": "Using “javascript:void(0);” in anchor tag: Writing “javascript:void(0);” in anchor tag can prevent the page to reload and JavaScript functions can be called on single or double clicks easily.Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title>JavaScript:void(0)</title></head> <body> <center> <h1 style=\"color:green\">GeksforGeeks</h1> <h3>JavaScript:void(0)</h3> <a href=\"javascript:void(0);\" ondblclick=\"alert('Welcome to Geeks for Geeks')\">Double click on me </a> </center></body> </html>",
"e": 1732,
"s": 1404,
"text": null
},
{
"code": null,
"e": 1740,
"s": 1732,
"text": "Output:"
},
{
"code": null,
"e": 1756,
"s": 1740,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 1763,
"s": 1756,
"text": "Picked"
},
{
"code": null,
"e": 1774,
"s": 1763,
"text": "JavaScript"
},
{
"code": null,
"e": 1793,
"s": 1774,
"text": "Technical Scripter"
},
{
"code": null,
"e": 1810,
"s": 1793,
"text": "Web Technologies"
},
{
"code": null,
"e": 1837,
"s": 1810,
"text": "Web technologies Questions"
}
] |
Largest Independent Set Problem | DP-26
|
19 Jul, 2021
Given a Binary Tree, find size of the Largest Independent Set(LIS) in it. A subset of all tree nodes is an independent set if there is no edge between any two nodes of the subset.
For example, consider the following binary tree. The largest independent set(LIS) is {10, 40, 60, 70, 80} and size of the LIS is 5.
A Dynamic Programming solution solves a given problem using solutions of subproblems in bottom up manner. Can the given problem be solved using solutions to subproblems? If yes, then what are the subproblems? Can we find largest independent set size (LISS) for a node X if we know LISS for all descendants of X? If a node is considered as part of LIS, then its children cannot be part of LIS, but its grandchildren can be. Following is optimal substructure property.
1) Optimal Substructure: Let LISS(X) indicates size of largest independent set of a tree with root X.
LISS(X) = MAX { (1 + sum of LISS for all grandchildren of X),
(sum of LISS for all children of X) }
The idea is simple, there are two possibilities for every node X, either X is a member of the set or not a member. If X is a member, then the value of LISS(X) is 1 plus LISS of all grandchildren. If X is not a member, then the value is sum of LISS of all children.
2) Overlapping Subproblems Following is recursive implementation that simply follows the recursive structure mentioned above.
C++
C
Java
Python3
C#
Javascript
// A naive recursive implementation of// Largest Independent Set problem#include <bits/stdc++.h>using namespace std; // A utility function to find// max of two integersint max(int x, int y){ return (x > y) ? x : y;} /* A binary tree node has data,pointer to left child and apointer to right child */class node{ public: int data; node *left, *right;}; // The function returns size of the// largest independent set in a given// binary treeint LISS(node *root){ if (root == NULL) return 0; // Calculate size excluding the current node int size_excl = LISS(root->left) + LISS(root->right); // Calculate size including the current node int size_incl = 1; if (root->left) size_incl += LISS(root->left->left) + LISS(root->left->right); if (root->right) size_incl += LISS(root->right->left) + LISS(root->right->right); // Return the maximum of two sizes return max(size_incl, size_excl);} // A utility function to create a nodenode* newNode( int data ){ node* temp = new node(); temp->data = data; temp->left = temp->right = NULL; return temp;} // Driver Codeint main(){ // Let us construct the tree // given in the above diagram node *root = newNode(20); root->left = newNode(8); root->left->left = newNode(4); root->left->right = newNode(12); root->left->right->left = newNode(10); root->left->right->right = newNode(14); root->right = newNode(22); root->right->right = newNode(25); cout << "Size of the Largest" << " Independent Set is " << LISS(root); return 0;} // This is code is contributed// by rathbhupendra
// A naive recursive implementation of Largest Independent Set problem#include <stdio.h>#include <stdlib.h> // A utility function to find max of two integersint max(int x, int y) { return (x > y)? x: y; } /* A binary tree node has data, pointer to left child and a pointer to right child */struct node{ int data; struct node *left, *right;}; // The function returns size of the largest independent set in a given// binary treeint LISS(struct node *root){ if (root == NULL) return 0; // Calculate size excluding the current node int size_excl = LISS(root->left) + LISS(root->right); // Calculate size including the current node int size_incl = 1; if (root->left) size_incl += LISS(root->left->left) + LISS(root->left->right); if (root->right) size_incl += LISS(root->right->left) + LISS(root->right->right); // Return the maximum of two sizes return max(size_incl, size_excl);} // A utility function to create a nodestruct node* newNode( int data ){ struct node* temp = (struct node *) malloc( sizeof(struct node) ); temp->data = data; temp->left = temp->right = NULL; return temp;} // Driver program to test above functionsint main(){ // Let us construct the tree given in the above diagram struct node *root = newNode(20); root->left = newNode(8); root->left->left = newNode(4); root->left->right = newNode(12); root->left->right->left = newNode(10); root->left->right->right = newNode(14); root->right = newNode(22); root->right->right = newNode(25); printf ("Size of the Largest Independent Set is %d ", LISS(root)); return 0;}
// A naive recursive implementation of// Largest Independent Set problemclass GFG { // A utility function to find// max of two integersstatic int max(int x, int y){ return (x > y) ? x : y;} /* A binary tree node has data,pointer to left child and apointer to right child */static class Node{ int data; Node left, right;}; // The function returns size of the// largest independent set in a given// binary treestatic int LISS(Node root){ if (root == null) return 0; // Calculate size excluding the current node int size_excl = LISS(root.left) + LISS(root.right); // Calculate size including the current node int size_incl = 1; if (root.left!=null) size_incl += LISS(root.left.left) + LISS(root.left.right); if (root.right!=null) size_incl += LISS(root.right.left) + LISS(root.right.right); // Return the maximum of two sizes return max(size_incl, size_excl);} // A utility function to create a nodestatic Node newNode( int data ){ Node temp = new Node(); temp.data = data; temp.left = temp.right = null; return temp;} // Driver Codepublic static void main(String args[]) { // Let us construct the tree // given in the above diagram Node root = newNode(20); root.left = newNode(8); root.left.left = newNode(4); root.left.right = newNode(12); root.left.right.left = newNode(10); root.left.right.right = newNode(14); root.right = newNode(22); root.right.right = newNode(25); System.out.println("Size of the Largest" + " Independent Set is " + LISS(root)); }} // This code has been contributed by 29AjayKumar
# A naive recursive implementation of# Largest Independent Set problem # A utility function to find# max of two integersdef max(x, y): if(x > y): return x else: return y # A binary tree node has data,#pointer to left child and a#pointer to right childclass node : def __init__(self): self.data = 0 self.left = self.right = None # The function returns size of the# largest independent set in a given# binary treedef LISS(root): if (root == None) : return 0 # Calculate size excluding the current node size_excl = LISS(root.left) + LISS(root.right) # Calculate size including the current node size_incl = 1 if (root.left != None): size_incl += LISS(root.left.left) + \ LISS(root.left.right) if (root.right != None): size_incl += LISS(root.right.left) + \ LISS(root.right.right) # Return the maximum of two sizes return max(size_incl, size_excl) # A utility function to create a nodedef newNode( data ) : temp = node() temp.data = data temp.left = temp.right = None return temp # Driver Code # Let us construct the tree# given in the above diagramroot = newNode(20)root.left = newNode(8)root.left.left = newNode(4)root.left.right = newNode(12)root.left.right.left = newNode(10)root.left.right.right = newNode(14)root.right = newNode(22)root.right.right = newNode(25) print( "Size of the Largest" , " Independent Set is " , LISS(root) ) # This code is contributed by Arnab Kundu
// C# program for calculating LISS// using dynamic programmingusing System; class LisTree{ /* A binary tree node has data, pointer to left child and a pointer to right child */ public class node { public int data, liss; public node left, right; public node(int data) { this.data = data; this.liss = 0; } } // A memoization function returns size // of the largest independent set in // a given binary tree static int liss(node root) { if (root == null) return 0; if (root.liss != 0) return root.liss; if (root.left == null && root.right == null) return root.liss = 1; // Calculate size excluding the // current node int liss_excl = liss(root.left) + liss(root.right); // Calculate size including the // current node int liss_incl = 1; if (root.left != null) { liss_incl += (liss(root.left.left) + liss(root.left.right)); } if (root.right != null) { liss_incl += (liss(root.right.left) + liss(root.right.right)); } // Maximum of two sizes is LISS, // store it for future uses. return root.liss = Math.Max(liss_excl, liss_incl); } // Driver code public static void Main(String[] args) { // Let us construct the tree given // in the above diagram node root = new node(20); root.left = new node(8); root.left.left = new node(4); root.left.right = new node(12); root.left.right.left = new node(10); root.left.right.right = new node(14); root.right = new node(22); root.right.right = new node(25); Console.WriteLine("Size of the Largest Independent Set is " + liss(root)); }} // This code is contributed by Princi Singh
<script> // A naive recursive implementation of// Largest Independent Set problem // A utility function to find// max of two integersfunction max(x, y){ return(x > y) ? x : y;} // A binary tree node has data,// pointer to left child and a// pointer to right childclass Node{ constructor(data) { this.data = data; this.left = this.right = null; }} // The function returns size of the// largest independent set in a given// binary treefunction LISS(root){ if (root == null) return 0; // Calculate size excluding the current node let size_excl = LISS(root.left) + LISS(root.right); // Calculate size including the current node let size_incl = 1; if (root.left != null) size_incl += LISS(root.left.left) + LISS(root.left.right); if (root.right != null) size_incl += LISS(root.right.left) + LISS(root.right.right); // Return the maximum of two sizes return max(size_incl, size_excl);} // Driver Code // Let us construct the tree// given in the above diagramlet root = new Node(20);root.left = new Node(8);root.left.left = new Node(4);root.left.right = new Node(12);root.left.right.left = new Node(10);root.left.right.right = new Node(14);root.right = new Node(22);root.right.right = new Node(25); document.write("Size of the Largest" + " Independent Set is " + LISS(root)); // This code is contributed by avanitrachhadiya2155 </script>
Output:
Size of the Largest Independent Set is 5
Time complexity of the above naive recursive approach is exponential. It should be noted that the above function computes the same subproblems again and again. For example, LISS of node with value 50 is evaluated for node with values 10 and 20 as 50 is grandchild of 10 and child of 20.
Since same subproblems are called again, this problem has Overlapping Subproblems property. So LISS problem has both properties (see this and this) of a dynamic programming problem. Like other typical Dynamic Programming(DP) problems, recomputations of same subproblems can be avoided by storing the solutions to subproblems and solving problems in bottom up manner.
Following are implementation of Dynamic Programming based solution. In the following solution, an additional field ‘liss’ is added to tree nodes. The initial value of ‘liss’ is set as 0 for all nodes. The recursive function LISS() calculates ‘liss’ for a node only if it is not already set.
C++
C
Java
Python3
C#
Javascript
/* Dynamic programming based programfor Largest Independent Set problem */#include <bits/stdc++.h>using namespace std; // A utility function to find max of two integersint max(int x, int y) { return (x > y)? x: y; } /* A binary tree node has data, pointerto left child and a pointer toright child */class node{ public: int data; int liss; node *left, *right;}; // A memoization function returns size// of the largest independent set in// a given binary treeint LISS(node *root){ if (root == NULL) return 0; if (root->liss) return root->liss; if (root->left == NULL && root->right == NULL) return (root->liss = 1); // Calculate size excluding the current node int liss_excl = LISS(root->left) + LISS(root->right); // Calculate size including the current node int liss_incl = 1; if (root->left) liss_incl += LISS(root->left->left) + LISS(root->left->right); if (root->right) liss_incl += LISS(root->right->left) + LISS(root->right->right); // Maximum of two sizes is LISS, store it for future uses. root->liss = max(liss_incl, liss_excl); return root->liss;} // A utility function to create a nodenode* newNode(int data){ node* temp = new node(); temp->data = data; temp->left = temp->right = NULL; temp->liss = 0; return temp;} // Driver codeint main(){ // Let us construct the tree // given in the above diagram node *root = newNode(20); root->left = newNode(8); root->left->left = newNode(4); root->left->right = newNode(12); root->left->right->left = newNode(10); root->left->right->right = newNode(14); root->right = newNode(22); root->right->right = newNode(25); cout << "Size of the Largest Independent Set is " << LISS(root); return 0;} // This code is contributed by rathbhupendra
/* Dynamic programming based program for Largest Independent Set problem */#include <stdio.h>#include <stdlib.h> // A utility function to find max of two integersint max(int x, int y) { return (x > y)? x: y; } /* A binary tree node has data, pointer to left child and a pointer to right child */struct node{ int data; int liss; struct node *left, *right;}; // A memoization function returns size of the largest independent set in// a given binary treeint LISS(struct node *root){ if (root == NULL) return 0; if (root->liss) return root->liss; if (root->left == NULL && root->right == NULL) return (root->liss = 1); // Calculate size excluding the current node int liss_excl = LISS(root->left) + LISS(root->right); // Calculate size including the current node int liss_incl = 1; if (root->left) liss_incl += LISS(root->left->left) + LISS(root->left->right); if (root->right) liss_incl += LISS(root->right->left) + LISS(root->right->right); // Maximum of two sizes is LISS, store it for future uses. root->liss = max(liss_incl, liss_excl); return root->liss;} // A utility function to create a nodestruct node* newNode(int data){ struct node* temp = (struct node *) malloc( sizeof(struct node) ); temp->data = data; temp->left = temp->right = NULL; temp->liss = 0; return temp;} // Driver program to test above functionsint main(){ // Let us construct the tree given in the above diagram struct node *root = newNode(20); root->left = newNode(8); root->left->left = newNode(4); root->left->right = newNode(12); root->left->right->left = newNode(10); root->left->right->right = newNode(14); root->right = newNode(22); root->right->right = newNode(25); printf ("Size of the Largest Independent Set is %d ", LISS(root)); return 0;}
// Java program for calculating LISS// using dynamic programming public class LisTree{ /* A binary tree node has data, pointer to left child and a pointer to right child */ static class node { int data, liss; node left, right; public node(int data) { this.data = data; this.liss = 0; } } // A memoization function returns size // of the largest independent set in // a given binary tree static int liss(node root) { if (root == null) return 0; if (root.liss != 0) return root.liss; if (root.left == null && root.right == null) return root.liss = 1; // Calculate size excluding the // current node int liss_excl = liss(root.left) + liss(root.right); // Calculate size including the // current node int liss_incl = 1; if (root.left != null) { liss_incl += (liss(root.left.left) + liss(root.left.right)); } if (root.right != null) { liss_incl += (liss(root.right.left) + liss(root.right.right)); } // Maximum of two sizes is LISS, // store it for future uses. return root.liss = Math.max(liss_excl, liss_incl); } public static void main(String[] args) { // Let us construct the tree given // in the above diagram node root = new node(20); root.left = new node(8); root.left.left = new node(4); root.left.right = new node(12); root.left.right.left = new node(10); root.left.right.right = new node(14); root.right = new node(22); root.right.right = new node(25); System.out.println("Size of the Largest Independent Set is " + liss(root)); }} // This code is contributed by Rishabh Mahrsee
# Python3 program for calculating LISS# using dynamic programming # A binary tree node has data,# pointer to left child and a# pointer to right childclass node: def __init__(self, data): self.data = data self.left = self.right = None self.liss = 0 # A memoization function returns size# of the largest independent set in# a given binary treedef liss(root): if root == None: return 0 if root.liss != 0: return root.liss if (root.left == None and root.right == None): root.liss = 1 return root.liss # Calculate size excluding the # current node liss_excl = (liss(root.left) + liss(root.right)) # Calculate size including the # current node liss_incl = 1 if root.left != None: liss_incl += (liss(root.left.left) + liss(root.left.right)) if root.right != None: liss_incl += (liss(root.right.left) + liss(root.right.right)) # Maximum of two sizes is LISS, # store it for future uses. root.liss = max(liss_excl, liss_incl) return root.liss # Driver Code # Let us construct the tree given# in the above diagramroot = node(20)root.left = node(8)root.left.left = node(4)root.left.right = node(12)root.left.right.left = node(10)root.left.right.right = node(14)root.right = node(22)root.right.right = node(25) print("Size of the Largest Independent "\ "Set is ", liss(root)) # This code is contributed by nishthagoel712
// C# program for calculating LISS// using dynamic programmingusing System; public class LisTree{ /* A binary tree node has data, pointer to left child and a pointer to right child */ public class node { public int data, liss; public node left, right; public node(int data) { this.data = data; this.liss = 0; } } // A memoization function returns size // of the largest independent set in // a given binary tree static int liss(node root) { if (root == null) return 0; if (root.liss != 0) return root.liss; if (root.left == null && root.right == null) return root.liss = 1; // Calculate size excluding the // current node int liss_excl = liss(root.left) + liss(root.right); // Calculate size including the // current node int liss_incl = 1; if (root.left != null) { liss_incl += (liss(root.left.left) + liss(root.left.right)); } if (root.right != null) { liss_incl += (liss(root.right.left) + liss(root.right.right)); } // Maximum of two sizes is LISS, // store it for future uses. return root.liss = Math.Max(liss_excl, liss_incl); } // Driver code public static void Main(String[] args) { // Let us construct the tree given // in the above diagram node root = new node(20); root.left = new node(8); root.left.left = new node(4); root.left.right = new node(12); root.left.right.left = new node(10); root.left.right.right = new node(14); root.right = new node(22); root.right.right = new node(25); Console.WriteLine("Size of the Largest Independent Set is " + liss(root)); }} /* This code is contributed by PrinciRaj1992 */
<script> // JavaScript program for calculating LISS // using dynamic programming /* A binary tree node has data, pointer to left child and a pointer to right child */ class node { constructor(data) { this.data = data; this.liss = 0; this.left = null; this.right = null; } } // A memoization function returns size // of the largest independent set in // a given binary tree function liss(root) { if (root == null) return 0; if (root.liss != 0) return root.liss; if (root.left == null && root.right == null) return (root.liss = 1); // Calculate size excluding the // current node var liss_excl = liss(root.left) + liss(root.right); // Calculate size including the // current node var liss_incl = 1; if (root.left != null) { liss_incl += liss(root.left.left) + liss(root.left.right); } if (root.right != null) { liss_incl += liss(root.right.left) + liss(root.right.right); } // Maximum of two sizes is LISS, // store it for future uses. return (root.liss = Math.max(liss_excl, liss_incl)); } // Driver code // Let us construct the tree given // in the above diagram var root = new node(20); root.left = new node(8); root.left.left = new node(4); root.left.right = new node(12); root.left.right.left = new node(10); root.left.right.right = new node(14); root.right = new node(22); root.right.right = new node(25); document.write( "Size of the Largest Independent Set is " + liss(root) ); </script>
Output:
Size of the Largest Independent Set is 5
Time Complexity: O(n) where n is the number of nodes in given Binary tree. Following extensions to above solution can be tried as an exercise. 1) Extend the above solution for n-ary tree. 2) The above solution modifies the given tree structure by adding an additional field ‘liss’ to tree nodes. Extend the solution so that it doesn’t modify the tree structure.3) The above solution only returns size of LIS, it doesn’t print elements of LIS. Extend the solution to print all nodes that are part of LIS.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
rathbhupendra
29AjayKumar
princi singh
princiraj1992
andrew1234
nishthagoel712
anikakapoor
avanitrachhadiya2155
rdtank
surindertarika1234
Dynamic Programming
Tree
Dynamic Programming
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Find if there is a path between two vertices in an undirected graph
Longest Palindromic Substring | Set 1
Floyd Warshall Algorithm | DP-16
Coin Change | DP-7
Bellman–Ford Algorithm | DP-23
Tree Traversals (Inorder, Preorder and Postorder)
Binary Tree | Set 1 (Introduction)
Level Order Binary Tree Traversal
AVL Tree | Set 1 (Insertion)
Introduction to Data Structures
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n19 Jul, 2021"
},
{
"code": null,
"e": 235,
"s": 54,
"text": "Given a Binary Tree, find size of the Largest Independent Set(LIS) in it. A subset of all tree nodes is an independent set if there is no edge between any two nodes of the subset. "
},
{
"code": null,
"e": 367,
"s": 235,
"text": "For example, consider the following binary tree. The largest independent set(LIS) is {10, 40, 60, 70, 80} and size of the LIS is 5."
},
{
"code": null,
"e": 834,
"s": 367,
"text": "A Dynamic Programming solution solves a given problem using solutions of subproblems in bottom up manner. Can the given problem be solved using solutions to subproblems? If yes, then what are the subproblems? Can we find largest independent set size (LISS) for a node X if we know LISS for all descendants of X? If a node is considered as part of LIS, then its children cannot be part of LIS, but its grandchildren can be. Following is optimal substructure property."
},
{
"code": null,
"e": 937,
"s": 834,
"text": "1) Optimal Substructure: Let LISS(X) indicates size of largest independent set of a tree with root X. "
},
{
"code": null,
"e": 1063,
"s": 937,
"text": " LISS(X) = MAX { (1 + sum of LISS for all grandchildren of X),\n (sum of LISS for all children of X) }"
},
{
"code": null,
"e": 1328,
"s": 1063,
"text": "The idea is simple, there are two possibilities for every node X, either X is a member of the set or not a member. If X is a member, then the value of LISS(X) is 1 plus LISS of all grandchildren. If X is not a member, then the value is sum of LISS of all children."
},
{
"code": null,
"e": 1455,
"s": 1328,
"text": "2) Overlapping Subproblems Following is recursive implementation that simply follows the recursive structure mentioned above. "
},
{
"code": null,
"e": 1459,
"s": 1455,
"text": "C++"
},
{
"code": null,
"e": 1461,
"s": 1459,
"text": "C"
},
{
"code": null,
"e": 1466,
"s": 1461,
"text": "Java"
},
{
"code": null,
"e": 1474,
"s": 1466,
"text": "Python3"
},
{
"code": null,
"e": 1477,
"s": 1474,
"text": "C#"
},
{
"code": null,
"e": 1488,
"s": 1477,
"text": "Javascript"
},
{
"code": "// A naive recursive implementation of// Largest Independent Set problem#include <bits/stdc++.h>using namespace std; // A utility function to find// max of two integersint max(int x, int y){ return (x > y) ? x : y;} /* A binary tree node has data,pointer to left child and apointer to right child */class node{ public: int data; node *left, *right;}; // The function returns size of the// largest independent set in a given// binary treeint LISS(node *root){ if (root == NULL) return 0; // Calculate size excluding the current node int size_excl = LISS(root->left) + LISS(root->right); // Calculate size including the current node int size_incl = 1; if (root->left) size_incl += LISS(root->left->left) + LISS(root->left->right); if (root->right) size_incl += LISS(root->right->left) + LISS(root->right->right); // Return the maximum of two sizes return max(size_incl, size_excl);} // A utility function to create a nodenode* newNode( int data ){ node* temp = new node(); temp->data = data; temp->left = temp->right = NULL; return temp;} // Driver Codeint main(){ // Let us construct the tree // given in the above diagram node *root = newNode(20); root->left = newNode(8); root->left->left = newNode(4); root->left->right = newNode(12); root->left->right->left = newNode(10); root->left->right->right = newNode(14); root->right = newNode(22); root->right->right = newNode(25); cout << \"Size of the Largest\" << \" Independent Set is \" << LISS(root); return 0;} // This is code is contributed// by rathbhupendra",
"e": 3181,
"s": 1488,
"text": null
},
{
"code": "// A naive recursive implementation of Largest Independent Set problem#include <stdio.h>#include <stdlib.h> // A utility function to find max of two integersint max(int x, int y) { return (x > y)? x: y; } /* A binary tree node has data, pointer to left child and a pointer to right child */struct node{ int data; struct node *left, *right;}; // The function returns size of the largest independent set in a given// binary treeint LISS(struct node *root){ if (root == NULL) return 0; // Calculate size excluding the current node int size_excl = LISS(root->left) + LISS(root->right); // Calculate size including the current node int size_incl = 1; if (root->left) size_incl += LISS(root->left->left) + LISS(root->left->right); if (root->right) size_incl += LISS(root->right->left) + LISS(root->right->right); // Return the maximum of two sizes return max(size_incl, size_excl);} // A utility function to create a nodestruct node* newNode( int data ){ struct node* temp = (struct node *) malloc( sizeof(struct node) ); temp->data = data; temp->left = temp->right = NULL; return temp;} // Driver program to test above functionsint main(){ // Let us construct the tree given in the above diagram struct node *root = newNode(20); root->left = newNode(8); root->left->left = newNode(4); root->left->right = newNode(12); root->left->right->left = newNode(10); root->left->right->right = newNode(14); root->right = newNode(22); root->right->right = newNode(25); printf (\"Size of the Largest Independent Set is %d \", LISS(root)); return 0;}",
"e": 4880,
"s": 3181,
"text": null
},
{
"code": "// A naive recursive implementation of// Largest Independent Set problemclass GFG { // A utility function to find// max of two integersstatic int max(int x, int y){ return (x > y) ? x : y;} /* A binary tree node has data,pointer to left child and apointer to right child */static class Node{ int data; Node left, right;}; // The function returns size of the// largest independent set in a given// binary treestatic int LISS(Node root){ if (root == null) return 0; // Calculate size excluding the current node int size_excl = LISS(root.left) + LISS(root.right); // Calculate size including the current node int size_incl = 1; if (root.left!=null) size_incl += LISS(root.left.left) + LISS(root.left.right); if (root.right!=null) size_incl += LISS(root.right.left) + LISS(root.right.right); // Return the maximum of two sizes return max(size_incl, size_excl);} // A utility function to create a nodestatic Node newNode( int data ){ Node temp = new Node(); temp.data = data; temp.left = temp.right = null; return temp;} // Driver Codepublic static void main(String args[]) { // Let us construct the tree // given in the above diagram Node root = newNode(20); root.left = newNode(8); root.left.left = newNode(4); root.left.right = newNode(12); root.left.right.left = newNode(10); root.left.right.right = newNode(14); root.right = newNode(22); root.right.right = newNode(25); System.out.println(\"Size of the Largest\" + \" Independent Set is \" + LISS(root)); }} // This code has been contributed by 29AjayKumar",
"e": 6559,
"s": 4880,
"text": null
},
{
"code": "# A naive recursive implementation of# Largest Independent Set problem # A utility function to find# max of two integersdef max(x, y): if(x > y): return x else: return y # A binary tree node has data,#pointer to left child and a#pointer to right childclass node : def __init__(self): self.data = 0 self.left = self.right = None # The function returns size of the# largest independent set in a given# binary treedef LISS(root): if (root == None) : return 0 # Calculate size excluding the current node size_excl = LISS(root.left) + LISS(root.right) # Calculate size including the current node size_incl = 1 if (root.left != None): size_incl += LISS(root.left.left) + \\ LISS(root.left.right) if (root.right != None): size_incl += LISS(root.right.left) + \\ LISS(root.right.right) # Return the maximum of two sizes return max(size_incl, size_excl) # A utility function to create a nodedef newNode( data ) : temp = node() temp.data = data temp.left = temp.right = None return temp # Driver Code # Let us construct the tree# given in the above diagramroot = newNode(20)root.left = newNode(8)root.left.left = newNode(4)root.left.right = newNode(12)root.left.right.left = newNode(10)root.left.right.right = newNode(14)root.right = newNode(22)root.right.right = newNode(25) print( \"Size of the Largest\" , \" Independent Set is \" , LISS(root) ) # This code is contributed by Arnab Kundu",
"e": 8088,
"s": 6559,
"text": null
},
{
"code": "// C# program for calculating LISS// using dynamic programmingusing System; class LisTree{ /* A binary tree node has data, pointer to left child and a pointer to right child */ public class node { public int data, liss; public node left, right; public node(int data) { this.data = data; this.liss = 0; } } // A memoization function returns size // of the largest independent set in // a given binary tree static int liss(node root) { if (root == null) return 0; if (root.liss != 0) return root.liss; if (root.left == null && root.right == null) return root.liss = 1; // Calculate size excluding the // current node int liss_excl = liss(root.left) + liss(root.right); // Calculate size including the // current node int liss_incl = 1; if (root.left != null) { liss_incl += (liss(root.left.left) + liss(root.left.right)); } if (root.right != null) { liss_incl += (liss(root.right.left) + liss(root.right.right)); } // Maximum of two sizes is LISS, // store it for future uses. return root.liss = Math.Max(liss_excl, liss_incl); } // Driver code public static void Main(String[] args) { // Let us construct the tree given // in the above diagram node root = new node(20); root.left = new node(8); root.left.left = new node(4); root.left.right = new node(12); root.left.right.left = new node(10); root.left.right.right = new node(14); root.right = new node(22); root.right.right = new node(25); Console.WriteLine(\"Size of the Largest Independent Set is \" + liss(root)); }} // This code is contributed by Princi Singh",
"e": 10049,
"s": 8088,
"text": null
},
{
"code": "<script> // A naive recursive implementation of// Largest Independent Set problem // A utility function to find// max of two integersfunction max(x, y){ return(x > y) ? x : y;} // A binary tree node has data,// pointer to left child and a// pointer to right childclass Node{ constructor(data) { this.data = data; this.left = this.right = null; }} // The function returns size of the// largest independent set in a given// binary treefunction LISS(root){ if (root == null) return 0; // Calculate size excluding the current node let size_excl = LISS(root.left) + LISS(root.right); // Calculate size including the current node let size_incl = 1; if (root.left != null) size_incl += LISS(root.left.left) + LISS(root.left.right); if (root.right != null) size_incl += LISS(root.right.left) + LISS(root.right.right); // Return the maximum of two sizes return max(size_incl, size_excl);} // Driver Code // Let us construct the tree// given in the above diagramlet root = new Node(20);root.left = new Node(8);root.left.left = new Node(4);root.left.right = new Node(12);root.left.right.left = new Node(10);root.left.right.right = new Node(14);root.right = new Node(22);root.right.right = new Node(25); document.write(\"Size of the Largest\" + \" Independent Set is \" + LISS(root)); // This code is contributed by avanitrachhadiya2155 </script>",
"e": 11543,
"s": 10049,
"text": null
},
{
"code": null,
"e": 11552,
"s": 11543,
"text": "Output: "
},
{
"code": null,
"e": 11593,
"s": 11552,
"text": "Size of the Largest Independent Set is 5"
},
{
"code": null,
"e": 11881,
"s": 11593,
"text": "Time complexity of the above naive recursive approach is exponential. It should be noted that the above function computes the same subproblems again and again. For example, LISS of node with value 50 is evaluated for node with values 10 and 20 as 50 is grandchild of 10 and child of 20. "
},
{
"code": null,
"e": 12248,
"s": 11881,
"text": "Since same subproblems are called again, this problem has Overlapping Subproblems property. So LISS problem has both properties (see this and this) of a dynamic programming problem. Like other typical Dynamic Programming(DP) problems, recomputations of same subproblems can be avoided by storing the solutions to subproblems and solving problems in bottom up manner."
},
{
"code": null,
"e": 12540,
"s": 12248,
"text": "Following are implementation of Dynamic Programming based solution. In the following solution, an additional field ‘liss’ is added to tree nodes. The initial value of ‘liss’ is set as 0 for all nodes. The recursive function LISS() calculates ‘liss’ for a node only if it is not already set. "
},
{
"code": null,
"e": 12544,
"s": 12540,
"text": "C++"
},
{
"code": null,
"e": 12546,
"s": 12544,
"text": "C"
},
{
"code": null,
"e": 12551,
"s": 12546,
"text": "Java"
},
{
"code": null,
"e": 12559,
"s": 12551,
"text": "Python3"
},
{
"code": null,
"e": 12562,
"s": 12559,
"text": "C#"
},
{
"code": null,
"e": 12573,
"s": 12562,
"text": "Javascript"
},
{
"code": "/* Dynamic programming based programfor Largest Independent Set problem */#include <bits/stdc++.h>using namespace std; // A utility function to find max of two integersint max(int x, int y) { return (x > y)? x: y; } /* A binary tree node has data, pointerto left child and a pointer toright child */class node{ public: int data; int liss; node *left, *right;}; // A memoization function returns size// of the largest independent set in// a given binary treeint LISS(node *root){ if (root == NULL) return 0; if (root->liss) return root->liss; if (root->left == NULL && root->right == NULL) return (root->liss = 1); // Calculate size excluding the current node int liss_excl = LISS(root->left) + LISS(root->right); // Calculate size including the current node int liss_incl = 1; if (root->left) liss_incl += LISS(root->left->left) + LISS(root->left->right); if (root->right) liss_incl += LISS(root->right->left) + LISS(root->right->right); // Maximum of two sizes is LISS, store it for future uses. root->liss = max(liss_incl, liss_excl); return root->liss;} // A utility function to create a nodenode* newNode(int data){ node* temp = new node(); temp->data = data; temp->left = temp->right = NULL; temp->liss = 0; return temp;} // Driver codeint main(){ // Let us construct the tree // given in the above diagram node *root = newNode(20); root->left = newNode(8); root->left->left = newNode(4); root->left->right = newNode(12); root->left->right->left = newNode(10); root->left->right->right = newNode(14); root->right = newNode(22); root->right->right = newNode(25); cout << \"Size of the Largest Independent Set is \" << LISS(root); return 0;} // This code is contributed by rathbhupendra",
"e": 14435,
"s": 12573,
"text": null
},
{
"code": "/* Dynamic programming based program for Largest Independent Set problem */#include <stdio.h>#include <stdlib.h> // A utility function to find max of two integersint max(int x, int y) { return (x > y)? x: y; } /* A binary tree node has data, pointer to left child and a pointer to right child */struct node{ int data; int liss; struct node *left, *right;}; // A memoization function returns size of the largest independent set in// a given binary treeint LISS(struct node *root){ if (root == NULL) return 0; if (root->liss) return root->liss; if (root->left == NULL && root->right == NULL) return (root->liss = 1); // Calculate size excluding the current node int liss_excl = LISS(root->left) + LISS(root->right); // Calculate size including the current node int liss_incl = 1; if (root->left) liss_incl += LISS(root->left->left) + LISS(root->left->right); if (root->right) liss_incl += LISS(root->right->left) + LISS(root->right->right); // Maximum of two sizes is LISS, store it for future uses. root->liss = max(liss_incl, liss_excl); return root->liss;} // A utility function to create a nodestruct node* newNode(int data){ struct node* temp = (struct node *) malloc( sizeof(struct node) ); temp->data = data; temp->left = temp->right = NULL; temp->liss = 0; return temp;} // Driver program to test above functionsint main(){ // Let us construct the tree given in the above diagram struct node *root = newNode(20); root->left = newNode(8); root->left->left = newNode(4); root->left->right = newNode(12); root->left->right->left = newNode(10); root->left->right->right = newNode(14); root->right = newNode(22); root->right->right = newNode(25); printf (\"Size of the Largest Independent Set is %d \", LISS(root)); return 0;}",
"e": 16364,
"s": 14435,
"text": null
},
{
"code": "// Java program for calculating LISS// using dynamic programming public class LisTree{ /* A binary tree node has data, pointer to left child and a pointer to right child */ static class node { int data, liss; node left, right; public node(int data) { this.data = data; this.liss = 0; } } // A memoization function returns size // of the largest independent set in // a given binary tree static int liss(node root) { if (root == null) return 0; if (root.liss != 0) return root.liss; if (root.left == null && root.right == null) return root.liss = 1; // Calculate size excluding the // current node int liss_excl = liss(root.left) + liss(root.right); // Calculate size including the // current node int liss_incl = 1; if (root.left != null) { liss_incl += (liss(root.left.left) + liss(root.left.right)); } if (root.right != null) { liss_incl += (liss(root.right.left) + liss(root.right.right)); } // Maximum of two sizes is LISS, // store it for future uses. return root.liss = Math.max(liss_excl, liss_incl); } public static void main(String[] args) { // Let us construct the tree given // in the above diagram node root = new node(20); root.left = new node(8); root.left.left = new node(4); root.left.right = new node(12); root.left.right.left = new node(10); root.left.right.right = new node(14); root.right = new node(22); root.right.right = new node(25); System.out.println(\"Size of the Largest Independent Set is \" + liss(root)); }} // This code is contributed by Rishabh Mahrsee",
"e": 18253,
"s": 16364,
"text": null
},
{
"code": "# Python3 program for calculating LISS# using dynamic programming # A binary tree node has data,# pointer to left child and a# pointer to right childclass node: def __init__(self, data): self.data = data self.left = self.right = None self.liss = 0 # A memoization function returns size# of the largest independent set in# a given binary treedef liss(root): if root == None: return 0 if root.liss != 0: return root.liss if (root.left == None and root.right == None): root.liss = 1 return root.liss # Calculate size excluding the # current node liss_excl = (liss(root.left) + liss(root.right)) # Calculate size including the # current node liss_incl = 1 if root.left != None: liss_incl += (liss(root.left.left) + liss(root.left.right)) if root.right != None: liss_incl += (liss(root.right.left) + liss(root.right.right)) # Maximum of two sizes is LISS, # store it for future uses. root.liss = max(liss_excl, liss_incl) return root.liss # Driver Code # Let us construct the tree given# in the above diagramroot = node(20)root.left = node(8)root.left.left = node(4)root.left.right = node(12)root.left.right.left = node(10)root.left.right.right = node(14)root.right = node(22)root.right.right = node(25) print(\"Size of the Largest Independent \"\\ \"Set is \", liss(root)) # This code is contributed by nishthagoel712",
"e": 19796,
"s": 18253,
"text": null
},
{
"code": "// C# program for calculating LISS// using dynamic programmingusing System; public class LisTree{ /* A binary tree node has data, pointer to left child and a pointer to right child */ public class node { public int data, liss; public node left, right; public node(int data) { this.data = data; this.liss = 0; } } // A memoization function returns size // of the largest independent set in // a given binary tree static int liss(node root) { if (root == null) return 0; if (root.liss != 0) return root.liss; if (root.left == null && root.right == null) return root.liss = 1; // Calculate size excluding the // current node int liss_excl = liss(root.left) + liss(root.right); // Calculate size including the // current node int liss_incl = 1; if (root.left != null) { liss_incl += (liss(root.left.left) + liss(root.left.right)); } if (root.right != null) { liss_incl += (liss(root.right.left) + liss(root.right.right)); } // Maximum of two sizes is LISS, // store it for future uses. return root.liss = Math.Max(liss_excl, liss_incl); } // Driver code public static void Main(String[] args) { // Let us construct the tree given // in the above diagram node root = new node(20); root.left = new node(8); root.left.left = new node(4); root.left.right = new node(12); root.left.right.left = new node(10); root.left.right.right = new node(14); root.right = new node(22); root.right.right = new node(25); Console.WriteLine(\"Size of the Largest Independent Set is \" + liss(root)); }} /* This code is contributed by PrinciRaj1992 */",
"e": 21726,
"s": 19796,
"text": null
},
{
"code": "<script> // JavaScript program for calculating LISS // using dynamic programming /* A binary tree node has data, pointer to left child and a pointer to right child */ class node { constructor(data) { this.data = data; this.liss = 0; this.left = null; this.right = null; } } // A memoization function returns size // of the largest independent set in // a given binary tree function liss(root) { if (root == null) return 0; if (root.liss != 0) return root.liss; if (root.left == null && root.right == null) return (root.liss = 1); // Calculate size excluding the // current node var liss_excl = liss(root.left) + liss(root.right); // Calculate size including the // current node var liss_incl = 1; if (root.left != null) { liss_incl += liss(root.left.left) + liss(root.left.right); } if (root.right != null) { liss_incl += liss(root.right.left) + liss(root.right.right); } // Maximum of two sizes is LISS, // store it for future uses. return (root.liss = Math.max(liss_excl, liss_incl)); } // Driver code // Let us construct the tree given // in the above diagram var root = new node(20); root.left = new node(8); root.left.left = new node(4); root.left.right = new node(12); root.left.right.left = new node(10); root.left.right.right = new node(14); root.right = new node(22); root.right.right = new node(25); document.write( \"Size of the Largest Independent Set is \" + liss(root) ); </script>",
"e": 23454,
"s": 21726,
"text": null
},
{
"code": null,
"e": 23463,
"s": 23454,
"text": "Output: "
},
{
"code": null,
"e": 23504,
"s": 23463,
"text": "Size of the Largest Independent Set is 5"
},
{
"code": null,
"e": 24133,
"s": 23504,
"text": "Time Complexity: O(n) where n is the number of nodes in given Binary tree. Following extensions to above solution can be tried as an exercise. 1) Extend the above solution for n-ary tree. 2) The above solution modifies the given tree structure by adding an additional field ‘liss’ to tree nodes. Extend the solution so that it doesn’t modify the tree structure.3) The above solution only returns size of LIS, it doesn’t print elements of LIS. Extend the solution to print all nodes that are part of LIS.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 24147,
"s": 24133,
"text": "rathbhupendra"
},
{
"code": null,
"e": 24159,
"s": 24147,
"text": "29AjayKumar"
},
{
"code": null,
"e": 24172,
"s": 24159,
"text": "princi singh"
},
{
"code": null,
"e": 24186,
"s": 24172,
"text": "princiraj1992"
},
{
"code": null,
"e": 24197,
"s": 24186,
"text": "andrew1234"
},
{
"code": null,
"e": 24212,
"s": 24197,
"text": "nishthagoel712"
},
{
"code": null,
"e": 24224,
"s": 24212,
"text": "anikakapoor"
},
{
"code": null,
"e": 24245,
"s": 24224,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 24252,
"s": 24245,
"text": "rdtank"
},
{
"code": null,
"e": 24271,
"s": 24252,
"text": "surindertarika1234"
},
{
"code": null,
"e": 24291,
"s": 24271,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 24296,
"s": 24291,
"text": "Tree"
},
{
"code": null,
"e": 24316,
"s": 24296,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 24321,
"s": 24316,
"text": "Tree"
},
{
"code": null,
"e": 24419,
"s": 24321,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 24487,
"s": 24419,
"text": "Find if there is a path between two vertices in an undirected graph"
},
{
"code": null,
"e": 24525,
"s": 24487,
"text": "Longest Palindromic Substring | Set 1"
},
{
"code": null,
"e": 24558,
"s": 24525,
"text": "Floyd Warshall Algorithm | DP-16"
},
{
"code": null,
"e": 24577,
"s": 24558,
"text": "Coin Change | DP-7"
},
{
"code": null,
"e": 24608,
"s": 24577,
"text": "Bellman–Ford Algorithm | DP-23"
},
{
"code": null,
"e": 24658,
"s": 24608,
"text": "Tree Traversals (Inorder, Preorder and Postorder)"
},
{
"code": null,
"e": 24693,
"s": 24658,
"text": "Binary Tree | Set 1 (Introduction)"
},
{
"code": null,
"e": 24727,
"s": 24693,
"text": "Level Order Binary Tree Traversal"
},
{
"code": null,
"e": 24756,
"s": 24727,
"text": "AVL Tree | Set 1 (Insertion)"
}
] |
Scikit Learn - Stochastic Gradient Descent
|
Here, we will learn about an optimization algorithm in Sklearn, termed as Stochastic Gradient Descent (SGD).
Stochastic Gradient Descent (SGD) is a simple yet efficient optimization algorithm used to find the values of parameters/coefficients of functions that minimize a cost function. In other words, it is used for discriminative learning of linear classifiers under convex loss functions such as SVM and Logistic regression. It has been successfully applied to large-scale datasets because the update to the coefficients is performed for each training instance, rather than at the end of instances.
Stochastic Gradient Descent (SGD) classifier basically implements a plain SGD learning routine supporting various loss functions and penalties for classification. Scikit-learn provides SGDClassifier module to implement SGD classification.
Followings table consist the parameters used by SGDClassifier module −
loss − str, default = ‘hinge’
It represents the loss function to be used while implementing. The default value is ‘hinge’ which will give us a linear SVM. The other options which can be used are −
log − This loss will give us logistic regression i.e. a probabilistic classifier.
log − This loss will give us logistic regression i.e. a probabilistic classifier.
modified_huber − a smooth loss that brings tolerance to outliers along with probability estimates.
modified_huber − a smooth loss that brings tolerance to outliers along with probability estimates.
squared_hinge − similar to ‘hinge’ loss but it is quadratically penalized.
squared_hinge − similar to ‘hinge’ loss but it is quadratically penalized.
perceptron − as the name suggests, it is a linear loss which is used by the perceptron algorithm.
perceptron − as the name suggests, it is a linear loss which is used by the perceptron algorithm.
penalty − str, ‘none’, ‘l2’, ‘l1’, ‘elasticnet’
It is the regularization term used in the model. By default, it is L2. We can use L1 or ‘elasticnet; as well but both might bring sparsity to the model, hence not achievable with L2.
alpha − float, default = 0.0001
Alpha, the constant that multiplies the regularization term, is the tuning parameter that decides how much we want to penalize the model. The default value is 0.0001.
l1_ratio − float, default = 0.15
This is called the ElasticNet mixing parameter. Its range is 0 < = l1_ratio < = 1. If l1_ratio = 1, the penalty would be L1 penalty. If l1_ratio = 0, the penalty would be an L2 penalty.
fit_intercept − Boolean, Default=True
This parameter specifies that a constant (bias or intercept) should be added to the decision function. No intercept will be used in calculation and data will be assumed already centered, if it will set to false.
tol − float or none, optional, default = 1.e-3
This parameter represents the stopping criterion for iterations. Its default value is False but if set to None, the iterations will stop when lloss > best_loss - tol for n_iter_no_changesuccessive epochs.
shuffle − Boolean, optional, default = True
This parameter represents that whether we want our training data to be shuffled after each epoch or not.
verbose − integer, default = 0
It represents the verbosity level. Its default value is 0.
epsilon − float, default = 0.1
This parameter specifies the width of the insensitive region. If loss = ‘epsilon-insensitive’, any difference, between current prediction and the correct label, less than the threshold would be ignored.
max_iter − int, optional, default = 1000
As name suggest, it represents the maximum number of passes over the epochs i.e. training data.
warm_start − bool, optional, default = false
With this parameter set to True, we can reuse the solution of the previous call to fit as initialization. If we choose default i.e. false, it will erase the previous solution.
random_state − int, RandomState instance or None, optional, default = none
This parameter represents the seed of the pseudo random number generated which is used while shuffling the data. Followings are the options.
int − In this case, random_state is the seed used by random number generator.
int − In this case, random_state is the seed used by random number generator.
RandomState instance − In this case, random_state is the random number generator.
RandomState instance − In this case, random_state is the random number generator.
None − In this case, the random number generator is the RandonState instance used by np.random.
None − In this case, the random number generator is the RandonState instance used by np.random.
n_jobs − int or none, optional, Default = None
It represents the number of CPUs to be used in OVA (One Versus All) computation, for multi-class problems. The default value is none which means 1.
learning_rate − string, optional, default = ‘optimal’
If learning rate is ‘constant’, eta = eta0;
If learning rate is ‘constant’, eta = eta0;
If learning rate is ‘optimal’, eta = 1.0/(alpha*(t+t0)), where t0 is chosen by Leon Bottou;
If learning rate is ‘optimal’, eta = 1.0/(alpha*(t+t0)), where t0 is chosen by Leon Bottou;
If learning rate = ‘invscalling’, eta = eta0/pow(t, power_t).
If learning rate = ‘invscalling’, eta = eta0/pow(t, power_t).
If learning rate = ‘adaptive’, eta = eta0.
If learning rate = ‘adaptive’, eta = eta0.
eta0 − double, default = 0.0
It represents the initial learning rate for above mentioned learning rate options i.e. ‘constant’, ‘invscalling’, or ‘adaptive’.
power_t − idouble, default =0.5
It is the exponent for ‘incscalling’ learning rate.
early_stopping − bool, default = False
This parameter represents the use of early stopping to terminate training when validation score is not improving. Its default value is false but when set to true, it automatically set aside a stratified fraction of training data as validation and stop training when validation score is not improving.
validation_fraction − float, default = 0.1
It is only used when early_stopping is true. It represents the proportion of training data to set asides as validation set for early termination of training data..
n_iter_no_change − int, default=5
It represents the number of iteration with no improvement should algorithm run before early stopping.
classs_weight − dict, {class_label: weight} or “balanced”, or None, optional
This parameter represents the weights associated with classes. If not provided, the classes are supposed to have weight 1.
warm_start − bool, optional, default = false
With this parameter set to True, we can reuse the solution of the previous call to fit as initialization. If we choose default i.e. false, it will erase the previous solution.
average − iBoolean or int, optional, default = false
It represents the number of CPUs to be used in OVA (One Versus All) computation, for multi-class problems. The default value is none which means 1.
Following table consist the attributes used by SGDClassifier module −
coef_ − array, shape (1, n_features) if n_classes==2, else (n_classes, n_features)
This attribute provides the weight assigned to the features.
intercept_ − array, shape (1,) if n_classes==2, else (n_classes,)
It represents the independent term in decision function.
n_iter_ − int
It gives the number of iterations to reach the stopping criterion.
Implementation Example
Like other classifiers, Stochastic Gradient Descent (SGD) has to be fitted with following two arrays −
An array X holding the training samples. It is of size [n_samples, n_features].
An array X holding the training samples. It is of size [n_samples, n_features].
An array Y holding the target values i.e. class labels for the training samples. It is of size [n_samples].
An array Y holding the target values i.e. class labels for the training samples. It is of size [n_samples].
Example
Following Python script uses SGDClassifier linear model −
import numpy as np
from sklearn import linear_model
X = np.array([[-1, -1], [-2, -1], [1, 1], [2, 1]])
Y = np.array([1, 1, 2, 2])
SGDClf = linear_model.SGDClassifier(max_iter = 1000, tol=1e-3,penalty = "elasticnet")
SGDClf.fit(X, Y)
Output
SGDClassifier(
alpha = 0.0001, average = False, class_weight = None,
early_stopping = False, epsilon = 0.1, eta0 = 0.0, fit_intercept = True,
l1_ratio = 0.15, learning_rate = 'optimal', loss = 'hinge', max_iter = 1000,
n_iter = None, n_iter_no_change = 5, n_jobs = None, penalty = 'elasticnet',
power_t = 0.5, random_state = None, shuffle = True, tol = 0.001,
validation_fraction = 0.1, verbose = 0, warm_start = False
)
Example
Now, once fitted, the model can predict new values as follows −
SGDClf.predict([[2.,2.]])
Output
array([2])
Example
For the above example, we can get the weight vector with the help of following python script −
SGDClf.coef_
Output
array([[19.54811198, 9.77200712]])
Example
Similarly, we can get the value of intercept with the help of following python script −
SGDClf.intercept_
Output
array([10.])
Example
We can get the signed distance to the hyperplane by using SGDClassifier.decision_function as used in the following python script −
SGDClf.decision_function([[2., 2.]])
Output
array([68.6402382])
Stochastic Gradient Descent (SGD) regressor basically implements a plain SGD learning routine supporting various loss functions and penalties to fit linear regression models. Scikit-learn provides SGDRegressor module to implement SGD regression.
Parameters used by SGDRegressor are almost same as that were used in SGDClassifier module. The difference lies in ‘loss’ parameter. For SGDRegressor modules’ loss parameter the positives values are as follows −
squared_loss − It refers to the ordinary least squares fit.
squared_loss − It refers to the ordinary least squares fit.
huber: SGDRegressor − correct the outliers by switching from squared to linear loss past a distance of epsilon. The work of ‘huber’ is to modify ‘squared_loss’ so that algorithm focus less on correcting outliers.
huber: SGDRegressor − correct the outliers by switching from squared to linear loss past a distance of epsilon. The work of ‘huber’ is to modify ‘squared_loss’ so that algorithm focus less on correcting outliers.
epsilon_insensitive − Actually, it ignores the errors less than epsilon.
epsilon_insensitive − Actually, it ignores the errors less than epsilon.
squared_epsilon_insensitive − It is same as epsilon_insensitive. The only difference is that it becomes squared loss past a tolerance of epsilon.
squared_epsilon_insensitive − It is same as epsilon_insensitive. The only difference is that it becomes squared loss past a tolerance of epsilon.
Another difference is that the parameter named ‘power_t’ has the default value of 0.25 rather than 0.5 as in SGDClassifier. Furthermore, it doesn’t have ‘class_weight’ and ‘n_jobs’ parameters.
Attributes of SGDRegressor are also same as that were of SGDClassifier module. Rather it has three extra attributes as follows −
average_coef_ − array, shape(n_features,)
average_coef_ − array, shape(n_features,)
As name suggest, it provides the average weights assigned to the features.
average_intercept_ − array, shape(1,)
average_intercept_ − array, shape(1,)
As name suggest, it provides the averaged intercept term.
t_ − int
t_ − int
It provides the number of weight updates performed during the training phase.
Note − the attributes average_coef_ and average_intercept_ will work after enabling parameter ‘average’ to True.
Implementation Example
Following Python script uses SGDRegressor linear model −
import numpy as np
from sklearn import linear_model
n_samples, n_features = 10, 5
rng = np.random.RandomState(0)
y = rng.randn(n_samples)
X = rng.randn(n_samples, n_features)
SGDReg =linear_model.SGDRegressor(
max_iter = 1000,penalty = "elasticnet",loss = 'huber',tol = 1e-3, average = True
)
SGDReg.fit(X, y)
Output
SGDRegressor(
alpha = 0.0001, average = True, early_stopping = False, epsilon = 0.1,
eta0 = 0.01, fit_intercept = True, l1_ratio = 0.15,
learning_rate = 'invscaling', loss = 'huber', max_iter = 1000,
n_iter = None, n_iter_no_change = 5, penalty = 'elasticnet', power_t = 0.25,
random_state = None, shuffle = True, tol = 0.001, validation_fraction = 0.1,
verbose = 0, warm_start = False
)
Example
Now, once fitted, we can get the weight vector with the help of following python script −
SGDReg.coef_
Output
array([-0.00423314, 0.00362922, -0.00380136, 0.00585455, 0.00396787])
Example
Similarly, we can get the value of intercept with the help of following python script −
SGReg.intercept_
Output
SGReg.intercept_
Example
We can get the number of weight updates during training phase with the help of the following python script −
SGDReg.t_
Output
61.0
Following the pros of SGD −
Stochastic Gradient Descent (SGD) is very efficient.
Stochastic Gradient Descent (SGD) is very efficient.
It is very easy to implement as there are lots of opportunities for code tuning.
It is very easy to implement as there are lots of opportunities for code tuning.
Following the cons of SGD −
Stochastic Gradient Descent (SGD) requires several hyperparameters like regularization parameters.
Stochastic Gradient Descent (SGD) requires several hyperparameters like regularization parameters.
It is sensitive to feature scaling.
It is sensitive to feature scaling.
|
[
{
"code": null,
"e": 2464,
"s": 2355,
"text": "Here, we will learn about an optimization algorithm in Sklearn, termed as Stochastic Gradient Descent (SGD)."
},
{
"code": null,
"e": 2958,
"s": 2464,
"text": "Stochastic Gradient Descent (SGD) is a simple yet efficient optimization algorithm used to find the values of parameters/coefficients of functions that minimize a cost function. In other words, it is used for discriminative learning of linear classifiers under convex loss functions such as SVM and Logistic regression. It has been successfully applied to large-scale datasets because the update to the coefficients is performed for each training instance, rather than at the end of instances."
},
{
"code": null,
"e": 3197,
"s": 2958,
"text": "Stochastic Gradient Descent (SGD) classifier basically implements a plain SGD learning routine supporting various loss functions and penalties for classification. Scikit-learn provides SGDClassifier module to implement SGD classification."
},
{
"code": null,
"e": 3268,
"s": 3197,
"text": "Followings table consist the parameters used by SGDClassifier module −"
},
{
"code": null,
"e": 3298,
"s": 3268,
"text": "loss − str, default = ‘hinge’"
},
{
"code": null,
"e": 3465,
"s": 3298,
"text": "It represents the loss function to be used while implementing. The default value is ‘hinge’ which will give us a linear SVM. The other options which can be used are −"
},
{
"code": null,
"e": 3547,
"s": 3465,
"text": "log − This loss will give us logistic regression i.e. a probabilistic classifier."
},
{
"code": null,
"e": 3629,
"s": 3547,
"text": "log − This loss will give us logistic regression i.e. a probabilistic classifier."
},
{
"code": null,
"e": 3728,
"s": 3629,
"text": "modified_huber − a smooth loss that brings tolerance to outliers along with probability estimates."
},
{
"code": null,
"e": 3827,
"s": 3728,
"text": "modified_huber − a smooth loss that brings tolerance to outliers along with probability estimates."
},
{
"code": null,
"e": 3902,
"s": 3827,
"text": "squared_hinge − similar to ‘hinge’ loss but it is quadratically penalized."
},
{
"code": null,
"e": 3977,
"s": 3902,
"text": "squared_hinge − similar to ‘hinge’ loss but it is quadratically penalized."
},
{
"code": null,
"e": 4075,
"s": 3977,
"text": "perceptron − as the name suggests, it is a linear loss which is used by the perceptron algorithm."
},
{
"code": null,
"e": 4173,
"s": 4075,
"text": "perceptron − as the name suggests, it is a linear loss which is used by the perceptron algorithm."
},
{
"code": null,
"e": 4221,
"s": 4173,
"text": "penalty − str, ‘none’, ‘l2’, ‘l1’, ‘elasticnet’"
},
{
"code": null,
"e": 4404,
"s": 4221,
"text": "It is the regularization term used in the model. By default, it is L2. We can use L1 or ‘elasticnet; as well but both might bring sparsity to the model, hence not achievable with L2."
},
{
"code": null,
"e": 4436,
"s": 4404,
"text": "alpha − float, default = 0.0001"
},
{
"code": null,
"e": 4603,
"s": 4436,
"text": "Alpha, the constant that multiplies the regularization term, is the tuning parameter that decides how much we want to penalize the model. The default value is 0.0001."
},
{
"code": null,
"e": 4636,
"s": 4603,
"text": "l1_ratio − float, default = 0.15"
},
{
"code": null,
"e": 4822,
"s": 4636,
"text": "This is called the ElasticNet mixing parameter. Its range is 0 < = l1_ratio < = 1. If l1_ratio = 1, the penalty would be L1 penalty. If l1_ratio = 0, the penalty would be an L2 penalty."
},
{
"code": null,
"e": 4860,
"s": 4822,
"text": "fit_intercept − Boolean, Default=True"
},
{
"code": null,
"e": 5072,
"s": 4860,
"text": "This parameter specifies that a constant (bias or intercept) should be added to the decision function. No intercept will be used in calculation and data will be assumed already centered, if it will set to false."
},
{
"code": null,
"e": 5119,
"s": 5072,
"text": "tol − float or none, optional, default = 1.e-3"
},
{
"code": null,
"e": 5324,
"s": 5119,
"text": "This parameter represents the stopping criterion for iterations. Its default value is False but if set to None, the iterations will stop when lloss > best_loss - tol for n_iter_no_changesuccessive epochs."
},
{
"code": null,
"e": 5368,
"s": 5324,
"text": "shuffle − Boolean, optional, default = True"
},
{
"code": null,
"e": 5473,
"s": 5368,
"text": "This parameter represents that whether we want our training data to be shuffled after each epoch or not."
},
{
"code": null,
"e": 5504,
"s": 5473,
"text": "verbose − integer, default = 0"
},
{
"code": null,
"e": 5563,
"s": 5504,
"text": "It represents the verbosity level. Its default value is 0."
},
{
"code": null,
"e": 5594,
"s": 5563,
"text": "epsilon − float, default = 0.1"
},
{
"code": null,
"e": 5797,
"s": 5594,
"text": "This parameter specifies the width of the insensitive region. If loss = ‘epsilon-insensitive’, any difference, between current prediction and the correct label, less than the threshold would be ignored."
},
{
"code": null,
"e": 5838,
"s": 5797,
"text": "max_iter − int, optional, default = 1000"
},
{
"code": null,
"e": 5934,
"s": 5838,
"text": "As name suggest, it represents the maximum number of passes over the epochs i.e. training data."
},
{
"code": null,
"e": 5979,
"s": 5934,
"text": "warm_start − bool, optional, default = false"
},
{
"code": null,
"e": 6155,
"s": 5979,
"text": "With this parameter set to True, we can reuse the solution of the previous call to fit as initialization. If we choose default i.e. false, it will erase the previous solution."
},
{
"code": null,
"e": 6230,
"s": 6155,
"text": "random_state − int, RandomState instance or None, optional, default = none"
},
{
"code": null,
"e": 6371,
"s": 6230,
"text": "This parameter represents the seed of the pseudo random number generated which is used while shuffling the data. Followings are the options."
},
{
"code": null,
"e": 6449,
"s": 6371,
"text": "int − In this case, random_state is the seed used by random number generator."
},
{
"code": null,
"e": 6527,
"s": 6449,
"text": "int − In this case, random_state is the seed used by random number generator."
},
{
"code": null,
"e": 6609,
"s": 6527,
"text": "RandomState instance − In this case, random_state is the random number generator."
},
{
"code": null,
"e": 6691,
"s": 6609,
"text": "RandomState instance − In this case, random_state is the random number generator."
},
{
"code": null,
"e": 6787,
"s": 6691,
"text": "None − In this case, the random number generator is the RandonState instance used by np.random."
},
{
"code": null,
"e": 6883,
"s": 6787,
"text": "None − In this case, the random number generator is the RandonState instance used by np.random."
},
{
"code": null,
"e": 6930,
"s": 6883,
"text": "n_jobs − int or none, optional, Default = None"
},
{
"code": null,
"e": 7078,
"s": 6930,
"text": "It represents the number of CPUs to be used in OVA (One Versus All) computation, for multi-class problems. The default value is none which means 1."
},
{
"code": null,
"e": 7132,
"s": 7078,
"text": "learning_rate − string, optional, default = ‘optimal’"
},
{
"code": null,
"e": 7176,
"s": 7132,
"text": "If learning rate is ‘constant’, eta = eta0;"
},
{
"code": null,
"e": 7220,
"s": 7176,
"text": "If learning rate is ‘constant’, eta = eta0;"
},
{
"code": null,
"e": 7312,
"s": 7220,
"text": "If learning rate is ‘optimal’, eta = 1.0/(alpha*(t+t0)), where t0 is chosen by Leon Bottou;"
},
{
"code": null,
"e": 7404,
"s": 7312,
"text": "If learning rate is ‘optimal’, eta = 1.0/(alpha*(t+t0)), where t0 is chosen by Leon Bottou;"
},
{
"code": null,
"e": 7466,
"s": 7404,
"text": "If learning rate = ‘invscalling’, eta = eta0/pow(t, power_t)."
},
{
"code": null,
"e": 7528,
"s": 7466,
"text": "If learning rate = ‘invscalling’, eta = eta0/pow(t, power_t)."
},
{
"code": null,
"e": 7571,
"s": 7528,
"text": "If learning rate = ‘adaptive’, eta = eta0."
},
{
"code": null,
"e": 7614,
"s": 7571,
"text": "If learning rate = ‘adaptive’, eta = eta0."
},
{
"code": null,
"e": 7643,
"s": 7614,
"text": "eta0 − double, default = 0.0"
},
{
"code": null,
"e": 7772,
"s": 7643,
"text": "It represents the initial learning rate for above mentioned learning rate options i.e. ‘constant’, ‘invscalling’, or ‘adaptive’."
},
{
"code": null,
"e": 7804,
"s": 7772,
"text": "power_t − idouble, default =0.5"
},
{
"code": null,
"e": 7856,
"s": 7804,
"text": "It is the exponent for ‘incscalling’ learning rate."
},
{
"code": null,
"e": 7895,
"s": 7856,
"text": "early_stopping − bool, default = False"
},
{
"code": null,
"e": 8196,
"s": 7895,
"text": "This parameter represents the use of early stopping to terminate training when validation score is not improving. Its default value is false but when set to true, it automatically set aside a stratified fraction of training data as validation and stop training when validation score is not improving."
},
{
"code": null,
"e": 8239,
"s": 8196,
"text": "validation_fraction − float, default = 0.1"
},
{
"code": null,
"e": 8403,
"s": 8239,
"text": "It is only used when early_stopping is true. It represents the proportion of training data to set asides as validation set for early termination of training data.."
},
{
"code": null,
"e": 8437,
"s": 8403,
"text": "n_iter_no_change − int, default=5"
},
{
"code": null,
"e": 8539,
"s": 8437,
"text": "It represents the number of iteration with no improvement should algorithm run before early stopping."
},
{
"code": null,
"e": 8616,
"s": 8539,
"text": "classs_weight − dict, {class_label: weight} or “balanced”, or None, optional"
},
{
"code": null,
"e": 8739,
"s": 8616,
"text": "This parameter represents the weights associated with classes. If not provided, the classes are supposed to have weight 1."
},
{
"code": null,
"e": 8784,
"s": 8739,
"text": "warm_start − bool, optional, default = false"
},
{
"code": null,
"e": 8960,
"s": 8784,
"text": "With this parameter set to True, we can reuse the solution of the previous call to fit as initialization. If we choose default i.e. false, it will erase the previous solution."
},
{
"code": null,
"e": 9013,
"s": 8960,
"text": "average − iBoolean or int, optional, default = false"
},
{
"code": null,
"e": 9161,
"s": 9013,
"text": "It represents the number of CPUs to be used in OVA (One Versus All) computation, for multi-class problems. The default value is none which means 1."
},
{
"code": null,
"e": 9231,
"s": 9161,
"text": "Following table consist the attributes used by SGDClassifier module −"
},
{
"code": null,
"e": 9314,
"s": 9231,
"text": "coef_ − array, shape (1, n_features) if n_classes==2, else (n_classes, n_features)"
},
{
"code": null,
"e": 9375,
"s": 9314,
"text": "This attribute provides the weight assigned to the features."
},
{
"code": null,
"e": 9441,
"s": 9375,
"text": "intercept_ − array, shape (1,) if n_classes==2, else (n_classes,)"
},
{
"code": null,
"e": 9498,
"s": 9441,
"text": "It represents the independent term in decision function."
},
{
"code": null,
"e": 9512,
"s": 9498,
"text": "n_iter_ − int"
},
{
"code": null,
"e": 9579,
"s": 9512,
"text": "It gives the number of iterations to reach the stopping criterion."
},
{
"code": null,
"e": 9602,
"s": 9579,
"text": "Implementation Example"
},
{
"code": null,
"e": 9705,
"s": 9602,
"text": "Like other classifiers, Stochastic Gradient Descent (SGD) has to be fitted with following two arrays −"
},
{
"code": null,
"e": 9785,
"s": 9705,
"text": "An array X holding the training samples. It is of size [n_samples, n_features]."
},
{
"code": null,
"e": 9865,
"s": 9785,
"text": "An array X holding the training samples. It is of size [n_samples, n_features]."
},
{
"code": null,
"e": 9973,
"s": 9865,
"text": "An array Y holding the target values i.e. class labels for the training samples. It is of size [n_samples]."
},
{
"code": null,
"e": 10081,
"s": 9973,
"text": "An array Y holding the target values i.e. class labels for the training samples. It is of size [n_samples]."
},
{
"code": null,
"e": 10089,
"s": 10081,
"text": "Example"
},
{
"code": null,
"e": 10147,
"s": 10089,
"text": "Following Python script uses SGDClassifier linear model −"
},
{
"code": null,
"e": 10380,
"s": 10147,
"text": "import numpy as np\nfrom sklearn import linear_model\nX = np.array([[-1, -1], [-2, -1], [1, 1], [2, 1]])\nY = np.array([1, 1, 2, 2])\nSGDClf = linear_model.SGDClassifier(max_iter = 1000, tol=1e-3,penalty = \"elasticnet\")\nSGDClf.fit(X, Y)"
},
{
"code": null,
"e": 10387,
"s": 10380,
"text": "Output"
},
{
"code": null,
"e": 10827,
"s": 10387,
"text": "SGDClassifier(\n alpha = 0.0001, average = False, class_weight = None,\n early_stopping = False, epsilon = 0.1, eta0 = 0.0, fit_intercept = True,\n l1_ratio = 0.15, learning_rate = 'optimal', loss = 'hinge', max_iter = 1000,\n n_iter = None, n_iter_no_change = 5, n_jobs = None, penalty = 'elasticnet',\n power_t = 0.5, random_state = None, shuffle = True, tol = 0.001,\n validation_fraction = 0.1, verbose = 0, warm_start = False\n)\n"
},
{
"code": null,
"e": 10835,
"s": 10827,
"text": "Example"
},
{
"code": null,
"e": 10899,
"s": 10835,
"text": "Now, once fitted, the model can predict new values as follows −"
},
{
"code": null,
"e": 10925,
"s": 10899,
"text": "SGDClf.predict([[2.,2.]])"
},
{
"code": null,
"e": 10932,
"s": 10925,
"text": "Output"
},
{
"code": null,
"e": 10944,
"s": 10932,
"text": "array([2])\n"
},
{
"code": null,
"e": 10952,
"s": 10944,
"text": "Example"
},
{
"code": null,
"e": 11047,
"s": 10952,
"text": "For the above example, we can get the weight vector with the help of following python script −"
},
{
"code": null,
"e": 11060,
"s": 11047,
"text": "SGDClf.coef_"
},
{
"code": null,
"e": 11067,
"s": 11060,
"text": "Output"
},
{
"code": null,
"e": 11103,
"s": 11067,
"text": "array([[19.54811198, 9.77200712]])\n"
},
{
"code": null,
"e": 11111,
"s": 11103,
"text": "Example"
},
{
"code": null,
"e": 11199,
"s": 11111,
"text": "Similarly, we can get the value of intercept with the help of following python script −"
},
{
"code": null,
"e": 11217,
"s": 11199,
"text": "SGDClf.intercept_"
},
{
"code": null,
"e": 11224,
"s": 11217,
"text": "Output"
},
{
"code": null,
"e": 11238,
"s": 11224,
"text": "array([10.])\n"
},
{
"code": null,
"e": 11246,
"s": 11238,
"text": "Example"
},
{
"code": null,
"e": 11377,
"s": 11246,
"text": "We can get the signed distance to the hyperplane by using SGDClassifier.decision_function as used in the following python script −"
},
{
"code": null,
"e": 11414,
"s": 11377,
"text": "SGDClf.decision_function([[2., 2.]])"
},
{
"code": null,
"e": 11421,
"s": 11414,
"text": "Output"
},
{
"code": null,
"e": 11442,
"s": 11421,
"text": "array([68.6402382])\n"
},
{
"code": null,
"e": 11688,
"s": 11442,
"text": "Stochastic Gradient Descent (SGD) regressor basically implements a plain SGD learning routine supporting various loss functions and penalties to fit linear regression models. Scikit-learn provides SGDRegressor module to implement SGD regression."
},
{
"code": null,
"e": 11899,
"s": 11688,
"text": "Parameters used by SGDRegressor are almost same as that were used in SGDClassifier module. The difference lies in ‘loss’ parameter. For SGDRegressor modules’ loss parameter the positives values are as follows −"
},
{
"code": null,
"e": 11959,
"s": 11899,
"text": "squared_loss − It refers to the ordinary least squares fit."
},
{
"code": null,
"e": 12019,
"s": 11959,
"text": "squared_loss − It refers to the ordinary least squares fit."
},
{
"code": null,
"e": 12232,
"s": 12019,
"text": "huber: SGDRegressor − correct the outliers by switching from squared to linear loss past a distance of epsilon. The work of ‘huber’ is to modify ‘squared_loss’ so that algorithm focus less on correcting outliers."
},
{
"code": null,
"e": 12445,
"s": 12232,
"text": "huber: SGDRegressor − correct the outliers by switching from squared to linear loss past a distance of epsilon. The work of ‘huber’ is to modify ‘squared_loss’ so that algorithm focus less on correcting outliers."
},
{
"code": null,
"e": 12518,
"s": 12445,
"text": "epsilon_insensitive − Actually, it ignores the errors less than epsilon."
},
{
"code": null,
"e": 12591,
"s": 12518,
"text": "epsilon_insensitive − Actually, it ignores the errors less than epsilon."
},
{
"code": null,
"e": 12737,
"s": 12591,
"text": "squared_epsilon_insensitive − It is same as epsilon_insensitive. The only difference is that it becomes squared loss past a tolerance of epsilon."
},
{
"code": null,
"e": 12883,
"s": 12737,
"text": "squared_epsilon_insensitive − It is same as epsilon_insensitive. The only difference is that it becomes squared loss past a tolerance of epsilon."
},
{
"code": null,
"e": 13076,
"s": 12883,
"text": "Another difference is that the parameter named ‘power_t’ has the default value of 0.25 rather than 0.5 as in SGDClassifier. Furthermore, it doesn’t have ‘class_weight’ and ‘n_jobs’ parameters."
},
{
"code": null,
"e": 13205,
"s": 13076,
"text": "Attributes of SGDRegressor are also same as that were of SGDClassifier module. Rather it has three extra attributes as follows −"
},
{
"code": null,
"e": 13247,
"s": 13205,
"text": "average_coef_ − array, shape(n_features,)"
},
{
"code": null,
"e": 13289,
"s": 13247,
"text": "average_coef_ − array, shape(n_features,)"
},
{
"code": null,
"e": 13364,
"s": 13289,
"text": "As name suggest, it provides the average weights assigned to the features."
},
{
"code": null,
"e": 13402,
"s": 13364,
"text": "average_intercept_ − array, shape(1,)"
},
{
"code": null,
"e": 13440,
"s": 13402,
"text": "average_intercept_ − array, shape(1,)"
},
{
"code": null,
"e": 13498,
"s": 13440,
"text": "As name suggest, it provides the averaged intercept term."
},
{
"code": null,
"e": 13507,
"s": 13498,
"text": "t_ − int"
},
{
"code": null,
"e": 13516,
"s": 13507,
"text": "t_ − int"
},
{
"code": null,
"e": 13594,
"s": 13516,
"text": "It provides the number of weight updates performed during the training phase."
},
{
"code": null,
"e": 13707,
"s": 13594,
"text": "Note − the attributes average_coef_ and average_intercept_ will work after enabling parameter ‘average’ to True."
},
{
"code": null,
"e": 13730,
"s": 13707,
"text": "Implementation Example"
},
{
"code": null,
"e": 13787,
"s": 13730,
"text": "Following Python script uses SGDRegressor linear model −"
},
{
"code": null,
"e": 14100,
"s": 13787,
"text": "import numpy as np\nfrom sklearn import linear_model\nn_samples, n_features = 10, 5\nrng = np.random.RandomState(0)\ny = rng.randn(n_samples)\nX = rng.randn(n_samples, n_features)\nSGDReg =linear_model.SGDRegressor(\n max_iter = 1000,penalty = \"elasticnet\",loss = 'huber',tol = 1e-3, average = True\n)\nSGDReg.fit(X, y)"
},
{
"code": null,
"e": 14107,
"s": 14100,
"text": "Output"
},
{
"code": null,
"e": 14514,
"s": 14107,
"text": "SGDRegressor(\n alpha = 0.0001, average = True, early_stopping = False, epsilon = 0.1,\n eta0 = 0.01, fit_intercept = True, l1_ratio = 0.15,\n learning_rate = 'invscaling', loss = 'huber', max_iter = 1000,\n n_iter = None, n_iter_no_change = 5, penalty = 'elasticnet', power_t = 0.25,\n random_state = None, shuffle = True, tol = 0.001, validation_fraction = 0.1,\n verbose = 0, warm_start = False\n)\n"
},
{
"code": null,
"e": 14522,
"s": 14514,
"text": "Example"
},
{
"code": null,
"e": 14612,
"s": 14522,
"text": "Now, once fitted, we can get the weight vector with the help of following python script −"
},
{
"code": null,
"e": 14625,
"s": 14612,
"text": "SGDReg.coef_"
},
{
"code": null,
"e": 14632,
"s": 14625,
"text": "Output"
},
{
"code": null,
"e": 14703,
"s": 14632,
"text": "array([-0.00423314, 0.00362922, -0.00380136, 0.00585455, 0.00396787])\n"
},
{
"code": null,
"e": 14711,
"s": 14703,
"text": "Example"
},
{
"code": null,
"e": 14799,
"s": 14711,
"text": "Similarly, we can get the value of intercept with the help of following python script −"
},
{
"code": null,
"e": 14816,
"s": 14799,
"text": "SGReg.intercept_"
},
{
"code": null,
"e": 14823,
"s": 14816,
"text": "Output"
},
{
"code": null,
"e": 14841,
"s": 14823,
"text": "SGReg.intercept_\n"
},
{
"code": null,
"e": 14849,
"s": 14841,
"text": "Example"
},
{
"code": null,
"e": 14958,
"s": 14849,
"text": "We can get the number of weight updates during training phase with the help of the following python script −"
},
{
"code": null,
"e": 14968,
"s": 14958,
"text": "SGDReg.t_"
},
{
"code": null,
"e": 14975,
"s": 14968,
"text": "Output"
},
{
"code": null,
"e": 14981,
"s": 14975,
"text": "61.0\n"
},
{
"code": null,
"e": 15009,
"s": 14981,
"text": "Following the pros of SGD −"
},
{
"code": null,
"e": 15062,
"s": 15009,
"text": "Stochastic Gradient Descent (SGD) is very efficient."
},
{
"code": null,
"e": 15115,
"s": 15062,
"text": "Stochastic Gradient Descent (SGD) is very efficient."
},
{
"code": null,
"e": 15196,
"s": 15115,
"text": "It is very easy to implement as there are lots of opportunities for code tuning."
},
{
"code": null,
"e": 15277,
"s": 15196,
"text": "It is very easy to implement as there are lots of opportunities for code tuning."
},
{
"code": null,
"e": 15305,
"s": 15277,
"text": "Following the cons of SGD −"
},
{
"code": null,
"e": 15404,
"s": 15305,
"text": "Stochastic Gradient Descent (SGD) requires several hyperparameters like regularization parameters."
},
{
"code": null,
"e": 15503,
"s": 15404,
"text": "Stochastic Gradient Descent (SGD) requires several hyperparameters like regularization parameters."
},
{
"code": null,
"e": 15539,
"s": 15503,
"text": "It is sensitive to feature scaling."
}
] |
How to Deploy React project on Firebase?
|
06 Jan, 2021
When developing any project we must host it somewhere so that the whole world can see our hard-work. Hosting websites can be hectic sometimes, but you don’t need to worry as we can now host our React project on Firebase within a minute or two with a very simple setup.
Steps to Deploy React project on Firebase:
Follow the below steps or specially needed to Setup a Firebase for your React Project.
Step 1: First we shall set up our Firebase project, go to its official website, and create a project as shown below.
Step 2: Then we will enable Firebase Hosting by going into the hosting section under Build dropdown.
Step 3: Then we will go through the hosting setup as described below.
Step 3: Then we will go through the hosting setup as described below.
Creating React Application:
Step 1: Create a React application using the following command:npx create-react-app react_hostingStep 2: Install Firebase Tools:
Step 1: Create a React application using the following command:
npx create-react-app react_hosting
Step 2: Install Firebase Tools:
npm install -g firebase-toolsProject Structure:Project Structure
npm install -g firebase-tools
Project Structure:
Project Structure
Hosting Website:
Step 1: First, we will initialize a firebase project in our React app by running the following command in the console in our root directory.firebase initNow type y as we are ready to proceed.
Step 1: First, we will initialize a firebase project in our React app by running the following command in the console in our root directory.
firebase init
Now type y as we are ready to proceed.
Step 2: Select Hosting from the options provided.
Step 3: Select the Use an existing project option.
Step 4: As the build folder of react apps is generated in the build folder by default, we will use the same as our public directory.
Step 5: Type y as we want to configure our app as a single-page app.The initialization is complete, now we just need to run a few commands and our application will be ready to go.
The initialization is complete, now we just need to run a few commands and our application will be ready to go.
Step 6: Now we will run the following command to build our react app.npm run build
npm run build
Step 7: Now we just need to run the last command and our application will be deployed.firebase deployThis will deploy our project and also provide us the hosting link which we can visit.
firebase deploy
This will deploy our project and also provide us the hosting link which we can visit.
Output:We can verify that our website was successfully deployed by visiting the hosting link provided by firebase in the console as shown below:
Firebase
react-js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n06 Jan, 2021"
},
{
"code": null,
"e": 323,
"s": 53,
"text": "When developing any project we must host it somewhere so that the whole world can see our hard-work. Hosting websites can be hectic sometimes, but you don’t need to worry as we can now host our React project on Firebase within a minute or two with a very simple setup. "
},
{
"code": null,
"e": 366,
"s": 323,
"text": "Steps to Deploy React project on Firebase:"
},
{
"code": null,
"e": 453,
"s": 366,
"text": "Follow the below steps or specially needed to Setup a Firebase for your React Project."
},
{
"code": null,
"e": 570,
"s": 453,
"text": "Step 1: First we shall set up our Firebase project, go to its official website, and create a project as shown below."
},
{
"code": null,
"e": 671,
"s": 570,
"text": "Step 2: Then we will enable Firebase Hosting by going into the hosting section under Build dropdown."
},
{
"code": null,
"e": 741,
"s": 671,
"text": "Step 3: Then we will go through the hosting setup as described below."
},
{
"code": null,
"e": 811,
"s": 741,
"text": "Step 3: Then we will go through the hosting setup as described below."
},
{
"code": null,
"e": 839,
"s": 811,
"text": "Creating React Application:"
},
{
"code": null,
"e": 968,
"s": 839,
"text": "Step 1: Create a React application using the following command:npx create-react-app react_hostingStep 2: Install Firebase Tools:"
},
{
"code": null,
"e": 1032,
"s": 968,
"text": "Step 1: Create a React application using the following command:"
},
{
"code": null,
"e": 1067,
"s": 1032,
"text": "npx create-react-app react_hosting"
},
{
"code": null,
"e": 1099,
"s": 1067,
"text": "Step 2: Install Firebase Tools:"
},
{
"code": null,
"e": 1164,
"s": 1099,
"text": "npm install -g firebase-toolsProject Structure:Project Structure"
},
{
"code": null,
"e": 1194,
"s": 1164,
"text": "npm install -g firebase-tools"
},
{
"code": null,
"e": 1213,
"s": 1194,
"text": "Project Structure:"
},
{
"code": null,
"e": 1231,
"s": 1213,
"text": "Project Structure"
},
{
"code": null,
"e": 1248,
"s": 1231,
"text": "Hosting Website:"
},
{
"code": null,
"e": 1440,
"s": 1248,
"text": "Step 1: First, we will initialize a firebase project in our React app by running the following command in the console in our root directory.firebase initNow type y as we are ready to proceed."
},
{
"code": null,
"e": 1581,
"s": 1440,
"text": "Step 1: First, we will initialize a firebase project in our React app by running the following command in the console in our root directory."
},
{
"code": null,
"e": 1595,
"s": 1581,
"text": "firebase init"
},
{
"code": null,
"e": 1634,
"s": 1595,
"text": "Now type y as we are ready to proceed."
},
{
"code": null,
"e": 1684,
"s": 1634,
"text": "Step 2: Select Hosting from the options provided."
},
{
"code": null,
"e": 1735,
"s": 1684,
"text": "Step 3: Select the Use an existing project option."
},
{
"code": null,
"e": 1868,
"s": 1735,
"text": "Step 4: As the build folder of react apps is generated in the build folder by default, we will use the same as our public directory."
},
{
"code": null,
"e": 2048,
"s": 1868,
"text": "Step 5: Type y as we want to configure our app as a single-page app.The initialization is complete, now we just need to run a few commands and our application will be ready to go."
},
{
"code": null,
"e": 2160,
"s": 2048,
"text": "The initialization is complete, now we just need to run a few commands and our application will be ready to go."
},
{
"code": null,
"e": 2243,
"s": 2160,
"text": "Step 6: Now we will run the following command to build our react app.npm run build"
},
{
"code": null,
"e": 2257,
"s": 2243,
"text": "npm run build"
},
{
"code": null,
"e": 2444,
"s": 2257,
"text": "Step 7: Now we just need to run the last command and our application will be deployed.firebase deployThis will deploy our project and also provide us the hosting link which we can visit."
},
{
"code": null,
"e": 2460,
"s": 2444,
"text": "firebase deploy"
},
{
"code": null,
"e": 2546,
"s": 2460,
"text": "This will deploy our project and also provide us the hosting link which we can visit."
},
{
"code": null,
"e": 2691,
"s": 2546,
"text": "Output:We can verify that our website was successfully deployed by visiting the hosting link provided by firebase in the console as shown below:"
},
{
"code": null,
"e": 2700,
"s": 2691,
"text": "Firebase"
},
{
"code": null,
"e": 2709,
"s": 2700,
"text": "react-js"
},
{
"code": null,
"e": 2720,
"s": 2709,
"text": "JavaScript"
},
{
"code": null,
"e": 2737,
"s": 2720,
"text": "Web Technologies"
}
] |
C# | Uri.ToString() Method
|
30 Apr, 2019
Uri.HexEscape(Char) Method is used to get a canonical string representation for the specified Uri instance.
Syntax: public override string ToString ();
Return Value: This method returns a String instance that contains the unescaped canonical representation of the Uri instance. All characters are unescaped except #, ?, and %.
Below programs illustrate the use of Uri.ToString() Method:
Example 1:
// C# program to demonstrate the// Uri.ToString() Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { // Create a new Uri from a string address. Uri uri = new Uri("HTTP://www.Contoso.com:80/thick%20and%20thin.htm"); // Converts a specified uri into // its string equivalent. // using ToString() method string value = uri.ToString(); // Displaying the result Console.WriteLine("Converted string is: {0}", value); }}
Converted string is: http://www.contoso.com/thick and thin.htm
Example 2:
// C# program to demonstrate the// Uri.ToString() Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { // calling get() method get(new Uri("http://www.contoso.com")); get(new Uri("http://www.google.com")); } // defining get() method public static void get(Uri uri) { // Converts a specified uri // into its string equivalent. // using ToString() method string value = uri.ToString(); // Displaying the result Console.WriteLine("Converted string is: {0}", value); }}
Converted string is: http://www.contoso.com/
Converted string is: http://www.google.com/
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.uri.tostring?view=netstandard-2.1
CSharp-method
CSharp-Uri-Class
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# Dictionary with examples
C# | Delegates
Introduction to .NET Framework
C# | Multiple inheritance using interfaces
Differences Between .NET Core and .NET Framework
C# | Method Overriding
C# | Data Types
C# | String.IndexOf( ) Method | Set - 1
C# | Constructors
C# | Class and Object
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Apr, 2019"
},
{
"code": null,
"e": 136,
"s": 28,
"text": "Uri.HexEscape(Char) Method is used to get a canonical string representation for the specified Uri instance."
},
{
"code": null,
"e": 180,
"s": 136,
"text": "Syntax: public override string ToString ();"
},
{
"code": null,
"e": 355,
"s": 180,
"text": "Return Value: This method returns a String instance that contains the unescaped canonical representation of the Uri instance. All characters are unescaped except #, ?, and %."
},
{
"code": null,
"e": 415,
"s": 355,
"text": "Below programs illustrate the use of Uri.ToString() Method:"
},
{
"code": null,
"e": 426,
"s": 415,
"text": "Example 1:"
},
{
"code": "// C# program to demonstrate the// Uri.ToString() Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { // Create a new Uri from a string address. Uri uri = new Uri(\"HTTP://www.Contoso.com:80/thick%20and%20thin.htm\"); // Converts a specified uri into // its string equivalent. // using ToString() method string value = uri.ToString(); // Displaying the result Console.WriteLine(\"Converted string is: {0}\", value); }}",
"e": 966,
"s": 426,
"text": null
},
{
"code": null,
"e": 1030,
"s": 966,
"text": "Converted string is: http://www.contoso.com/thick and thin.htm\n"
},
{
"code": null,
"e": 1041,
"s": 1030,
"text": "Example 2:"
},
{
"code": "// C# program to demonstrate the// Uri.ToString() Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { // calling get() method get(new Uri(\"http://www.contoso.com\")); get(new Uri(\"http://www.google.com\")); } // defining get() method public static void get(Uri uri) { // Converts a specified uri // into its string equivalent. // using ToString() method string value = uri.ToString(); // Displaying the result Console.WriteLine(\"Converted string is: {0}\", value); }}",
"e": 1655,
"s": 1041,
"text": null
},
{
"code": null,
"e": 1745,
"s": 1655,
"text": "Converted string is: http://www.contoso.com/\nConverted string is: http://www.google.com/\n"
},
{
"code": null,
"e": 1756,
"s": 1745,
"text": "Reference:"
},
{
"code": null,
"e": 1841,
"s": 1756,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.uri.tostring?view=netstandard-2.1"
},
{
"code": null,
"e": 1855,
"s": 1841,
"text": "CSharp-method"
},
{
"code": null,
"e": 1872,
"s": 1855,
"text": "CSharp-Uri-Class"
},
{
"code": null,
"e": 1875,
"s": 1872,
"text": "C#"
},
{
"code": null,
"e": 1973,
"s": 1875,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2001,
"s": 1973,
"text": "C# Dictionary with examples"
},
{
"code": null,
"e": 2016,
"s": 2001,
"text": "C# | Delegates"
},
{
"code": null,
"e": 2047,
"s": 2016,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 2090,
"s": 2047,
"text": "C# | Multiple inheritance using interfaces"
},
{
"code": null,
"e": 2139,
"s": 2090,
"text": "Differences Between .NET Core and .NET Framework"
},
{
"code": null,
"e": 2162,
"s": 2139,
"text": "C# | Method Overriding"
},
{
"code": null,
"e": 2178,
"s": 2162,
"text": "C# | Data Types"
},
{
"code": null,
"e": 2218,
"s": 2178,
"text": "C# | String.IndexOf( ) Method | Set - 1"
},
{
"code": null,
"e": 2236,
"s": 2218,
"text": "C# | Constructors"
}
] |
Kotlin | Math.abs() method with Examples
|
11 Nov, 2019
The Math.abs() function returns the absolute value of a given argument. If the argument is non-negative, the argument itself is returned. whereas, if the argument is negative, it’s negation value is returned. Basically, it works as the modulus function in mathematics.
Syntax : fun abs(x : DataType) : DataType
Parameters: It can take values of Data type int, double, long, float.
Returns: It returns absolute value of the argument, without changing the data type.
Exceptions:
If the argument is NaN, the result is NaN.
If the argument is Int.MIN_VALUE, the result is that same value, Int.MIN_VALUE, which is negative.
If the argument is Long.MIN_VALUE, the result if that same value, Long.MIN_VALUE, which is negative.
Code #1: Taking float and double data types as argument.
// Kotlin program to illustrate// working of Math.abs() method import kotlin.math.abs fun main(args : Array<String>){ val f = -45.23f; val d = 999.32; // abs() function taking float as input println(abs(f)); // abs() function taking double as input println(abs(d));}
Output:
45.23
999.32
Code #2: Taking int and long data types as argument.
// Kotlin program to illustrate// working of Math.abs() method import kotlin.math.abs fun main(args : Array<String>){ val i = -0; val l = -69973688; // abs() function taking int as input println(abs(i)); println(abs(Int.MIN_VALUE)); // abs() function taking long as input println(abs(l)); println(abs(Long.MIN_VALUE));}
Output:
0
-2147483648
69973688
-9223372036854775808
Kotlin Mics
Kotlin
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Nov, 2019"
},
{
"code": null,
"e": 297,
"s": 28,
"text": "The Math.abs() function returns the absolute value of a given argument. If the argument is non-negative, the argument itself is returned. whereas, if the argument is negative, it’s negation value is returned. Basically, it works as the modulus function in mathematics."
},
{
"code": null,
"e": 339,
"s": 297,
"text": "Syntax : fun abs(x : DataType) : DataType"
},
{
"code": null,
"e": 409,
"s": 339,
"text": "Parameters: It can take values of Data type int, double, long, float."
},
{
"code": null,
"e": 493,
"s": 409,
"text": "Returns: It returns absolute value of the argument, without changing the data type."
},
{
"code": null,
"e": 505,
"s": 493,
"text": "Exceptions:"
},
{
"code": null,
"e": 548,
"s": 505,
"text": "If the argument is NaN, the result is NaN."
},
{
"code": null,
"e": 647,
"s": 548,
"text": "If the argument is Int.MIN_VALUE, the result is that same value, Int.MIN_VALUE, which is negative."
},
{
"code": null,
"e": 748,
"s": 647,
"text": "If the argument is Long.MIN_VALUE, the result if that same value, Long.MIN_VALUE, which is negative."
},
{
"code": null,
"e": 805,
"s": 748,
"text": "Code #1: Taking float and double data types as argument."
},
{
"code": "// Kotlin program to illustrate// working of Math.abs() method import kotlin.math.abs fun main(args : Array<String>){ val f = -45.23f; val d = 999.32; // abs() function taking float as input println(abs(f)); // abs() function taking double as input println(abs(d));}",
"e": 1099,
"s": 805,
"text": null
},
{
"code": null,
"e": 1107,
"s": 1099,
"text": "Output:"
},
{
"code": null,
"e": 1121,
"s": 1107,
"text": "45.23\n999.32\n"
},
{
"code": null,
"e": 1174,
"s": 1121,
"text": "Code #2: Taking int and long data types as argument."
},
{
"code": "// Kotlin program to illustrate// working of Math.abs() method import kotlin.math.abs fun main(args : Array<String>){ val i = -0; val l = -69973688; // abs() function taking int as input println(abs(i)); println(abs(Int.MIN_VALUE)); // abs() function taking long as input println(abs(l)); println(abs(Long.MIN_VALUE));}",
"e": 1527,
"s": 1174,
"text": null
},
{
"code": null,
"e": 1535,
"s": 1527,
"text": "Output:"
},
{
"code": null,
"e": 1581,
"s": 1535,
"text": "0\n-2147483648\n\n69973688\n-9223372036854775808\n"
},
{
"code": null,
"e": 1593,
"s": 1581,
"text": "Kotlin Mics"
},
{
"code": null,
"e": 1600,
"s": 1593,
"text": "Kotlin"
}
] |
Place k elements such that minimum distance is maximized
|
20 Apr, 2022
Given an array representing n positions along a straight line. Find k (where k <= n) elements from the array such that the minimum distance between any two (consecutive points among the k points) is maximized.
Examples :
Input : arr[] = {1, 2, 8, 4, 9}
k = 3
Output : 3
Largest minimum distance = 3
3 elements arranged at positions 1, 4 and 8,
Resulting in a minimum distance of 3
Input : arr[] = {1, 2, 7, 5, 11, 12}
k = 3
Output : 5
Largest minimum distance = 5
3 elements arranged at positions 1, 7 and 12,
resulting in a minimum distance of 5 (between
7 and 12)
A Naive Solution is to consider all subsets of size 3 and find the minimum distance for every subset. Finally, return the largest of all minimum distances.
An Efficient Solution is based on Binary Search. We first sort the array. Now we know maximum possible value result is arr[n-1] – arr[0] (for k = 2). We do a binary search for maximum result for given k. We start with the middle of the maximum possible result. If the middle is a feasible solution, we search on the right half of mid. Else we search is left half. To check feasibility, we place k elements under given mid-distance.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find largest minimum distance// among k points.#include <bits/stdc++.h> using namespace std; // Returns true if it is possible to arrange// k elements of arr[0..n-1] with minimum distance// given as mid.bool isFeasible(int mid, int arr[], int n, int k){ // Place first element at arr[0] position int pos = arr[0]; // Initialize count of elements placed. int elements = 1; // Try placing k elements with minimum // distance mid. for (int i = 1; i < n; i++) { if (arr[i] - pos >= mid) { // Place next element if its // distance from the previously // placed element is greater // than current mid pos = arr[i]; elements++; // Return if all elements are placed // successfully if (elements == k) return true; } } return 0;} // Returns largest minimum distance for k elements// in arr[0..n-1]. If elements can't be placed,// returns -1.int largestMinDist(int arr[], int n, int k){ // Sort the positions sort(arr, arr + n); // Initialize result. int res = -1; // Consider the maximum possible distance //here we are using right value as highest distance difference, //so we remove some extra checks int left = 1, right = arr[n - 1]; // left is initialized with 1 and not with arr[0] // because, minimum distance between each element // can be one and not arr[0]. consider this example: // arr[] = {9,12} and you have to place 2 element // then left = arr[0] will force the function to // look the answer between range arr[0] to arr[n-1], // i.e 9 to 12, but the answer is 3 so It is required // that you initialize the left with 1 // Do binary search for largest minimum distance while (left < right) { int mid = (left + right) / 2; // If it is possible to place k elements // with minimum distance mid, search for // higher distance. if (isFeasible(mid, arr, n, k)) { // Change value of variable max to mid if // all elements can be successfully placed res = max(res, mid); left = mid + 1; } // If not possible to place k elements, search // for lower distance else right = mid; } return res;} // Driver codeint main(){ int arr[] = { 1, 2, 8, 4, 9 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 3; cout << largestMinDist(arr, n, k); return 0;}
// Java program to find largest// minimum distance among k points.import java.util.Arrays; class GFG { // Returns true if it is possible to // arrange k elements of arr[0..n-1] // with minimum distance given as mid. static boolean isFeasible(int mid, int arr[], int n, int k) { // Place first element at arr[0] position int pos = arr[0]; // Initialize count of elements placed. int elements = 1; // Try placing k elements with minimum // distance mid. for (int i = 1; i < n; i++) { if (arr[i] - pos >= mid) { // Place next element if its // distance from the previously // placed element is greater // than current mid pos = arr[i]; elements++; // Return if all elements are // placed successfully if (elements == k) return true; } } return false; } // Returns largest minimum distance for // k elements in arr[0..n-1]. If elements // can't be placed, returns -1. static int largestMinDist(int arr[], int n, int k) { // Sort the positions Arrays.sort(arr); // Initialize result. int res = -1; // Consider the maximum possible distance int left = 1, right = arr[n - 1]; // left is initialized with 1 and not with arr[0] // because, minimum distance between each element // can be one and not arr[0]. consider this example: // arr[] = {9,12} and you have to place 2 element // then left = arr[0] will force the function to // look the answer between range arr[0] to arr[n-1], // i.e 9 to 12, but the answer is 3 so It is // required that you initialize the left with 1 // Do binary search for largest // minimum distance while (left < right) { int mid = (left + right) / 2; // If it is possible to place k // elements with minimum distance mid, // search for higher distance. if (isFeasible(mid, arr, n, k)) { // Change value of variable max to // mid if all elements can be // successfully placed res = Math.max(res, mid); left = mid + 1; } // If not possible to place k elements, // search for lower distance else right = mid; } return res; } // driver code public static void main(String[] args) { int arr[] = { 1, 2, 8, 4, 9 }; int n = arr.length; int k = 3; System.out.print(largestMinDist(arr, n, k)); }} // This code is contributed by Anant Agarwal.
# Python 3 program to find largest minimum# distance among k points. # Returns true if it is possible to arrange# k elements of arr[0..n-1] with minimum# distance given as mid. def isFeasible(mid, arr, n, k): # Place first element at arr[0] position pos = arr[0] # Initialize count of elements placed. elements = 1 # Try placing k elements with minimum # distance mid. for i in range(1, n, 1): if (arr[i] - pos >= mid): # Place next element if its distance # from the previously placed element # is greater than current mid pos = arr[i] elements += 1 # Return if all elements are placed # successfully if (elements == k): return True return 0 # Returns largest minimum distance for k elements# in arr[0..n-1]. If elements can't be placed,# returns -1. def largestMinDist(arr, n, k): # Sort the positions arr.sort(reverse=False) # Initialize result. res = -1 # Consider the maximum possible distance left = 1 right = arr[n - 1] # left is initialized with 1 and not with arr[0] # because, minimum distance between each element # can be one and not arr[0]. consider this example: # arr[] = {9,12} and you have to place 2 element # then left = arr[0] will force the function to # look the answer between range arr[0] to arr[n-1], # i.e 9 to 12, but the answer is 3 so It is required # that you initialize the left with 1 # Do binary search for largest # minimum distance while (left < right): mid = (left + right) / 2 # If it is possible to place k elements # with minimum distance mid, search for # higher distance. if (isFeasible(mid, arr, n, k)): # Change value of variable max to mid if # all elements can be successfully placed res = max(res, mid) left = mid + 1 # If not possible to place k elements, # search for lower distance else: right = mid return res # Driver codeif __name__ == '__main__': arr = [1, 2, 8, 4, 9] n = len(arr) k = 3 print(largestMinDist(arr, n, k)) # This code is contributed by# Sanjit_prasad
// C# program to find largest// minimum distance among k points.using System; public class GFG { // Returns true if it is possible to // arrange k elements of arr[0..n-1] // with minimum distance given as mid. static bool isFeasible(int mid, int[] arr, int n, int k) { // Place first element at arr[0] // position int pos = arr[0]; // Initialize count of elements placed. int elements = 1; // Try placing k elements with minimum // distance mid. for (int i = 1; i < n; i++) { if (arr[i] - pos >= mid) { // Place next element if its // distance from the previously // placed element is greater // than current mid pos = arr[i]; elements++; // Return if all elements are // placed successfully if (elements == k) return true; } } return false; } // Returns largest minimum distance for // k elements in arr[0..n-1]. If elements // can't be placed, returns -1. static int largestMinDist(int[] arr, int n, int k) { // Sort the positions Array.Sort(arr); // Initialize result. int res = -1; // Consider the maximum possible // distance int left = 1, right = arr[n - 1]; // left is initialized with 1 and not with arr[0] // because, minimum distance between each element // can be one and not arr[0]. consider this example: // arr[] = {9,12} and you have to place 2 element // then left = arr[0] will force the function to // look the answer between range arr[0] to arr[n-1], // i.e 9 to 12, but the answer is 3 so It is // required that you initialize the left with 1 // Do binary search for largest // minimum distance while (left < right) { int mid = (left + right) / 2; // If it is possible to place k // elements with minimum distance // mid, search for higher distance. if (isFeasible(mid, arr, n, k)) { // Change value of variable // max to mid if all elements // can be successfully placed res = Math.Max(res, mid); left = mid + 1; } // If not possible to place k // elements, search for lower // distance else right = mid; } return res; } // driver code public static void Main() { int[] arr = { 1, 2, 8, 4, 9 }; int n = arr.Length; int k = 3; Console.WriteLine(largestMinDist(arr, n, k)); }} // This code is contributed by Sam007.
<?php// PHP program to find largest// minimum distance among k points. // Returns true if it is possible// to arrange k elements of// arr[0..n-1] with minimum// distance given as mid.function isFeasible($mid, $arr, $n, $k){ // Place first element // at arr[0] position $pos = $arr[0]; // Initialize count of // elements placed. $elements = 1; // Try placing k elements // with minimum distance mid. for ($i = 1; $i < $n; $i++) { if ($arr[$i] - $pos >= $mid) { // Place next element if // its distance from the // previously placed // element is greater // than current mid $pos = $arr[$i]; $elements++; // Return if all elements // are placed successfully if ($elements == $k) return true; } } return 0;} // Returns largest minimum// distance for k elements// in arr[0..n-1]. If elements// can't be placed, returns -1.function largestMinDist($arr, $n, $k){ // Sort the positions sort($arr); // Initialize result. $res = -1; // Consider the maximum // possible distance $left = 1; $right = $arr[$n - 1]; // left is initialized with 1 and not with arr[0] // because, minimum distance between each element // can be one and not arr[0]. consider this example: // arr[] = {9,12} and you have to place 2 element // then left = arr[0] will force the function to // look the answer between range arr[0] to arr[n-1], // i.e 9 to 12, but the answer is 3 so It is required // that you initialize the left with 1 // Do binary search for // largest minimum distance while ($left < $right) { $mid = ($left + $right) / 2; // If it is possible to place // k elements with minimum // distance mid, search for // higher distance. if (isFeasible($mid, $arr, $n, $k)) { // Change value of variable // max to mid if all elements // can be successfully placed $res = max($res, $mid); $left = $mid + 1; } // If not possible to place // k elements, search for // lower distance else $right = $mid; } return $res;} // Driver Code$arr = array(1, 2, 8, 4, 9);$n = sizeof($arr);$k = 3;echo largestMinDist($arr, $n, $k); // This code is contributed by aj_36?>
<script> // Javascript program to find largest // minimum distance among k points. // Returns true if it is possible to // arrange k elements of arr[0..n-1] // with minimum distance given as mid. function isFeasible(mid, arr, n, k) { // Place first element at arr[0] // position let pos = arr[0]; // Initialize count of elements placed. let elements = 1; // Try placing k elements with minimum // distance mid. for (let i = 1; i < n; i++) { if (arr[i] - pos >= mid) { // Place next element if its // distance from the previously // placed element is greater // than current mid pos = arr[i]; elements++; // Return if all elements are // placed successfully if (elements == k) return true; } } return false; } // Returns largest minimum distance for // k elements in arr[0..n-1]. If elements // can't be placed, returns -1. function largestMinDist(arr, n, k) { // Sort the positions arr.sort(function(a, b){return a - b}); // Initialize result. let res = -1; // Consider the maximum possible // distance let left = 1, right = arr[n - 1]; // left is initialized with 1 and not with arr[0] // because, minimum distance between each element // can be one and not arr[0]. consider this example: // arr[] = {9,12} and you have to place 2 element // then left = arr[0] will force the function to // look the answer between range arr[0] to arr[n-1], // i.e 9 to 12, but the answer is 3 so It is // required that you initialize the left with 1 // Do binary search for largest // minimum distance while (left < right) { let mid = parseInt((left + right) / 2, 10); // If it is possible to place k // elements with minimum distance // mid, search for higher distance. if (isFeasible(mid, arr, n, k)) { // Change value of variable // max to mid if all elements // can be successfully placed res = Math.max(res, mid); left = mid + 1; } // If not possible to place k // elements, search for lower // distance else right = mid; } return res; } let arr = [ 1, 2, 8, 4, 9 ]; let n = arr.length; let k = 3; document.write(largestMinDist(arr, n, k)); </script>
3
Time Complexity : O(nlog n) , where n is length of array.
Space Compeity : O(1)
This article is contributed by Raghav Jajodia. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Sam007
jit_t
sonamchawla
Sanjit_Prasad
naklicoder
AakashYadav4
achy97
mukesh07
gulshankumarar231
ayush123ngp
bhiruddigvijay
iramkhalid24
simmytarika5
Binary Search
Arrays
Divide and Conquer
Arrays
Divide and Conquer
Binary Search
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
Merge Sort
QuickSort
Binary Search
Maximum and minimum of an array using minimum number of comparisons
Count Inversions in an array | Set 1 (Using Merge Sort)
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n20 Apr, 2022"
},
{
"code": null,
"e": 264,
"s": 54,
"text": "Given an array representing n positions along a straight line. Find k (where k <= n) elements from the array such that the minimum distance between any two (consecutive points among the k points) is maximized."
},
{
"code": null,
"e": 277,
"s": 264,
"text": "Examples : "
},
{
"code": null,
"e": 651,
"s": 277,
"text": "Input : arr[] = {1, 2, 8, 4, 9}\n k = 3\nOutput : 3\nLargest minimum distance = 3\n3 elements arranged at positions 1, 4 and 8, \nResulting in a minimum distance of 3\n\nInput : arr[] = {1, 2, 7, 5, 11, 12}\n k = 3\nOutput : 5\nLargest minimum distance = 5\n3 elements arranged at positions 1, 7 and 12, \nresulting in a minimum distance of 5 (between\n7 and 12)"
},
{
"code": null,
"e": 807,
"s": 651,
"text": "A Naive Solution is to consider all subsets of size 3 and find the minimum distance for every subset. Finally, return the largest of all minimum distances."
},
{
"code": null,
"e": 1239,
"s": 807,
"text": "An Efficient Solution is based on Binary Search. We first sort the array. Now we know maximum possible value result is arr[n-1] – arr[0] (for k = 2). We do a binary search for maximum result for given k. We start with the middle of the maximum possible result. If the middle is a feasible solution, we search on the right half of mid. Else we search is left half. To check feasibility, we place k elements under given mid-distance."
},
{
"code": null,
"e": 1243,
"s": 1239,
"text": "C++"
},
{
"code": null,
"e": 1248,
"s": 1243,
"text": "Java"
},
{
"code": null,
"e": 1256,
"s": 1248,
"text": "Python3"
},
{
"code": null,
"e": 1259,
"s": 1256,
"text": "C#"
},
{
"code": null,
"e": 1263,
"s": 1259,
"text": "PHP"
},
{
"code": null,
"e": 1274,
"s": 1263,
"text": "Javascript"
},
{
"code": "// C++ program to find largest minimum distance// among k points.#include <bits/stdc++.h> using namespace std; // Returns true if it is possible to arrange// k elements of arr[0..n-1] with minimum distance// given as mid.bool isFeasible(int mid, int arr[], int n, int k){ // Place first element at arr[0] position int pos = arr[0]; // Initialize count of elements placed. int elements = 1; // Try placing k elements with minimum // distance mid. for (int i = 1; i < n; i++) { if (arr[i] - pos >= mid) { // Place next element if its // distance from the previously // placed element is greater // than current mid pos = arr[i]; elements++; // Return if all elements are placed // successfully if (elements == k) return true; } } return 0;} // Returns largest minimum distance for k elements// in arr[0..n-1]. If elements can't be placed,// returns -1.int largestMinDist(int arr[], int n, int k){ // Sort the positions sort(arr, arr + n); // Initialize result. int res = -1; // Consider the maximum possible distance //here we are using right value as highest distance difference, //so we remove some extra checks int left = 1, right = arr[n - 1]; // left is initialized with 1 and not with arr[0] // because, minimum distance between each element // can be one and not arr[0]. consider this example: // arr[] = {9,12} and you have to place 2 element // then left = arr[0] will force the function to // look the answer between range arr[0] to arr[n-1], // i.e 9 to 12, but the answer is 3 so It is required // that you initialize the left with 1 // Do binary search for largest minimum distance while (left < right) { int mid = (left + right) / 2; // If it is possible to place k elements // with minimum distance mid, search for // higher distance. if (isFeasible(mid, arr, n, k)) { // Change value of variable max to mid if // all elements can be successfully placed res = max(res, mid); left = mid + 1; } // If not possible to place k elements, search // for lower distance else right = mid; } return res;} // Driver codeint main(){ int arr[] = { 1, 2, 8, 4, 9 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 3; cout << largestMinDist(arr, n, k); return 0;}",
"e": 3794,
"s": 1274,
"text": null
},
{
"code": "// Java program to find largest// minimum distance among k points.import java.util.Arrays; class GFG { // Returns true if it is possible to // arrange k elements of arr[0..n-1] // with minimum distance given as mid. static boolean isFeasible(int mid, int arr[], int n, int k) { // Place first element at arr[0] position int pos = arr[0]; // Initialize count of elements placed. int elements = 1; // Try placing k elements with minimum // distance mid. for (int i = 1; i < n; i++) { if (arr[i] - pos >= mid) { // Place next element if its // distance from the previously // placed element is greater // than current mid pos = arr[i]; elements++; // Return if all elements are // placed successfully if (elements == k) return true; } } return false; } // Returns largest minimum distance for // k elements in arr[0..n-1]. If elements // can't be placed, returns -1. static int largestMinDist(int arr[], int n, int k) { // Sort the positions Arrays.sort(arr); // Initialize result. int res = -1; // Consider the maximum possible distance int left = 1, right = arr[n - 1]; // left is initialized with 1 and not with arr[0] // because, minimum distance between each element // can be one and not arr[0]. consider this example: // arr[] = {9,12} and you have to place 2 element // then left = arr[0] will force the function to // look the answer between range arr[0] to arr[n-1], // i.e 9 to 12, but the answer is 3 so It is // required that you initialize the left with 1 // Do binary search for largest // minimum distance while (left < right) { int mid = (left + right) / 2; // If it is possible to place k // elements with minimum distance mid, // search for higher distance. if (isFeasible(mid, arr, n, k)) { // Change value of variable max to // mid if all elements can be // successfully placed res = Math.max(res, mid); left = mid + 1; } // If not possible to place k elements, // search for lower distance else right = mid; } return res; } // driver code public static void main(String[] args) { int arr[] = { 1, 2, 8, 4, 9 }; int n = arr.length; int k = 3; System.out.print(largestMinDist(arr, n, k)); }} // This code is contributed by Anant Agarwal.",
"e": 6627,
"s": 3794,
"text": null
},
{
"code": "# Python 3 program to find largest minimum# distance among k points. # Returns true if it is possible to arrange# k elements of arr[0..n-1] with minimum# distance given as mid. def isFeasible(mid, arr, n, k): # Place first element at arr[0] position pos = arr[0] # Initialize count of elements placed. elements = 1 # Try placing k elements with minimum # distance mid. for i in range(1, n, 1): if (arr[i] - pos >= mid): # Place next element if its distance # from the previously placed element # is greater than current mid pos = arr[i] elements += 1 # Return if all elements are placed # successfully if (elements == k): return True return 0 # Returns largest minimum distance for k elements# in arr[0..n-1]. If elements can't be placed,# returns -1. def largestMinDist(arr, n, k): # Sort the positions arr.sort(reverse=False) # Initialize result. res = -1 # Consider the maximum possible distance left = 1 right = arr[n - 1] # left is initialized with 1 and not with arr[0] # because, minimum distance between each element # can be one and not arr[0]. consider this example: # arr[] = {9,12} and you have to place 2 element # then left = arr[0] will force the function to # look the answer between range arr[0] to arr[n-1], # i.e 9 to 12, but the answer is 3 so It is required # that you initialize the left with 1 # Do binary search for largest # minimum distance while (left < right): mid = (left + right) / 2 # If it is possible to place k elements # with minimum distance mid, search for # higher distance. if (isFeasible(mid, arr, n, k)): # Change value of variable max to mid if # all elements can be successfully placed res = max(res, mid) left = mid + 1 # If not possible to place k elements, # search for lower distance else: right = mid return res # Driver codeif __name__ == '__main__': arr = [1, 2, 8, 4, 9] n = len(arr) k = 3 print(largestMinDist(arr, n, k)) # This code is contributed by# Sanjit_prasad",
"e": 8877,
"s": 6627,
"text": null
},
{
"code": "// C# program to find largest// minimum distance among k points.using System; public class GFG { // Returns true if it is possible to // arrange k elements of arr[0..n-1] // with minimum distance given as mid. static bool isFeasible(int mid, int[] arr, int n, int k) { // Place first element at arr[0] // position int pos = arr[0]; // Initialize count of elements placed. int elements = 1; // Try placing k elements with minimum // distance mid. for (int i = 1; i < n; i++) { if (arr[i] - pos >= mid) { // Place next element if its // distance from the previously // placed element is greater // than current mid pos = arr[i]; elements++; // Return if all elements are // placed successfully if (elements == k) return true; } } return false; } // Returns largest minimum distance for // k elements in arr[0..n-1]. If elements // can't be placed, returns -1. static int largestMinDist(int[] arr, int n, int k) { // Sort the positions Array.Sort(arr); // Initialize result. int res = -1; // Consider the maximum possible // distance int left = 1, right = arr[n - 1]; // left is initialized with 1 and not with arr[0] // because, minimum distance between each element // can be one and not arr[0]. consider this example: // arr[] = {9,12} and you have to place 2 element // then left = arr[0] will force the function to // look the answer between range arr[0] to arr[n-1], // i.e 9 to 12, but the answer is 3 so It is // required that you initialize the left with 1 // Do binary search for largest // minimum distance while (left < right) { int mid = (left + right) / 2; // If it is possible to place k // elements with minimum distance // mid, search for higher distance. if (isFeasible(mid, arr, n, k)) { // Change value of variable // max to mid if all elements // can be successfully placed res = Math.Max(res, mid); left = mid + 1; } // If not possible to place k // elements, search for lower // distance else right = mid; } return res; } // driver code public static void Main() { int[] arr = { 1, 2, 8, 4, 9 }; int n = arr.Length; int k = 3; Console.WriteLine(largestMinDist(arr, n, k)); }} // This code is contributed by Sam007.",
"e": 11692,
"s": 8877,
"text": null
},
{
"code": "<?php// PHP program to find largest// minimum distance among k points. // Returns true if it is possible// to arrange k elements of// arr[0..n-1] with minimum// distance given as mid.function isFeasible($mid, $arr, $n, $k){ // Place first element // at arr[0] position $pos = $arr[0]; // Initialize count of // elements placed. $elements = 1; // Try placing k elements // with minimum distance mid. for ($i = 1; $i < $n; $i++) { if ($arr[$i] - $pos >= $mid) { // Place next element if // its distance from the // previously placed // element is greater // than current mid $pos = $arr[$i]; $elements++; // Return if all elements // are placed successfully if ($elements == $k) return true; } } return 0;} // Returns largest minimum// distance for k elements// in arr[0..n-1]. If elements// can't be placed, returns -1.function largestMinDist($arr, $n, $k){ // Sort the positions sort($arr); // Initialize result. $res = -1; // Consider the maximum // possible distance $left = 1; $right = $arr[$n - 1]; // left is initialized with 1 and not with arr[0] // because, minimum distance between each element // can be one and not arr[0]. consider this example: // arr[] = {9,12} and you have to place 2 element // then left = arr[0] will force the function to // look the answer between range arr[0] to arr[n-1], // i.e 9 to 12, but the answer is 3 so It is required // that you initialize the left with 1 // Do binary search for // largest minimum distance while ($left < $right) { $mid = ($left + $right) / 2; // If it is possible to place // k elements with minimum // distance mid, search for // higher distance. if (isFeasible($mid, $arr, $n, $k)) { // Change value of variable // max to mid if all elements // can be successfully placed $res = max($res, $mid); $left = $mid + 1; } // If not possible to place // k elements, search for // lower distance else $right = $mid; } return $res;} // Driver Code$arr = array(1, 2, 8, 4, 9);$n = sizeof($arr);$k = 3;echo largestMinDist($arr, $n, $k); // This code is contributed by aj_36?>",
"e": 14170,
"s": 11692,
"text": null
},
{
"code": "<script> // Javascript program to find largest // minimum distance among k points. // Returns true if it is possible to // arrange k elements of arr[0..n-1] // with minimum distance given as mid. function isFeasible(mid, arr, n, k) { // Place first element at arr[0] // position let pos = arr[0]; // Initialize count of elements placed. let elements = 1; // Try placing k elements with minimum // distance mid. for (let i = 1; i < n; i++) { if (arr[i] - pos >= mid) { // Place next element if its // distance from the previously // placed element is greater // than current mid pos = arr[i]; elements++; // Return if all elements are // placed successfully if (elements == k) return true; } } return false; } // Returns largest minimum distance for // k elements in arr[0..n-1]. If elements // can't be placed, returns -1. function largestMinDist(arr, n, k) { // Sort the positions arr.sort(function(a, b){return a - b}); // Initialize result. let res = -1; // Consider the maximum possible // distance let left = 1, right = arr[n - 1]; // left is initialized with 1 and not with arr[0] // because, minimum distance between each element // can be one and not arr[0]. consider this example: // arr[] = {9,12} and you have to place 2 element // then left = arr[0] will force the function to // look the answer between range arr[0] to arr[n-1], // i.e 9 to 12, but the answer is 3 so It is // required that you initialize the left with 1 // Do binary search for largest // minimum distance while (left < right) { let mid = parseInt((left + right) / 2, 10); // If it is possible to place k // elements with minimum distance // mid, search for higher distance. if (isFeasible(mid, arr, n, k)) { // Change value of variable // max to mid if all elements // can be successfully placed res = Math.max(res, mid); left = mid + 1; } // If not possible to place k // elements, search for lower // distance else right = mid; } return res; } let arr = [ 1, 2, 8, 4, 9 ]; let n = arr.length; let k = 3; document.write(largestMinDist(arr, n, k)); </script>",
"e": 16901,
"s": 14170,
"text": null
},
{
"code": null,
"e": 16903,
"s": 16901,
"text": "3"
},
{
"code": null,
"e": 16961,
"s": 16903,
"text": "Time Complexity : O(nlog n) , where n is length of array."
},
{
"code": null,
"e": 16983,
"s": 16961,
"text": "Space Compeity : O(1)"
},
{
"code": null,
"e": 17405,
"s": 16983,
"text": "This article is contributed by Raghav Jajodia. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 17412,
"s": 17405,
"text": "Sam007"
},
{
"code": null,
"e": 17418,
"s": 17412,
"text": "jit_t"
},
{
"code": null,
"e": 17430,
"s": 17418,
"text": "sonamchawla"
},
{
"code": null,
"e": 17444,
"s": 17430,
"text": "Sanjit_Prasad"
},
{
"code": null,
"e": 17455,
"s": 17444,
"text": "naklicoder"
},
{
"code": null,
"e": 17468,
"s": 17455,
"text": "AakashYadav4"
},
{
"code": null,
"e": 17475,
"s": 17468,
"text": "achy97"
},
{
"code": null,
"e": 17484,
"s": 17475,
"text": "mukesh07"
},
{
"code": null,
"e": 17502,
"s": 17484,
"text": "gulshankumarar231"
},
{
"code": null,
"e": 17514,
"s": 17502,
"text": "ayush123ngp"
},
{
"code": null,
"e": 17529,
"s": 17514,
"text": "bhiruddigvijay"
},
{
"code": null,
"e": 17542,
"s": 17529,
"text": "iramkhalid24"
},
{
"code": null,
"e": 17555,
"s": 17542,
"text": "simmytarika5"
},
{
"code": null,
"e": 17569,
"s": 17555,
"text": "Binary Search"
},
{
"code": null,
"e": 17576,
"s": 17569,
"text": "Arrays"
},
{
"code": null,
"e": 17595,
"s": 17576,
"text": "Divide and Conquer"
},
{
"code": null,
"e": 17602,
"s": 17595,
"text": "Arrays"
},
{
"code": null,
"e": 17621,
"s": 17602,
"text": "Divide and Conquer"
},
{
"code": null,
"e": 17635,
"s": 17621,
"text": "Binary Search"
},
{
"code": null,
"e": 17733,
"s": 17635,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 17801,
"s": 17733,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 17845,
"s": 17801,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 17877,
"s": 17845,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 17925,
"s": 17877,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 17939,
"s": 17925,
"text": "Linear Search"
},
{
"code": null,
"e": 17950,
"s": 17939,
"text": "Merge Sort"
},
{
"code": null,
"e": 17960,
"s": 17950,
"text": "QuickSort"
},
{
"code": null,
"e": 17974,
"s": 17960,
"text": "Binary Search"
},
{
"code": null,
"e": 18042,
"s": 17974,
"text": "Maximum and minimum of an array using minimum number of comparisons"
}
] |
Find the ln(X) and log10X with the help of expansion
|
11 May, 2021
Given a positive number x, the task is to find the natural log (ln) and log to the base 10 (log10) of this number with the help of expansion.
Example:
Input: x = 5
Output: ln 5.000 = 1.609
log10 5.000 = 0.699
Input: x = 10
Output: ln 10.000 = 2.303
log10 10.000 = 1.000
Approach:
The expansion of natural logarithm of x (ln x) is:
Therefore this series can be summed up as:
Hence a function can be made to evaluate the nth term of the sequence for 1 ≤ x ≤ n
Now to calculate log10 x, below formula can be used:
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// CPP code to Find the ln x and// log<sub>10</sub> x with the help of expansion #include <cmath>#include <iomanip>#include <iostream> using namespace std; // Function to calculate ln x using expansiondouble calculateLnx(double n){ double num, mul, cal, sum = 0; num = (n - 1) / (n + 1); // terminating value of the loop // can be increased to improve the precision for (int i = 1; i <= 1000; i++) { mul = (2 * i) - 1; cal = pow(num, mul); cal = cal / mul; sum = sum + cal; } sum = 2 * sum; return sum;} // Function to calculate log10 xdouble calculateLogx(double lnx){ return (lnx / 2.303);} // Driver Codeint main(){ double lnx, logx, n = 5; lnx = calculateLnx(n); logx = calculateLogx(lnx); // setprecision(3) is used to display // the output up to 3 decimal places cout << fixed << setprecision(3) << "ln " << n << " = " << lnx << endl; cout << fixed << setprecision(3) << "log10 " << n << " = " << logx << endl;}
// Java code to Find the ln x and// log<sub>10</sub> x with the help of expansionimport java.io.*; class GFG{ // Function to calculate ln x using expansionstatic double calculateLnx(double n){ double num, mul, cal, sum = 0; num = (n - 1) / (n + 1); // terminating value of the loop // can be increased to improve the precision for (int i = 1; i <= 1000; i++) { mul = (2 * i) - 1; cal = Math.pow(num, mul); cal = cal / mul; sum = sum + cal; } sum = 2 * sum; return sum;} // Function to calculate log10 xstatic double calculateLogx(double lnx){ return (lnx / 2.303);} // Driver Codepublic static void main (String[] args){ double lnx, logx, n = 5; lnx = calculateLnx(n); logx = calculateLogx(lnx); // setprecision(3) is used to display // the output up to 3 decimal places System.out.println ("ln " + n + " = " + lnx ); System.out.println ("log10 " + n + " = "+ logx );}} // This code is contributed by ajit
# Python 3 code to Find the ln x and# log<sub>10</sub> x with the help of expansion# Function to calculate ln x using expansionfrom math import powdef calculateLnx(n): sum = 0 num = (n - 1) / (n + 1) # terminating value of the loop # can be increased to improve the precision for i in range(1, 1001, 1): mul = (2 * i) - 1 cal = pow(num, mul) cal = cal / mul sum = sum + cal sum = 2 * sum return sum # Function to calculate log10 xdef calculateLogx(lnx): return (lnx / 2.303) # Driver Codeif __name__ == '__main__': n = 5 lnx = calculateLnx(n) logx = calculateLogx(lnx) # setprecision(3) is used to display # the output up to 3 decimal places print("ln", "{0:.3f}".format(n), "=", "{0:.3f}".format(lnx)) print("log10", "{0:.3f}".format(n), "=", "{0:.3f}".format(logx)) # This code is contributed by# Surendra_Gangwar
// C# code to Find the ln x and// log<sub>10</sub> x with the help of expansionusing System; class GFG{ // Function to calculate ln x using expansionstatic double calculateLnx(double n){ double num, mul, cal, sum = 0; num = (n - 1) / (n + 1); // terminating value of the loop // can be increased to improve the precision for (int i = 1; i <= 1000; i++) { mul = (2 * i) - 1; cal = Math.Pow(num, mul); cal = cal / mul; sum = sum + cal; } sum = 2 * sum; return sum;} // Function to calculate log10 xstatic double calculateLogx(double lnx){ return (lnx / 2.303);} // Driver Codepublic static void Main (String[] args){ double lnx, logx, n = 5; lnx = calculateLnx(n); logx = calculateLogx(lnx); // setprecision(3) is used to display // the output up to 3 decimal places Console.WriteLine("ln " + n + " = " + lnx ); Console.WriteLine("log10 " + n + " = "+ logx );}} // This code is contributed by Princi Singh
<script> // Javascript code to Find the ln x and// log<sub>10</sub> x with the help of expansion // Function to calculate ln x using expansionfunction calculateLnx(n){ let num, mul, cal, sum = 0; num = (n - 1) / (n + 1); // Terminating value of the loop // can be increased to improve the precision for(let i = 1; i <= 1000; i++) { mul = (2 * i) - 1; cal = Math.pow(num, mul); cal = cal / mul; sum = sum + cal; } sum = 2 * sum; return sum;} // Function to calculate log10 xfunction calculateLogx(lnx){ return (lnx / 2.303);} // Driver Codelet lnx, logx, n = 5;lnx = calculateLnx(n);logx = calculateLogx(lnx); // setprecision(3) is used to display// the output up to 3 decimal placesdocument.write("ln " + n + " = " + lnx + "<br>");document.write("log10 " + n + " = "+ logx + "<br>"); // This code is contributed by souravmahato348 </script>
ln 5.000 = 1.609
log10 5.000 = 0.699
SURENDRA_GANGWAR
jit_t
princi singh
souravmahato348
series
Mathematical
Mathematical
series
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n11 May, 2021"
},
{
"code": null,
"e": 196,
"s": 54,
"text": "Given a positive number x, the task is to find the natural log (ln) and log to the base 10 (log10) of this number with the help of expansion."
},
{
"code": null,
"e": 207,
"s": 196,
"text": "Example: "
},
{
"code": null,
"e": 343,
"s": 207,
"text": "Input: x = 5\nOutput: ln 5.000 = 1.609\n log10 5.000 = 0.699\n\nInput: x = 10\nOutput: ln 10.000 = 2.303\n log10 10.000 = 1.000"
},
{
"code": null,
"e": 355,
"s": 343,
"text": "Approach: "
},
{
"code": null,
"e": 407,
"s": 355,
"text": "The expansion of natural logarithm of x (ln x) is: "
},
{
"code": null,
"e": 452,
"s": 407,
"text": "Therefore this series can be summed up as: "
},
{
"code": null,
"e": 537,
"s": 452,
"text": "Hence a function can be made to evaluate the nth term of the sequence for 1 ≤ x ≤ n "
},
{
"code": null,
"e": 592,
"s": 537,
"text": "Now to calculate log10 x, below formula can be used: "
},
{
"code": null,
"e": 644,
"s": 592,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 648,
"s": 644,
"text": "C++"
},
{
"code": null,
"e": 653,
"s": 648,
"text": "Java"
},
{
"code": null,
"e": 661,
"s": 653,
"text": "Python3"
},
{
"code": null,
"e": 664,
"s": 661,
"text": "C#"
},
{
"code": null,
"e": 675,
"s": 664,
"text": "Javascript"
},
{
"code": "// CPP code to Find the ln x and// log<sub>10</sub> x with the help of expansion #include <cmath>#include <iomanip>#include <iostream> using namespace std; // Function to calculate ln x using expansiondouble calculateLnx(double n){ double num, mul, cal, sum = 0; num = (n - 1) / (n + 1); // terminating value of the loop // can be increased to improve the precision for (int i = 1; i <= 1000; i++) { mul = (2 * i) - 1; cal = pow(num, mul); cal = cal / mul; sum = sum + cal; } sum = 2 * sum; return sum;} // Function to calculate log10 xdouble calculateLogx(double lnx){ return (lnx / 2.303);} // Driver Codeint main(){ double lnx, logx, n = 5; lnx = calculateLnx(n); logx = calculateLogx(lnx); // setprecision(3) is used to display // the output up to 3 decimal places cout << fixed << setprecision(3) << \"ln \" << n << \" = \" << lnx << endl; cout << fixed << setprecision(3) << \"log10 \" << n << \" = \" << logx << endl;}",
"e": 1706,
"s": 675,
"text": null
},
{
"code": "// Java code to Find the ln x and// log<sub>10</sub> x with the help of expansionimport java.io.*; class GFG{ // Function to calculate ln x using expansionstatic double calculateLnx(double n){ double num, mul, cal, sum = 0; num = (n - 1) / (n + 1); // terminating value of the loop // can be increased to improve the precision for (int i = 1; i <= 1000; i++) { mul = (2 * i) - 1; cal = Math.pow(num, mul); cal = cal / mul; sum = sum + cal; } sum = 2 * sum; return sum;} // Function to calculate log10 xstatic double calculateLogx(double lnx){ return (lnx / 2.303);} // Driver Codepublic static void main (String[] args){ double lnx, logx, n = 5; lnx = calculateLnx(n); logx = calculateLogx(lnx); // setprecision(3) is used to display // the output up to 3 decimal places System.out.println (\"ln \" + n + \" = \" + lnx ); System.out.println (\"log10 \" + n + \" = \"+ logx );}} // This code is contributed by ajit",
"e": 2706,
"s": 1706,
"text": null
},
{
"code": "# Python 3 code to Find the ln x and# log<sub>10</sub> x with the help of expansion# Function to calculate ln x using expansionfrom math import powdef calculateLnx(n): sum = 0 num = (n - 1) / (n + 1) # terminating value of the loop # can be increased to improve the precision for i in range(1, 1001, 1): mul = (2 * i) - 1 cal = pow(num, mul) cal = cal / mul sum = sum + cal sum = 2 * sum return sum # Function to calculate log10 xdef calculateLogx(lnx): return (lnx / 2.303) # Driver Codeif __name__ == '__main__': n = 5 lnx = calculateLnx(n) logx = calculateLogx(lnx) # setprecision(3) is used to display # the output up to 3 decimal places print(\"ln\", \"{0:.3f}\".format(n), \"=\", \"{0:.3f}\".format(lnx)) print(\"log10\", \"{0:.3f}\".format(n), \"=\", \"{0:.3f}\".format(logx)) # This code is contributed by# Surendra_Gangwar",
"e": 3626,
"s": 2706,
"text": null
},
{
"code": "// C# code to Find the ln x and// log<sub>10</sub> x with the help of expansionusing System; class GFG{ // Function to calculate ln x using expansionstatic double calculateLnx(double n){ double num, mul, cal, sum = 0; num = (n - 1) / (n + 1); // terminating value of the loop // can be increased to improve the precision for (int i = 1; i <= 1000; i++) { mul = (2 * i) - 1; cal = Math.Pow(num, mul); cal = cal / mul; sum = sum + cal; } sum = 2 * sum; return sum;} // Function to calculate log10 xstatic double calculateLogx(double lnx){ return (lnx / 2.303);} // Driver Codepublic static void Main (String[] args){ double lnx, logx, n = 5; lnx = calculateLnx(n); logx = calculateLogx(lnx); // setprecision(3) is used to display // the output up to 3 decimal places Console.WriteLine(\"ln \" + n + \" = \" + lnx ); Console.WriteLine(\"log10 \" + n + \" = \"+ logx );}} // This code is contributed by Princi Singh",
"e": 4628,
"s": 3626,
"text": null
},
{
"code": "<script> // Javascript code to Find the ln x and// log<sub>10</sub> x with the help of expansion // Function to calculate ln x using expansionfunction calculateLnx(n){ let num, mul, cal, sum = 0; num = (n - 1) / (n + 1); // Terminating value of the loop // can be increased to improve the precision for(let i = 1; i <= 1000; i++) { mul = (2 * i) - 1; cal = Math.pow(num, mul); cal = cal / mul; sum = sum + cal; } sum = 2 * sum; return sum;} // Function to calculate log10 xfunction calculateLogx(lnx){ return (lnx / 2.303);} // Driver Codelet lnx, logx, n = 5;lnx = calculateLnx(n);logx = calculateLogx(lnx); // setprecision(3) is used to display// the output up to 3 decimal placesdocument.write(\"ln \" + n + \" = \" + lnx + \"<br>\");document.write(\"log10 \" + n + \" = \"+ logx + \"<br>\"); // This code is contributed by souravmahato348 </script>",
"e": 5528,
"s": 4628,
"text": null
},
{
"code": null,
"e": 5565,
"s": 5528,
"text": "ln 5.000 = 1.609\nlog10 5.000 = 0.699"
},
{
"code": null,
"e": 5584,
"s": 5567,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 5590,
"s": 5584,
"text": "jit_t"
},
{
"code": null,
"e": 5603,
"s": 5590,
"text": "princi singh"
},
{
"code": null,
"e": 5619,
"s": 5603,
"text": "souravmahato348"
},
{
"code": null,
"e": 5626,
"s": 5619,
"text": "series"
},
{
"code": null,
"e": 5639,
"s": 5626,
"text": "Mathematical"
},
{
"code": null,
"e": 5652,
"s": 5639,
"text": "Mathematical"
},
{
"code": null,
"e": 5659,
"s": 5652,
"text": "series"
}
] |
Image Processing in Java – Read and Write
|
14 Nov, 2021
Java implements a particular type of object called a BufferedImage for images in Java. A BufferedImage can be read from several distinct image types (i.e., BMP, HEIC, etc.). Not all of these are backed by ImageIO itself, but there are plugins to extend ImageIO and other libraries such as Apache Imaging and JDeli.
In Java itself, all the complexity of various image types is hidden, and we only work on BufferedImage. Java provides immediate access to the image pixels and color information and allows conversions and image processing.
1. java.io.File: To read and write an image file, we must import the File class. This class represents file and directory path names in general.
2. java.io.IOException: To handle errors, we use the IOException class.
3. java.awt.image.BufferedImage: To hold the image, we create the BufferedImage object; we use BufferedImage class. This object is used to store an image in RAM.
4. javax.imageio.ImageIO: To perform the image read-write operation, we will import the ImageIO class. This class has static methods to read and write an image.
Java
// Java program to demonstrate read and write of image import java.awt.image.BufferedImage;import java.io.File;import java.io.IOException;import javax.imageio.ImageIO; public class MyImage { public static void main(String args[]) throws IOException { // width of the image int width = 963; // height of the image int height = 640; // For storing image in RAM BufferedImage image = null; // READ IMAGE try { File input_file = new File( "C:/Users/hp/Desktop/Image Processing in Java/gfg-logo.png"); // image file path create an object of // BufferedImage type and pass as parameter the // width, height and image int // type. TYPE_INT_ARGB means that we are // representing the Alpha , Red, Green and Blue // component of the image pixel using 8 bit // integer value. image = new BufferedImage( width, height, BufferedImage.TYPE_INT_ARGB); // Reading input file image = ImageIO.read(input_file); System.out.println("Reading complete."); } catch (IOException e) { System.out.println("Error: " + e); } // WRITE IMAGE try { // Output file path File output_file = new File( "C:/Users/hp/Desktop/Image Processing in Java/gfg.png"); // Writing to file taking type and path as ImageIO.write(image, "png", output_file); System.out.println("Writing complete."); } catch (IOException e) { System.out.println("Error: " + e); } } // main() ends here} // class ends here
Note: This code will not run on online IDE as it needs an image on disk.
This article is contributed by Pratik Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
nishkarshgandhi
Image-Processing
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Stream In Java
Collections in Java
Singleton Class in Java
Multidimensional Arrays in Java
Set in Java
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n14 Nov, 2021"
},
{
"code": null,
"e": 369,
"s": 54,
"text": "Java implements a particular type of object called a BufferedImage for images in Java. A BufferedImage can be read from several distinct image types (i.e., BMP, HEIC, etc.). Not all of these are backed by ImageIO itself, but there are plugins to extend ImageIO and other libraries such as Apache Imaging and JDeli."
},
{
"code": null,
"e": 591,
"s": 369,
"text": "In Java itself, all the complexity of various image types is hidden, and we only work on BufferedImage. Java provides immediate access to the image pixels and color information and allows conversions and image processing."
},
{
"code": null,
"e": 736,
"s": 591,
"text": "1. java.io.File: To read and write an image file, we must import the File class. This class represents file and directory path names in general."
},
{
"code": null,
"e": 808,
"s": 736,
"text": "2. java.io.IOException: To handle errors, we use the IOException class."
},
{
"code": null,
"e": 970,
"s": 808,
"text": "3. java.awt.image.BufferedImage: To hold the image, we create the BufferedImage object; we use BufferedImage class. This object is used to store an image in RAM."
},
{
"code": null,
"e": 1131,
"s": 970,
"text": "4. javax.imageio.ImageIO: To perform the image read-write operation, we will import the ImageIO class. This class has static methods to read and write an image."
},
{
"code": null,
"e": 1136,
"s": 1131,
"text": "Java"
},
{
"code": "// Java program to demonstrate read and write of image import java.awt.image.BufferedImage;import java.io.File;import java.io.IOException;import javax.imageio.ImageIO; public class MyImage { public static void main(String args[]) throws IOException { // width of the image int width = 963; // height of the image int height = 640; // For storing image in RAM BufferedImage image = null; // READ IMAGE try { File input_file = new File( \"C:/Users/hp/Desktop/Image Processing in Java/gfg-logo.png\"); // image file path create an object of // BufferedImage type and pass as parameter the // width, height and image int // type. TYPE_INT_ARGB means that we are // representing the Alpha , Red, Green and Blue // component of the image pixel using 8 bit // integer value. image = new BufferedImage( width, height, BufferedImage.TYPE_INT_ARGB); // Reading input file image = ImageIO.read(input_file); System.out.println(\"Reading complete.\"); } catch (IOException e) { System.out.println(\"Error: \" + e); } // WRITE IMAGE try { // Output file path File output_file = new File( \"C:/Users/hp/Desktop/Image Processing in Java/gfg.png\"); // Writing to file taking type and path as ImageIO.write(image, \"png\", output_file); System.out.println(\"Writing complete.\"); } catch (IOException e) { System.out.println(\"Error: \" + e); } } // main() ends here} // class ends here",
"e": 2897,
"s": 1136,
"text": null
},
{
"code": null,
"e": 2970,
"s": 2897,
"text": "Note: This code will not run on online IDE as it needs an image on disk."
},
{
"code": null,
"e": 3393,
"s": 2970,
"text": "This article is contributed by Pratik Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 3409,
"s": 3393,
"text": "nishkarshgandhi"
},
{
"code": null,
"e": 3426,
"s": 3409,
"text": "Image-Processing"
},
{
"code": null,
"e": 3431,
"s": 3426,
"text": "Java"
},
{
"code": null,
"e": 3436,
"s": 3431,
"text": "Java"
},
{
"code": null,
"e": 3534,
"s": 3436,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3585,
"s": 3534,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 3616,
"s": 3585,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 3635,
"s": 3616,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 3665,
"s": 3635,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 3683,
"s": 3665,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 3698,
"s": 3683,
"text": "Stream In Java"
},
{
"code": null,
"e": 3718,
"s": 3698,
"text": "Collections in Java"
},
{
"code": null,
"e": 3742,
"s": 3718,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 3774,
"s": 3742,
"text": "Multidimensional Arrays in Java"
}
] |
How to Calculate Deciles in Excel?
|
30 Nov, 2021
Decile is a statistical method to split data into 10 equal parts. Each represents 1/10 of the Population or Sample data. It is denoted D1, D2, ... D9. Fifth deciles D5 are equal to the median. It determines 10%,20%, ... 90%.
Here,
n: Number of data points in the population or sample (In the below eg. n = 25)
Find the position of Deciles
D1 = 1*((25+1)/10) = 1*(26/10) = 1*(2.6) = 2.6th value [data between 2 and 3 ]
D2 = 2*((25+1)/10) = 2*(26/10) = 2*(2.6) = 5.2nd value [data between 5 and 6 ]
Follow the below steps to calculate the Deciles in Excel:
Step 1: Sort the data in ascending order.
Step 2: Compute n (Number of data points); in the above example n is 25, which is placed in cell “F1”
Step 3: Write Headers for decile table as below in cells E3, F3 and G3.
Step 4: Type text D1 to D9 in cells “E4 to E12” respectively
Step 5: In cells “F4 to F12” fill decile formula for the respective deciles to find the positions
D1 =1*($F$1+1)/10
D2 =2*($F$1+1)/10
D3 =3*($F$1+1)/10
D4 =4*($F$1+1)/10
D5 =5*($F$1+1)/10
D6 =6*($F$1+1)/10
D7 =7*($F$1+1)/10
D8 =8*($F$1+1)/10
D9 =9*($F$1+1)/10
Step 6: Decile value calculation for the respective positions
For D1 2.6th Position
find 2nd observation – 12
find 3rd observation – 13
2nd observation + (3rd observation-2nd observation) * 0.6
12 + (13-12) *0.6 = 12.6
Write below formula in cells G4 to G12 for D1 to D9
=B3+(B4-B3)*0.6
=B6+(B7-B6)*0.2
=B7+(B8-B7)*0.8
=B11+(B12-B11)*0.4
=B14+(B14-B14)*0
=B16+(B17-B16)*0.6
=B19+(B20-B19)*0.2
=B21+(B22-B21)*0.8
=B24+(B25-B24)*0.4
Output:
Excel-functions
Picked
Excel
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Delete Blank Columns in Excel?
How to Normalize Data in Excel?
How to Get Length of Array in Excel VBA?
How to Find the Last Used Row and Column in Excel VBA?
How to Use Solver in Excel?
How to make a 3 Axis Graph using Excel?
Macros in Excel
Introduction to Excel Spreadsheet
How to Show Percentages in Stacked Column Chart in Excel?
How to Create a Macro in Excel?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Nov, 2021"
},
{
"code": null,
"e": 256,
"s": 28,
"text": "Decile is a statistical method to split data into 10 equal parts. Each represents 1/10 of the Population or Sample data. It is denoted D1, D2, ... D9. Fifth deciles D5 are equal to the median. It determines 10%,20%, ... 90%."
},
{
"code": null,
"e": 262,
"s": 256,
"text": "Here,"
},
{
"code": null,
"e": 341,
"s": 262,
"text": "n: Number of data points in the population or sample (In the below eg. n = 25)"
},
{
"code": null,
"e": 370,
"s": 341,
"text": "Find the position of Deciles"
},
{
"code": null,
"e": 528,
"s": 370,
"text": "D1 = 1*((25+1)/10) = 1*(26/10) = 1*(2.6) = 2.6th value [data between 2 and 3 ]\nD2 = 2*((25+1)/10) = 2*(26/10) = 2*(2.6) = 5.2nd value [data between 5 and 6 ]"
},
{
"code": null,
"e": 586,
"s": 528,
"text": "Follow the below steps to calculate the Deciles in Excel:"
},
{
"code": null,
"e": 628,
"s": 586,
"text": "Step 1: Sort the data in ascending order."
},
{
"code": null,
"e": 730,
"s": 628,
"text": "Step 2: Compute n (Number of data points); in the above example n is 25, which is placed in cell “F1”"
},
{
"code": null,
"e": 802,
"s": 730,
"text": "Step 3: Write Headers for decile table as below in cells E3, F3 and G3."
},
{
"code": null,
"e": 863,
"s": 802,
"text": "Step 4: Type text D1 to D9 in cells “E4 to E12” respectively"
},
{
"code": null,
"e": 961,
"s": 863,
"text": "Step 5: In cells “F4 to F12” fill decile formula for the respective deciles to find the positions"
},
{
"code": null,
"e": 1123,
"s": 961,
"text": "D1 =1*($F$1+1)/10\nD2 =2*($F$1+1)/10\nD3 =3*($F$1+1)/10\nD4 =4*($F$1+1)/10\nD5 =5*($F$1+1)/10\nD6 =6*($F$1+1)/10\nD7 =7*($F$1+1)/10\nD8 =8*($F$1+1)/10\nD9 =9*($F$1+1)/10"
},
{
"code": null,
"e": 1185,
"s": 1123,
"text": "Step 6: Decile value calculation for the respective positions"
},
{
"code": null,
"e": 1359,
"s": 1185,
"text": "For D1 2.6th Position \n find 2nd observation – 12\n find 3rd observation – 13\n 2nd observation + (3rd observation-2nd observation) * 0.6\n 12 + (13-12) *0.6 = 12.6"
},
{
"code": null,
"e": 1411,
"s": 1359,
"text": "Write below formula in cells G4 to G12 for D1 to D9"
},
{
"code": null,
"e": 1571,
"s": 1411,
"text": "=B3+(B4-B3)*0.6\n=B6+(B7-B6)*0.2\n=B7+(B8-B7)*0.8\n=B11+(B12-B11)*0.4\n=B14+(B14-B14)*0\n=B16+(B17-B16)*0.6\n=B19+(B20-B19)*0.2\n=B21+(B22-B21)*0.8\n=B24+(B25-B24)*0.4"
},
{
"code": null,
"e": 1579,
"s": 1571,
"text": "Output:"
},
{
"code": null,
"e": 1595,
"s": 1579,
"text": "Excel-functions"
},
{
"code": null,
"e": 1602,
"s": 1595,
"text": "Picked"
},
{
"code": null,
"e": 1608,
"s": 1602,
"text": "Excel"
},
{
"code": null,
"e": 1706,
"s": 1608,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1744,
"s": 1706,
"text": "How to Delete Blank Columns in Excel?"
},
{
"code": null,
"e": 1776,
"s": 1744,
"text": "How to Normalize Data in Excel?"
},
{
"code": null,
"e": 1817,
"s": 1776,
"text": "How to Get Length of Array in Excel VBA?"
},
{
"code": null,
"e": 1872,
"s": 1817,
"text": "How to Find the Last Used Row and Column in Excel VBA?"
},
{
"code": null,
"e": 1900,
"s": 1872,
"text": "How to Use Solver in Excel?"
},
{
"code": null,
"e": 1940,
"s": 1900,
"text": "How to make a 3 Axis Graph using Excel?"
},
{
"code": null,
"e": 1956,
"s": 1940,
"text": "Macros in Excel"
},
{
"code": null,
"e": 1990,
"s": 1956,
"text": "Introduction to Excel Spreadsheet"
},
{
"code": null,
"e": 2048,
"s": 1990,
"text": "How to Show Percentages in Stacked Column Chart in Excel?"
}
] |
Exit status of a child process in Linux
|
25 Aug, 2021
It is known that fork() system call is used to create a new process which becomes child of the caller process. Upon exit, the child leaves an exit status that should be returned to the parent. So, when the child finishes it becomes a zombie.Whenever the child exits or stops, the parent is sent a SIGCHLD signal. The parent can use the system call wait() or waitpid() along with the macros WIFEXITED and WEXITSTATUS with it to learn about the status of its stopped child.(*)wait() system call : It suspends execution of the calling process until one of its children terminates. Syntax of wait() system call:
pid_t wait(int *status);
(*)The waitpid() system call : It suspends execution of the calling process until a child specified by pid argument has changed state. Syntax of waitpid() system call :
pid_t waitpid(pid_t pid, int *status, int options)
Note: By default, waitpid() waits only for terminated children, but this behavior is modifiable via the options argument such as WIFEXITED, WEXITSTATUS etc.The value of pid can be :
Less than -1 : Meaning wait for any child process whose process group ID is equal to the absolute value of pid.Equal to -1 : Meaning wait for any child process.Equal to 0 : Meaning wait for any child process whose process group ID is equal to that of the calling process.Greater than 0 : Meaning wait for the child whose process ID is equal to the value of pid.
Less than -1 : Meaning wait for any child process whose process group ID is equal to the absolute value of pid.
Equal to -1 : Meaning wait for any child process.
Equal to 0 : Meaning wait for any child process whose process group ID is equal to that of the calling process.
Greater than 0 : Meaning wait for the child whose process ID is equal to the value of pid.
WIFEXITED and WEXITSTATUS are two of the options which can be used to know the exit status of the child. WIFEXITED(status) : returns true if the child terminated normally.WEXITSTATUS(status) : returns the exit status of the child. This macro should be employed only if WIFEXITED returned true.Below is a C implementation in which child uses execl() function but the path specified to execl() is undefined. Let us see what is the exit status value of the child that parent gets.
C
// C code to find the exit status of child process#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <sys/types.h>#include <sys/wait.h> // Driver codeint main(void){ pid_t pid = fork(); if ( pid == 0 ) { /* The pathname of the file passed to execl() is not defined */ execl("/bin/sh", "bin/sh", "-c", "./nopath", "NULL"); } int status; waitpid(pid, &status, 0); if ( WIFEXITED(status) ) { int exit_status = WEXITSTATUS(status); printf("Exit status of the child was %d\n", exit_status); } return 0;}
Output:
Note : Above code may not work with online compiler as fork() is disabled.Here the exit status is 127 which indicates that there is some problem with path or there is a typo.Few exit status codes are listed below for extra information :
1 : Miscellaneous errors, such as “divide by zero” and other impermissible operations.
2 : Missing keyword or command, or permission problem.
126 : Permission problem or command is not an executable
128 : invalid argument to exit.
Note : The C standard does not define the meaning of return codes. Rules for the use of return codes vary on different platforms.
kk773572498
Processes & Threads
system-programming
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
tar command in Linux with examples
Compiling with g++
'crontab' in Linux with Examples
UDP Server-Client implementation in C
touch command in Linux with Examples
nohup Command in Linux with Examples
echo command in Linux with Examples
Cat command in Linux with examples
Conditional Statements | Shell Script
diff command in Linux with examples
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n25 Aug, 2021"
},
{
"code": null,
"e": 663,
"s": 54,
"text": "It is known that fork() system call is used to create a new process which becomes child of the caller process. Upon exit, the child leaves an exit status that should be returned to the parent. So, when the child finishes it becomes a zombie.Whenever the child exits or stops, the parent is sent a SIGCHLD signal. The parent can use the system call wait() or waitpid() along with the macros WIFEXITED and WEXITSTATUS with it to learn about the status of its stopped child.(*)wait() system call : It suspends execution of the calling process until one of its children terminates. Syntax of wait() system call: "
},
{
"code": null,
"e": 688,
"s": 663,
"text": "pid_t wait(int *status);"
},
{
"code": null,
"e": 858,
"s": 688,
"text": "(*)The waitpid() system call : It suspends execution of the calling process until a child specified by pid argument has changed state. Syntax of waitpid() system call : "
},
{
"code": null,
"e": 909,
"s": 858,
"text": "pid_t waitpid(pid_t pid, int *status, int options)"
},
{
"code": null,
"e": 1093,
"s": 909,
"text": "Note: By default, waitpid() waits only for terminated children, but this behavior is modifiable via the options argument such as WIFEXITED, WEXITSTATUS etc.The value of pid can be : "
},
{
"code": null,
"e": 1455,
"s": 1093,
"text": "Less than -1 : Meaning wait for any child process whose process group ID is equal to the absolute value of pid.Equal to -1 : Meaning wait for any child process.Equal to 0 : Meaning wait for any child process whose process group ID is equal to that of the calling process.Greater than 0 : Meaning wait for the child whose process ID is equal to the value of pid."
},
{
"code": null,
"e": 1567,
"s": 1455,
"text": "Less than -1 : Meaning wait for any child process whose process group ID is equal to the absolute value of pid."
},
{
"code": null,
"e": 1617,
"s": 1567,
"text": "Equal to -1 : Meaning wait for any child process."
},
{
"code": null,
"e": 1729,
"s": 1617,
"text": "Equal to 0 : Meaning wait for any child process whose process group ID is equal to that of the calling process."
},
{
"code": null,
"e": 1820,
"s": 1729,
"text": "Greater than 0 : Meaning wait for the child whose process ID is equal to the value of pid."
},
{
"code": null,
"e": 2298,
"s": 1820,
"text": "WIFEXITED and WEXITSTATUS are two of the options which can be used to know the exit status of the child. WIFEXITED(status) : returns true if the child terminated normally.WEXITSTATUS(status) : returns the exit status of the child. This macro should be employed only if WIFEXITED returned true.Below is a C implementation in which child uses execl() function but the path specified to execl() is undefined. Let us see what is the exit status value of the child that parent gets."
},
{
"code": null,
"e": 2300,
"s": 2298,
"text": "C"
},
{
"code": "// C code to find the exit status of child process#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <sys/types.h>#include <sys/wait.h> // Driver codeint main(void){ pid_t pid = fork(); if ( pid == 0 ) { /* The pathname of the file passed to execl() is not defined */ execl(\"/bin/sh\", \"bin/sh\", \"-c\", \"./nopath\", \"NULL\"); } int status; waitpid(pid, &status, 0); if ( WIFEXITED(status) ) { int exit_status = WEXITSTATUS(status); printf(\"Exit status of the child was %d\\n\", exit_status); } return 0;}",
"e": 2935,
"s": 2300,
"text": null
},
{
"code": null,
"e": 2945,
"s": 2935,
"text": "Output: "
},
{
"code": null,
"e": 3186,
"s": 2947,
"text": "Note : Above code may not work with online compiler as fork() is disabled.Here the exit status is 127 which indicates that there is some problem with path or there is a typo.Few exit status codes are listed below for extra information : "
},
{
"code": null,
"e": 3273,
"s": 3186,
"text": "1 : Miscellaneous errors, such as “divide by zero” and other impermissible operations."
},
{
"code": null,
"e": 3328,
"s": 3273,
"text": "2 : Missing keyword or command, or permission problem."
},
{
"code": null,
"e": 3385,
"s": 3328,
"text": "126 : Permission problem or command is not an executable"
},
{
"code": null,
"e": 3417,
"s": 3385,
"text": "128 : invalid argument to exit."
},
{
"code": null,
"e": 3548,
"s": 3417,
"text": "Note : The C standard does not define the meaning of return codes. Rules for the use of return codes vary on different platforms. "
},
{
"code": null,
"e": 3560,
"s": 3548,
"text": "kk773572498"
},
{
"code": null,
"e": 3580,
"s": 3560,
"text": "Processes & Threads"
},
{
"code": null,
"e": 3599,
"s": 3580,
"text": "system-programming"
},
{
"code": null,
"e": 3610,
"s": 3599,
"text": "Linux-Unix"
},
{
"code": null,
"e": 3708,
"s": 3610,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3743,
"s": 3708,
"text": "tar command in Linux with examples"
},
{
"code": null,
"e": 3762,
"s": 3743,
"text": "Compiling with g++"
},
{
"code": null,
"e": 3795,
"s": 3762,
"text": "'crontab' in Linux with Examples"
},
{
"code": null,
"e": 3833,
"s": 3795,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 3870,
"s": 3833,
"text": "touch command in Linux with Examples"
},
{
"code": null,
"e": 3907,
"s": 3870,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 3943,
"s": 3907,
"text": "echo command in Linux with Examples"
},
{
"code": null,
"e": 3978,
"s": 3943,
"text": "Cat command in Linux with examples"
},
{
"code": null,
"e": 4016,
"s": 3978,
"text": "Conditional Statements | Shell Script"
}
] |
How to use financial functions. A comparison between SAS and Python. | by Valentin Nordstroem | 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.
Most people use Excel to make financial calculations. But both SAS and Python are very capable of helping in finance too. One of the benefits in using SAS and Python is the structured automation.
In this article, I will show you some of the most common formulas used in finance:
pmt, Calculating the monthly payment of an loan
fv, Computes the future value of an investment
pv, Computes the present value of an investment
nper, Computes the number of periodic payments
rate, Computes the interest rate per period of an annuity
ppmt, Computes the payment on the principal for an investment for a specified period
effect, Computes the effective annual interest rate
irr, Computes the internal rate of return for a series of cash flows
npv, Computes the net present value
Btw. There is a big error in SAS and Excel regarding the description on how to calculate net present values. I will show you the correct way to do it.
You can find financial functions in Python Numpy Library until version 1.17
import numpy as npimport pandas as pd
Check your Numpy version
print(np.__version__)1.15.3
If installed NumPy version is > 1.17, the financial function is moved from NumPy to NumPy Financial. So, you need to import the financial functions as npf instead of np in your Python program.
Import as follow:
import numpy_financial as npf
In this example, we want to calculate how much you have to pay monthly to pay back a loan of 10.000 in 5 years. The yearly interest rate is 6%, and is calculated monthly.
You can use a function called finance(). Its is a replica of the functionalities in Excel.
DATA pmt; rate = 0.06/12; nper = 5*12; pv = 10000; fv = 0; pmt = FINANCE('pmt', rate, nper, pv, fv);RUN;PROC PRINT;RUN;Using SAS Config named: defaultSAS Connection established. Subprocess id is 4412
You use the np.pmt() function to compute the monthly payment. I first create a data frame with a dictionary approach with only one record. I call it Obs and give it a value of 1. I need to create a non empty data frame, so I can assign scalars values to it.
df = pd.DataFrame({'Obs':[1]})df['rate'] = 0.06/12df['nper'] = 60df['pv'] = 10000df['fv'] = 0df['pmt'] = np.pmt(df.rate, df.nper, df.pv, df.fv)df
In this example, I refer to the columns, using dot notation instead of hard brackets. As I have mentioned before, you should be careful when using this notation, since it is the same way you refer to an attribute. Therefore, I mostly use this notatin when I use a column inside a function. I still use the df['var'] when I create the variable.
You have to pay 193.33 per month to pay back a loan of 10.000 over five years.
The next example is to find out what is left of the loan of 10.000 if you pay 200 per month over the next 60 month.
The yearly interest rate is 6% per year, and is calculated monthly.
We use the same finance function, FINANCE() as before, buut this time the missing argument is fv.
DATA fv; rate = (0.06/12); nper = 60; pmt = -200; pv = 10000; fv = FINANCE('fv', rate, nper, pmt, pv);RUN;PROC PRINT;RUN;
The result is that you have paid 465.51 more than you should.
You use the function np.fv(rate, nper, pmt, pv). Same syntax as before.
df = pd.DataFrame({'Obs':[1]})df['rate'] = 0.06/12df['nper'] = 60df['pmt'] = -200df['pv'] = 10000df['fv'] = np.fv(df.rate, df.nper, df.pmt, df.pv)df
Alternative ways in Python
I want to show you a way to do the same calculation without using a DataFrame. You can do this directly in Python. You assign the values to variables and use the variables as argument in the np.fv() function.
rate = 0.06/12nper = 60pmt= -200pv = 10000fv = np.fv(rate,nper,pmt,pv)fv465.50457647922485
Or you just type the values as an argument directly in the NumPy function.
np.fv(0.06/12,60,-200,10000)465.50457647922485
If you just have to make one calculation, that is for just one observation, the last two examples are sufficient.
In this example, we still look the loan, but this time we want to know how much we can borrow if we repay the loan with 200 per month for the next five years. The annual interest rate is 6% and is charged monthly.
We use PV to tell the finance function that we are looking for the present value.
DATA pv; rate=0.06/12; nper=12 * 5; pmt=-200; fv=0; pv=FINANCE('pv', rate, nper, pmt, fv);RUN;PROC PRINT;RUN;
The result of the calculation is that we can borrow 10.345,11.
You use the present value function np.pv() from NumPy:
df = pd.DataFrame({'Obs':[1]})df['rate'] = 0.06/12df['nper'] = 12*5df['pmt'] = -200df['fv'] = 0df['pv'] = np.pv(df.rate, df.nper, df.pmt, df.fv)df
What about the number of payments you need to make to pay back 10.000 with 200 per month?
We use the same setup as before, but this time we set the FINANCE() function to calculate nper.
DATA nper; rate=0.06/12; pmt=-200; pv=10000; fv=0; nper=FINANCE('nper', rate, pmt, pv, fv);RUN;PROC PRINT;RUN;
Again, the syntax is the same. This time we use the function np.fv():
df = pd.DataFrame({'Obs':[1]})df['rate'] = 0.06/12df['pmt'] = -200df['pv'] = 10000df['fv'] = 0df['nper'] = np.nper(df.rate, df.pmt, df.pv, df.fv)df
So we have to make 58 payments to pay back 10.000 over 5 years.
Now we want to look at the yearly interest rate when you pay back a loan of 10,000 with 60 monthly payments of 200.
The result from the FINANCE() function is the monthly interest. Therefore, you have to multiply the result with 12 to get the annual interest rate.
DATA rate; nper=60; payment=-200; pv=10000; fv=0; rate=FINANCE('rate', nper, payment, pv, fv) * 12;RUN;PROC PRINT;RUN;
So to pay back a loan of 10.000 with 200 per month, the anual interest would be 7.42%
We use the np.rate() function. But, we still need to multiply it with 12 to get the yearly result.
df = pd.DataFrame({'Obs':[1]})df['nper'] = 60df['pmt'] = -200df['pv'] = 10000df['fv'] = 0df['rate'] = np.rate(df.nper, df.pmt, df.pv, df.fv) * 12df
If you want to know how much principal you would pay each month, you can use the ppmt method.
You calculate ppmt for each period using the FINANCE() function in a do loop to get the 60 principal payments.
DATA ppmt; DO period = 1 TO 60; rate=0.06/12; nper=60; pv=10000; fv=0; ppmt=FINANCE('ppmt', rate, period, nper, pv, fv); output; end;run;proc print;run;
To create one records for the 60 months, we use range(1,61) to make a list of 60 values from 1 to 60 as the period column. For each period the np.ppmt() function is then used to calculates the principal payment.
df = pd.DataFrame()df['period'] = range(1, 61)df['rate'] = 0.06/12df['nper'] = 60df['pv'] = 10000df['fv'] = 0df['ppmt'] = np.ppmt(df.rate, df.period, df.nper, df.pv, df.fv)df
Remember that SAS count the possition of the records starting with the first record having the number 1. In Python the number of the first record is 0.
For SAS users, think about it as your age, when you were born. In you first year you were zero years old.
There are other financial calculations we can do.
The first is how to calculate the effective interest rate if you are charged monthly interest.
In SAS, the finance function can do the calculation for us.
In Python, you have to calculate it yourself and that is very simple.
I’ll show you how to use the FINANCE() function and how you can calculate it yourself.
DATA effective; rate=0.06; nper=12; effect_fin = FINANCE('effect', rate, nper); effect = (1 + rate/nper)**nper - 1;RUN;PROC PRINT;RUN;
You have to calculate the effective interest rate ourselves. I will show you how to do this in Python and in a DataFrame.
rate = 0.06nper = 12effect = (1 + rate/nper)**nper - 1print('The effective interest rate is: ', effect)The effective interest rate is: 0.06167781186449828
Notice how you can add a text in your print output!
df = pd.DataFrame({'Obs':[1]})df['rate'] = ratedf['nper'] = nperdf['effect'] = (1 + df.rate/df.nper)**df.nper - 1df
So the effective interest rate is 6.16%
There are other useful calculations you can use in finance. Internal rate of return is one of them.
You can still use the FINANCE() function. But this time the arguments are different as they are the cash flow for the investment.
In this example, you invest 40.000 and receive four payment in return. The function returns the IRR of this investment.
%%SASDATA irr; v1=-40000; v2=5000; v3=8000; v4=12000; v5=30000; r=FINANCE('irr', v1, v2, v3, v4, v5);RUN;PROC PRINT;RUN;
The internal rate of return is 10.58%
We also have a np.irr() function and the syntax is very similar to SAS. Only that you don't need to have the cash flow in separate variables.
df = pd.DataFrame()df['cashflow'] = [-40000, 5000, 8000, 12000, 30000]df['irr'] = np.irr(df['cashflow'])df
You can also do the calculation outside the DataFrame with Series as an input or directly with the cash flow numbers as input.
irr = np.irr(df['cashflow'])irr0.10582259840890207np.irr([-40000,5000,8000,12000,30000])0.10582259840890207
This is a very interesting formula. For many years the explanations of how to use this formula have been wrong in both SAS and Excel.
When you calculate a net, you have to deduct something. But that is not explained in the documentations of SAS and Microsoft. So the function is not calculating npv.
You have to add a deduction to get the right result. In Python, every thing is calculated correctly from the beginning.
You can use the FINANCE() function in calculating the Net Present Value. You use the cash flow and interest rate as input and then deduct the investment from the output.
I will also show you the formulas for calculating npv without a function.
DATA npv; rate=0.08; investment=-40000; cf1=5000; cf2=8000; cf3=12000; cf4=30000; npv = FINANCE('npv', rate, cf1, cf2, cf3, cf4) + investment; npv_formula = cf1/(1+rate)**1 + cf2/(1+rate)**2 + cf3/(1+rate)**3 + cf4/(1+rate)**4 + investment;RUN;PROC PRINT;RUN;
On the other hand, the np.npv() function takes the full list of values, both the investment and the cashflow as arguments.
df = pd.DataFrame()df['values'] = [-40000, 5000, 8000, 12000, 30000]df['rate'] = 0.08df['npv'] = np.npv(df['rate'],df['values'])df
You can also use your own formula for calculating NPV.
5000/(1+0.08)**1 + 8000/(1+0.08)**2 + 12000/(1+0.08)**3 + 30000/(1+0.08)**4 - 400003065.222668179529
This last example shows how to separate the two values, investment and cashflow. If you have the values in each list, you can add the two list's in the function as investment+cashflow
rate = 0.08investment = [-40000]cashflow = [5000, 8000, 12000, 30000]np.npv(rate,investment+cashflow)3065.2226681795255
That all I had about financial functions. In SAS you can use FINANCE() for all the calculations. In Python you use separate functions, but with very similar syntax.
I hope you are aware of the challenge in calculating net present values in SAS and Excel and that you are not including the invesment in you function. If you are, I wish you good luck telling you boss.
We all make mistake, we are humans after all.
I hope you have enjoyed the article and I look forward writing more tips about SAS and Python.
If you want to know more about how you can learn Python the way you work in SAS, go to the following link to get more details:
https://www.nordstroem.uk
Some rights reserved
|
[
{
"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": 668,
"s": 472,
"text": "Most people use Excel to make financial calculations. But both SAS and Python are very capable of helping in finance too. One of the benefits in using SAS and Python is the structured automation."
},
{
"code": null,
"e": 751,
"s": 668,
"text": "In this article, I will show you some of the most common formulas used in finance:"
},
{
"code": null,
"e": 799,
"s": 751,
"text": "pmt, Calculating the monthly payment of an loan"
},
{
"code": null,
"e": 846,
"s": 799,
"text": "fv, Computes the future value of an investment"
},
{
"code": null,
"e": 894,
"s": 846,
"text": "pv, Computes the present value of an investment"
},
{
"code": null,
"e": 941,
"s": 894,
"text": "nper, Computes the number of periodic payments"
},
{
"code": null,
"e": 999,
"s": 941,
"text": "rate, Computes the interest rate per period of an annuity"
},
{
"code": null,
"e": 1084,
"s": 999,
"text": "ppmt, Computes the payment on the principal for an investment for a specified period"
},
{
"code": null,
"e": 1136,
"s": 1084,
"text": "effect, Computes the effective annual interest rate"
},
{
"code": null,
"e": 1205,
"s": 1136,
"text": "irr, Computes the internal rate of return for a series of cash flows"
},
{
"code": null,
"e": 1241,
"s": 1205,
"text": "npv, Computes the net present value"
},
{
"code": null,
"e": 1392,
"s": 1241,
"text": "Btw. There is a big error in SAS and Excel regarding the description on how to calculate net present values. I will show you the correct way to do it."
},
{
"code": null,
"e": 1468,
"s": 1392,
"text": "You can find financial functions in Python Numpy Library until version 1.17"
},
{
"code": null,
"e": 1506,
"s": 1468,
"text": "import numpy as npimport pandas as pd"
},
{
"code": null,
"e": 1531,
"s": 1506,
"text": "Check your Numpy version"
},
{
"code": null,
"e": 1559,
"s": 1531,
"text": "print(np.__version__)1.15.3"
},
{
"code": null,
"e": 1752,
"s": 1559,
"text": "If installed NumPy version is > 1.17, the financial function is moved from NumPy to NumPy Financial. So, you need to import the financial functions as npf instead of np in your Python program."
},
{
"code": null,
"e": 1770,
"s": 1752,
"text": "Import as follow:"
},
{
"code": null,
"e": 1800,
"s": 1770,
"text": "import numpy_financial as npf"
},
{
"code": null,
"e": 1971,
"s": 1800,
"text": "In this example, we want to calculate how much you have to pay monthly to pay back a loan of 10.000 in 5 years. The yearly interest rate is 6%, and is calculated monthly."
},
{
"code": null,
"e": 2062,
"s": 1971,
"text": "You can use a function called finance(). Its is a replica of the functionalities in Excel."
},
{
"code": null,
"e": 2267,
"s": 2062,
"text": "DATA pmt; rate = 0.06/12; nper = 5*12; pv = 10000; fv = 0; pmt = FINANCE('pmt', rate, nper, pv, fv);RUN;PROC PRINT;RUN;Using SAS Config named: defaultSAS Connection established. Subprocess id is 4412"
},
{
"code": null,
"e": 2525,
"s": 2267,
"text": "You use the np.pmt() function to compute the monthly payment. I first create a data frame with a dictionary approach with only one record. I call it Obs and give it a value of 1. I need to create a non empty data frame, so I can assign scalars values to it."
},
{
"code": null,
"e": 2671,
"s": 2525,
"text": "df = pd.DataFrame({'Obs':[1]})df['rate'] = 0.06/12df['nper'] = 60df['pv'] = 10000df['fv'] = 0df['pmt'] = np.pmt(df.rate, df.nper, df.pv, df.fv)df"
},
{
"code": null,
"e": 3015,
"s": 2671,
"text": "In this example, I refer to the columns, using dot notation instead of hard brackets. As I have mentioned before, you should be careful when using this notation, since it is the same way you refer to an attribute. Therefore, I mostly use this notatin when I use a column inside a function. I still use the df['var'] when I create the variable."
},
{
"code": null,
"e": 3094,
"s": 3015,
"text": "You have to pay 193.33 per month to pay back a loan of 10.000 over five years."
},
{
"code": null,
"e": 3210,
"s": 3094,
"text": "The next example is to find out what is left of the loan of 10.000 if you pay 200 per month over the next 60 month."
},
{
"code": null,
"e": 3278,
"s": 3210,
"text": "The yearly interest rate is 6% per year, and is calculated monthly."
},
{
"code": null,
"e": 3376,
"s": 3278,
"text": "We use the same finance function, FINANCE() as before, buut this time the missing argument is fv."
},
{
"code": null,
"e": 3503,
"s": 3376,
"text": "DATA fv; rate = (0.06/12); nper = 60; pmt = -200; pv = 10000; fv = FINANCE('fv', rate, nper, pmt, pv);RUN;PROC PRINT;RUN;"
},
{
"code": null,
"e": 3565,
"s": 3503,
"text": "The result is that you have paid 465.51 more than you should."
},
{
"code": null,
"e": 3637,
"s": 3565,
"text": "You use the function np.fv(rate, nper, pmt, pv). Same syntax as before."
},
{
"code": null,
"e": 3786,
"s": 3637,
"text": "df = pd.DataFrame({'Obs':[1]})df['rate'] = 0.06/12df['nper'] = 60df['pmt'] = -200df['pv'] = 10000df['fv'] = np.fv(df.rate, df.nper, df.pmt, df.pv)df"
},
{
"code": null,
"e": 3813,
"s": 3786,
"text": "Alternative ways in Python"
},
{
"code": null,
"e": 4022,
"s": 3813,
"text": "I want to show you a way to do the same calculation without using a DataFrame. You can do this directly in Python. You assign the values to variables and use the variables as argument in the np.fv() function."
},
{
"code": null,
"e": 4113,
"s": 4022,
"text": "rate = 0.06/12nper = 60pmt= -200pv = 10000fv = np.fv(rate,nper,pmt,pv)fv465.50457647922485"
},
{
"code": null,
"e": 4188,
"s": 4113,
"text": "Or you just type the values as an argument directly in the NumPy function."
},
{
"code": null,
"e": 4235,
"s": 4188,
"text": "np.fv(0.06/12,60,-200,10000)465.50457647922485"
},
{
"code": null,
"e": 4349,
"s": 4235,
"text": "If you just have to make one calculation, that is for just one observation, the last two examples are sufficient."
},
{
"code": null,
"e": 4563,
"s": 4349,
"text": "In this example, we still look the loan, but this time we want to know how much we can borrow if we repay the loan with 200 per month for the next five years. The annual interest rate is 6% and is charged monthly."
},
{
"code": null,
"e": 4645,
"s": 4563,
"text": "We use PV to tell the finance function that we are looking for the present value."
},
{
"code": null,
"e": 4765,
"s": 4645,
"text": "DATA pv; rate=0.06/12; nper=12 * 5; pmt=-200; fv=0; pv=FINANCE('pv', rate, nper, pmt, fv);RUN;PROC PRINT;RUN;"
},
{
"code": null,
"e": 4828,
"s": 4765,
"text": "The result of the calculation is that we can borrow 10.345,11."
},
{
"code": null,
"e": 4883,
"s": 4828,
"text": "You use the present value function np.pv() from NumPy:"
},
{
"code": null,
"e": 5030,
"s": 4883,
"text": "df = pd.DataFrame({'Obs':[1]})df['rate'] = 0.06/12df['nper'] = 12*5df['pmt'] = -200df['fv'] = 0df['pv'] = np.pv(df.rate, df.nper, df.pmt, df.fv)df"
},
{
"code": null,
"e": 5120,
"s": 5030,
"text": "What about the number of payments you need to make to pay back 10.000 with 200 per month?"
},
{
"code": null,
"e": 5216,
"s": 5120,
"text": "We use the same setup as before, but this time we set the FINANCE() function to calculate nper."
},
{
"code": null,
"e": 5337,
"s": 5216,
"text": "DATA nper; rate=0.06/12; pmt=-200; pv=10000; fv=0; nper=FINANCE('nper', rate, pmt, pv, fv);RUN;PROC PRINT;RUN;"
},
{
"code": null,
"e": 5407,
"s": 5337,
"text": "Again, the syntax is the same. This time we use the function np.fv():"
},
{
"code": null,
"e": 5555,
"s": 5407,
"text": "df = pd.DataFrame({'Obs':[1]})df['rate'] = 0.06/12df['pmt'] = -200df['pv'] = 10000df['fv'] = 0df['nper'] = np.nper(df.rate, df.pmt, df.pv, df.fv)df"
},
{
"code": null,
"e": 5619,
"s": 5555,
"text": "So we have to make 58 payments to pay back 10.000 over 5 years."
},
{
"code": null,
"e": 5735,
"s": 5619,
"text": "Now we want to look at the yearly interest rate when you pay back a loan of 10,000 with 60 monthly payments of 200."
},
{
"code": null,
"e": 5883,
"s": 5735,
"text": "The result from the FINANCE() function is the monthly interest. Therefore, you have to multiply the result with 12 to get the annual interest rate."
},
{
"code": null,
"e": 6012,
"s": 5883,
"text": "DATA rate; nper=60; payment=-200; pv=10000; fv=0; rate=FINANCE('rate', nper, payment, pv, fv) * 12;RUN;PROC PRINT;RUN;"
},
{
"code": null,
"e": 6098,
"s": 6012,
"text": "So to pay back a loan of 10.000 with 200 per month, the anual interest would be 7.42%"
},
{
"code": null,
"e": 6197,
"s": 6098,
"text": "We use the np.rate() function. But, we still need to multiply it with 12 to get the yearly result."
},
{
"code": null,
"e": 6345,
"s": 6197,
"text": "df = pd.DataFrame({'Obs':[1]})df['nper'] = 60df['pmt'] = -200df['pv'] = 10000df['fv'] = 0df['rate'] = np.rate(df.nper, df.pmt, df.pv, df.fv) * 12df"
},
{
"code": null,
"e": 6439,
"s": 6345,
"text": "If you want to know how much principal you would pay each month, you can use the ppmt method."
},
{
"code": null,
"e": 6550,
"s": 6439,
"text": "You calculate ppmt for each period using the FINANCE() function in a do loop to get the 60 principal payments."
},
{
"code": null,
"e": 6745,
"s": 6550,
"text": "DATA ppmt; DO period = 1 TO 60; rate=0.06/12; nper=60; pv=10000; fv=0; ppmt=FINANCE('ppmt', rate, period, nper, pv, fv); output; end;run;proc print;run;"
},
{
"code": null,
"e": 6957,
"s": 6745,
"text": "To create one records for the 60 months, we use range(1,61) to make a list of 60 values from 1 to 60 as the period column. For each period the np.ppmt() function is then used to calculates the principal payment."
},
{
"code": null,
"e": 7132,
"s": 6957,
"text": "df = pd.DataFrame()df['period'] = range(1, 61)df['rate'] = 0.06/12df['nper'] = 60df['pv'] = 10000df['fv'] = 0df['ppmt'] = np.ppmt(df.rate, df.period, df.nper, df.pv, df.fv)df"
},
{
"code": null,
"e": 7284,
"s": 7132,
"text": "Remember that SAS count the possition of the records starting with the first record having the number 1. In Python the number of the first record is 0."
},
{
"code": null,
"e": 7390,
"s": 7284,
"text": "For SAS users, think about it as your age, when you were born. In you first year you were zero years old."
},
{
"code": null,
"e": 7440,
"s": 7390,
"text": "There are other financial calculations we can do."
},
{
"code": null,
"e": 7535,
"s": 7440,
"text": "The first is how to calculate the effective interest rate if you are charged monthly interest."
},
{
"code": null,
"e": 7595,
"s": 7535,
"text": "In SAS, the finance function can do the calculation for us."
},
{
"code": null,
"e": 7665,
"s": 7595,
"text": "In Python, you have to calculate it yourself and that is very simple."
},
{
"code": null,
"e": 7752,
"s": 7665,
"text": "I’ll show you how to use the FINANCE() function and how you can calculate it yourself."
},
{
"code": null,
"e": 7895,
"s": 7752,
"text": "DATA effective; rate=0.06; nper=12; effect_fin = FINANCE('effect', rate, nper); effect = (1 + rate/nper)**nper - 1;RUN;PROC PRINT;RUN;"
},
{
"code": null,
"e": 8017,
"s": 7895,
"text": "You have to calculate the effective interest rate ourselves. I will show you how to do this in Python and in a DataFrame."
},
{
"code": null,
"e": 8173,
"s": 8017,
"text": "rate = 0.06nper = 12effect = (1 + rate/nper)**nper - 1print('The effective interest rate is: ', effect)The effective interest rate is: 0.06167781186449828"
},
{
"code": null,
"e": 8225,
"s": 8173,
"text": "Notice how you can add a text in your print output!"
},
{
"code": null,
"e": 8341,
"s": 8225,
"text": "df = pd.DataFrame({'Obs':[1]})df['rate'] = ratedf['nper'] = nperdf['effect'] = (1 + df.rate/df.nper)**df.nper - 1df"
},
{
"code": null,
"e": 8381,
"s": 8341,
"text": "So the effective interest rate is 6.16%"
},
{
"code": null,
"e": 8481,
"s": 8381,
"text": "There are other useful calculations you can use in finance. Internal rate of return is one of them."
},
{
"code": null,
"e": 8611,
"s": 8481,
"text": "You can still use the FINANCE() function. But this time the arguments are different as they are the cash flow for the investment."
},
{
"code": null,
"e": 8731,
"s": 8611,
"text": "In this example, you invest 40.000 and receive four payment in return. The function returns the IRR of this investment."
},
{
"code": null,
"e": 8864,
"s": 8731,
"text": "%%SASDATA irr; v1=-40000; v2=5000; v3=8000; v4=12000; v5=30000; r=FINANCE('irr', v1, v2, v3, v4, v5);RUN;PROC PRINT;RUN;"
},
{
"code": null,
"e": 8902,
"s": 8864,
"text": "The internal rate of return is 10.58%"
},
{
"code": null,
"e": 9044,
"s": 8902,
"text": "We also have a np.irr() function and the syntax is very similar to SAS. Only that you don't need to have the cash flow in separate variables."
},
{
"code": null,
"e": 9151,
"s": 9044,
"text": "df = pd.DataFrame()df['cashflow'] = [-40000, 5000, 8000, 12000, 30000]df['irr'] = np.irr(df['cashflow'])df"
},
{
"code": null,
"e": 9278,
"s": 9151,
"text": "You can also do the calculation outside the DataFrame with Series as an input or directly with the cash flow numbers as input."
},
{
"code": null,
"e": 9386,
"s": 9278,
"text": "irr = np.irr(df['cashflow'])irr0.10582259840890207np.irr([-40000,5000,8000,12000,30000])0.10582259840890207"
},
{
"code": null,
"e": 9520,
"s": 9386,
"text": "This is a very interesting formula. For many years the explanations of how to use this formula have been wrong in both SAS and Excel."
},
{
"code": null,
"e": 9686,
"s": 9520,
"text": "When you calculate a net, you have to deduct something. But that is not explained in the documentations of SAS and Microsoft. So the function is not calculating npv."
},
{
"code": null,
"e": 9806,
"s": 9686,
"text": "You have to add a deduction to get the right result. In Python, every thing is calculated correctly from the beginning."
},
{
"code": null,
"e": 9976,
"s": 9806,
"text": "You can use the FINANCE() function in calculating the Net Present Value. You use the cash flow and interest rate as input and then deduct the investment from the output."
},
{
"code": null,
"e": 10050,
"s": 9976,
"text": "I will also show you the formulas for calculating npv without a function."
},
{
"code": null,
"e": 10326,
"s": 10050,
"text": "DATA npv; rate=0.08; investment=-40000; cf1=5000; cf2=8000; cf3=12000; cf4=30000; npv = FINANCE('npv', rate, cf1, cf2, cf3, cf4) + investment; npv_formula = cf1/(1+rate)**1 + cf2/(1+rate)**2 + cf3/(1+rate)**3 + cf4/(1+rate)**4 + investment;RUN;PROC PRINT;RUN;"
},
{
"code": null,
"e": 10449,
"s": 10326,
"text": "On the other hand, the np.npv() function takes the full list of values, both the investment and the cashflow as arguments."
},
{
"code": null,
"e": 10580,
"s": 10449,
"text": "df = pd.DataFrame()df['values'] = [-40000, 5000, 8000, 12000, 30000]df['rate'] = 0.08df['npv'] = np.npv(df['rate'],df['values'])df"
},
{
"code": null,
"e": 10635,
"s": 10580,
"text": "You can also use your own formula for calculating NPV."
},
{
"code": null,
"e": 10736,
"s": 10635,
"text": "5000/(1+0.08)**1 + 8000/(1+0.08)**2 + 12000/(1+0.08)**3 + 30000/(1+0.08)**4 - 400003065.222668179529"
},
{
"code": null,
"e": 10920,
"s": 10736,
"text": "This last example shows how to separate the two values, investment and cashflow. If you have the values in each list, you can add the two list's in the function as investment+cashflow"
},
{
"code": null,
"e": 11040,
"s": 10920,
"text": "rate = 0.08investment = [-40000]cashflow = [5000, 8000, 12000, 30000]np.npv(rate,investment+cashflow)3065.2226681795255"
},
{
"code": null,
"e": 11205,
"s": 11040,
"text": "That all I had about financial functions. In SAS you can use FINANCE() for all the calculations. In Python you use separate functions, but with very similar syntax."
},
{
"code": null,
"e": 11407,
"s": 11205,
"text": "I hope you are aware of the challenge in calculating net present values in SAS and Excel and that you are not including the invesment in you function. If you are, I wish you good luck telling you boss."
},
{
"code": null,
"e": 11453,
"s": 11407,
"text": "We all make mistake, we are humans after all."
},
{
"code": null,
"e": 11548,
"s": 11453,
"text": "I hope you have enjoyed the article and I look forward writing more tips about SAS and Python."
},
{
"code": null,
"e": 11675,
"s": 11548,
"text": "If you want to know more about how you can learn Python the way you work in SAS, go to the following link to get more details:"
},
{
"code": null,
"e": 11701,
"s": 11675,
"text": "https://www.nordstroem.uk"
}
] |
How to plot a multi-colored line, like a rainbow using Matplotlib?
|
To plot multi-colored lines, like a rainbow, we can create a list of seven rainbow colors (VIBGYOR).
Create x for data points using numpy.
Create x for data points using numpy.
Create a list of colors (rainbow VIBGYOR).
Create a list of colors (rainbow VIBGYOR).
Iterate in the range of colors list length.
Iterate in the range of colors list length.
Plot lines with x and y(x+i/20) using plot() method, with marker=o, linewidth=7 and colors[i] where i is the index.
Plot lines with x and y(x+i/20) using plot() method, with marker=o, linewidth=7 and colors[i] where i is the index.
To display the figure, use show() method.
To display the figure, use show() method.
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
x = np.linspace(-1, 1, 10)
colors = ["red", "orange", "yellow", "green", "blue", "indigo", "violet"]
for i in range(len(colors)):
plt.plot(x, x+i/20, c=colors[i], lw=7, marker='o')
plt.show()
|
[
{
"code": null,
"e": 1163,
"s": 1062,
"text": "To plot multi-colored lines, like a rainbow, we can create a list of seven rainbow colors (VIBGYOR)."
},
{
"code": null,
"e": 1201,
"s": 1163,
"text": "Create x for data points using numpy."
},
{
"code": null,
"e": 1239,
"s": 1201,
"text": "Create x for data points using numpy."
},
{
"code": null,
"e": 1282,
"s": 1239,
"text": "Create a list of colors (rainbow VIBGYOR)."
},
{
"code": null,
"e": 1325,
"s": 1282,
"text": "Create a list of colors (rainbow VIBGYOR)."
},
{
"code": null,
"e": 1369,
"s": 1325,
"text": "Iterate in the range of colors list length."
},
{
"code": null,
"e": 1413,
"s": 1369,
"text": "Iterate in the range of colors list length."
},
{
"code": null,
"e": 1529,
"s": 1413,
"text": "Plot lines with x and y(x+i/20) using plot() method, with marker=o, linewidth=7 and colors[i] where i is the index."
},
{
"code": null,
"e": 1645,
"s": 1529,
"text": "Plot lines with x and y(x+i/20) using plot() method, with marker=o, linewidth=7 and colors[i] where i is the index."
},
{
"code": null,
"e": 1687,
"s": 1645,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 1729,
"s": 1687,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 2067,
"s": 1729,
"text": "import numpy as np\nfrom matplotlib import pyplot as plt\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\nx = np.linspace(-1, 1, 10)\ncolors = [\"red\", \"orange\", \"yellow\", \"green\", \"blue\", \"indigo\", \"violet\"]\nfor i in range(len(colors)):\n plt.plot(x, x+i/20, c=colors[i], lw=7, marker='o')\nplt.show()"
}
] |
List push_back() function in C++ STL
|
In this article we will be discussing the working, syntax and examples of list:: push_back() function in C++.
List is a data structure that allows constant time insertion and deletion anywhere in sequence. Lists are implemented as doubly linked lists. Lists allow non-contiguous memory allocation. List perform better insertion extraction and moving of element in any position in container than array, vector and deque. In List the direct access to the element is slow and list is similar to forward_list, but forward list objects are single linked lists and they can only be iterated forwards.
list::push_back() is an inbuilt function in C++ STL which is declared in header file. push_back() is used to push/insert the element at the end of the list container. push_back also increases the size of the container by 1.
list_name. push_back (int ele);
This function accept one parameter only, i.e. the element we want to push/insert at the back/last of the list_name container.
This function returns nothing. It will only insert the element in the list container.
Live Demo
#include<bits/stdc++.h>
using namespace std;
int main(){
//create a list
list<int> myList;
//Displaying the initial size of a list
cout<<"size of the list: "<<myList.size()<< endl;
//inserting elements to the list
myList.push_back(1);
myList.push_back(2);
myList.push_back(3);
//Size of the list after inserting elements
cout<<"Size of the list after inserting elements: "<<myList.size();
return 0;
}
If we run the above code then it will generate the following output
Size of the list : 0
Size of the list after inserting elements: 3
|
[
{
"code": null,
"e": 1172,
"s": 1062,
"text": "In this article we will be discussing the working, syntax and examples of list:: push_back() function in C++."
},
{
"code": null,
"e": 1657,
"s": 1172,
"text": "List is a data structure that allows constant time insertion and deletion anywhere in sequence. Lists are implemented as doubly linked lists. Lists allow non-contiguous memory allocation. List perform better insertion extraction and moving of element in any position in container than array, vector and deque. In List the direct access to the element is slow and list is similar to forward_list, but forward list objects are single linked lists and they can only be iterated forwards."
},
{
"code": null,
"e": 1881,
"s": 1657,
"text": "list::push_back() is an inbuilt function in C++ STL which is declared in header file. push_back() is used to push/insert the element at the end of the list container. push_back also increases the size of the container by 1."
},
{
"code": null,
"e": 1913,
"s": 1881,
"text": "list_name. push_back (int ele);"
},
{
"code": null,
"e": 2039,
"s": 1913,
"text": "This function accept one parameter only, i.e. the element we want to push/insert at the back/last of the list_name container."
},
{
"code": null,
"e": 2125,
"s": 2039,
"text": "This function returns nothing. It will only insert the element in the list container."
},
{
"code": null,
"e": 2136,
"s": 2125,
"text": " Live Demo"
},
{
"code": null,
"e": 2571,
"s": 2136,
"text": "#include<bits/stdc++.h>\nusing namespace std;\nint main(){\n //create a list\n list<int> myList;\n //Displaying the initial size of a list\n cout<<\"size of the list: \"<<myList.size()<< endl;\n //inserting elements to the list\n myList.push_back(1);\n myList.push_back(2);\n myList.push_back(3);\n //Size of the list after inserting elements\n cout<<\"Size of the list after inserting elements: \"<<myList.size();\n return 0;\n}\n"
},
{
"code": null,
"e": 2639,
"s": 2571,
"text": "If we run the above code then it will generate the following output"
},
{
"code": null,
"e": 2705,
"s": 2639,
"text": "Size of the list : 0\nSize of the list after inserting elements: 3"
}
] |
How to add percentages on top of bars in Seaborn using Matplotlib?
|
To add percentages on top of bars in Seaborn, we can take the following steps −
Create the lists, x, y and percentages to plot using Seaborn.
Create the lists, x, y and percentages to plot using Seaborn.
Using barplot, show point estimates and confidence intervals with bars. Store the returned axis.
Using barplot, show point estimates and confidence intervals with bars. Store the returned axis.
Find patches from the returned axis (In step 2).
Find patches from the returned axis (In step 2).
Iterate the patches (returned in step 3).
Iterate the patches (returned in step 3).
Find x and y from the patches to place the percentage value at the top of the bars.
Find x and y from the patches to place the percentage value at the top of the bars.
To display the figure, use show() method.
To display the figure, use show() method.
import matplotlib.pyplot as plt
import seaborn as sns
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
x = ['A', 'B', 'C', 'D', 'E']
y = [1, 3, 2, 0, 4]
percentage = [10, 30, 20, 0, 40]
ax = sns.barplot(x=x, y=y, palette='PuBuGn_r')
patches = ax.patches
for i in range(len(patches)):
x = patches[i].get_x() + patches[i].get_width()/2
y = patches[i].get_height()+.05
ax.annotate('{:.1f}%'.format(percentage[i]), (x, y), ha='center')
plt.show()
|
[
{
"code": null,
"e": 1142,
"s": 1062,
"text": "To add percentages on top of bars in Seaborn, we can take the following steps −"
},
{
"code": null,
"e": 1204,
"s": 1142,
"text": "Create the lists, x, y and percentages to plot using Seaborn."
},
{
"code": null,
"e": 1266,
"s": 1204,
"text": "Create the lists, x, y and percentages to plot using Seaborn."
},
{
"code": null,
"e": 1363,
"s": 1266,
"text": "Using barplot, show point estimates and confidence intervals with bars. Store the returned axis."
},
{
"code": null,
"e": 1460,
"s": 1363,
"text": "Using barplot, show point estimates and confidence intervals with bars. Store the returned axis."
},
{
"code": null,
"e": 1509,
"s": 1460,
"text": "Find patches from the returned axis (In step 2)."
},
{
"code": null,
"e": 1558,
"s": 1509,
"text": "Find patches from the returned axis (In step 2)."
},
{
"code": null,
"e": 1600,
"s": 1558,
"text": "Iterate the patches (returned in step 3)."
},
{
"code": null,
"e": 1642,
"s": 1600,
"text": "Iterate the patches (returned in step 3)."
},
{
"code": null,
"e": 1726,
"s": 1642,
"text": "Find x and y from the patches to place the percentage value at the top of the bars."
},
{
"code": null,
"e": 1810,
"s": 1726,
"text": "Find x and y from the patches to place the percentage value at the top of the bars."
},
{
"code": null,
"e": 1852,
"s": 1810,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 1894,
"s": 1852,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 2384,
"s": 1894,
"text": "import matplotlib.pyplot as plt\nimport seaborn as sns\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\nx = ['A', 'B', 'C', 'D', 'E']\ny = [1, 3, 2, 0, 4]\npercentage = [10, 30, 20, 0, 40]\nax = sns.barplot(x=x, y=y, palette='PuBuGn_r')\npatches = ax.patches\nfor i in range(len(patches)):\n x = patches[i].get_x() + patches[i].get_width()/2\n y = patches[i].get_height()+.05\n ax.annotate('{:.1f}%'.format(percentage[i]), (x, y), ha='center')\nplt.show()"
}
] |
Chatbots are cool! A framework using Python | by Sundar Krishnan | Towards Data Science
|
Did you like what you saw on the Kelly Movie Bot video? If the answer is “Yes” and you want to implement a chatbot, you can start reading this article. This article is very detailed. I split the entire article into parts. So, sit back and relax! We will go through each one of the parts and finally at the end of the article, you should have deployed a chatbot in Slack.
Part 1: OverviewPart 2: DataPart 3: SlackPart 4: NLP using IBM WatsonPart 5: Custom NLP solutionsPart 6: LogsPart 7: Final Notes
Part 1: Overview
Part 2: Data
Part 3: Slack
Part 4: NLP using IBM Watson
Part 5: Custom NLP solutions
Part 6: Logs
Part 7: Final Notes
Audience for this article: I designed a generic chatbot framework and discussed in this article to cover a wide range of audience. Anyone who has a basic knowledge of Python, Jupyter notebooks and can perform pip installations should be able to complete this series and see the results.
The bot framework is modularized which opens up an array of opportunities for the readers to design and implement their own features. Integrations can be done easily in the framework. Also, the probability for failure is minimal since it is designed to be plug and play.
Beginner: An overall idea on how the framework is developed and used for this specific project. You should be able to download the codes from Github and complete the setup successfully. This includes package installations, slack and IBM Watson account creation and setup, run one time files to generate the links and movie recommendations. You can add extra skills in IBM Watson (like a small talk which generate static responses) and see the results in slack environment.
Intermediate: You should be able to use this framework as a template to design your own chatbot which can be deployed on a different domain. In addition, you can extend the knowledge base for the chatbot by adding new data sources which includes writing codes to connect to different databases (Elastic search, SQL databases, Excel and so on..). Also, you can add extra NLP features to the bot and see the results in slack environment.
Expert: You should be able to add/extend bot features by integrating API connections for Slack/NLP. I used IBM Watson to identify question category and to generate static responses. You can replace IBM Watson in the framework by designing your own NLP capabilities. Also, you can extend the bot integrations for different platforms (Web, Skype and so on..)
Chatbot is a tool to retrieve information and generate humanlike conversation. It is mainly a dialog system aimed to solve/serve a specific purpose. Depending upon the design, chatbots generally fall into 4 categories.
Open Domain
Open Domain bots are otherwise known as Generalist bots. Today we use Alexa, Google Home, Siri, Cortana which fall under this category(open domain/generative-based). These bots try to imitate humanlike conversation. Again, it answers questions (like FAQ’s) asked by most humans. However, they cannot answer a specific domain based question. For example: How did my company sales division performed in the last quarter? That is one of the reason, open domain/retrieval-based bots is impossible to build.
Closed Domain
Closed Domain bots are otherwise known as Specialist bots. Depending upon the type, it can be easy (retrieval-based) or hard(generative-based) to develop. The bot discussed in this article is a specialist bot and it falls under the closed domain/retrieval-based category. Other bots in this category include — order a pizza, book flights/restaurants/hotel/appointments. On the other hand, generative bots include customer service chatbots which try to imitate like a agent while answering the questions from customer. These bots are hard to build since the bots try to make the customer believe that they are talking to a actual human.
Chatbots needs to understand the following to respond to an user question.
What is the user talking about? (Intent)Did the user mention anything specific? (Entities)What should the bot ask to get further details from the user? (Dialog/Maintaining Context)How to fulfill the user request? (Response/Fulfillment)
What is the user talking about? (Intent)
Did the user mention anything specific? (Entities)
What should the bot ask to get further details from the user? (Dialog/Maintaining Context)
How to fulfill the user request? (Response/Fulfillment)
Let us use a Flight Bot example shown below to understand each of these pieces in detail. The user says “I want to book a ticket from New York to Seattle departing on September 15 and returning on September 19 for 2 people”.
Intent
The intent of the user is to book flights.
Entities
Entities are also known as keywords or slots. Here there are multiple entities.
From - New York
To - Seattle
Departure date - September 15
Return date - September 19
#people - 2
Dialog/Maintaining Context
Dialogs are back and forth communication between bot and user. A context let’s the bot know what state the bot is currently in. There are three states — Previous, Present and Future. When the user initiates the dialog, the bot reiterates the user itinerary and then checks with the user “Is this info correct?”. Here the previous state is blank, present state is “user validation” and future state is to “Provide a response based on user validation”. When the user responds “Yes”, then the bot state changes to “User validation”, “Provide a response based on user validation” and “Book a flight” for Previous, present and future state respectively. Without maintaining the context, bots cannot establish the back and forth communication. In the flight bot example, if the context is not maintained the bot would be asking “Is this info correct?” every time until the user gives up.
Response/Fulfillment
Fulfilling the user request is the final step in the bot conversation. Here the bot provides the results in the form of links “See all results”. So when the user clicks the link, they will be able to see the flights and make a reservation.
Generative-based bots use AI and Machine learning to generate user responses. So they need not have to understand the Intents and Entities to respond to a user.
I found this article which covers a lot of topics that we discussed so far and also the bot frameworks that you can use to build chatbots. It is a good read.
www.datasciencecentral.com
Okay, now it is time to deploy the Kelly movie bot. It is a simple bot that answers questions about movies. The user can ask about ratings, #people voted for the movie, genre, movie overview, similar movies, imdb and tmdb links, budget, revenue and adult content. The dataset for this exercise is taken from Kaggle — movies_metadata. The entire code for this project can be found in Github.
github.com
One important thing to note with this design is that, the data and processing is all handled in the local system. Even though we use IBM, it is used as an API service and none of the internal data is sent to IBM. This way the entire design can be implemented in your workplace without having to worry about data transfers.
Step 1 (User asks question):
Users can interact with Kelly via Slack. Once the user post a question, it is passed to the backend system for analysis.
Step 2 and 3 (NLP processing and Return the NLP results):
All the natural language processing happens in step 2. This includes IBM Watson processing, similarity search, recommendation based on collaborative filtering. After the NLP processing is completed, we have three outputs from it
Intents — What the user is trying to ask or query?Entities — What is the exact field or column they are looking for?Dialog/Interaction — Provide the appropriate request/response for the user question.
Intents — What the user is trying to ask or query?
Entities — What is the exact field or column they are looking for?
Dialog/Interaction — Provide the appropriate request/response for the user question.
Step 4 and 5(Query the data):
Currently, the data resides in a excel file. However, you can add multiple databases/excel files if needed, to access different sources. Based on the results from step 3, the appropriate database/excel file is queried and the results are returned.
Step 6 (Post the result to user):
The results obtained from the backend is posted to user via Slack
Step 7 (Log maintenance):
The interactions between the users are logged and stored in a text file. Also, if the bot is not able to identify the user questions it will add those questions to a followup file.
Package Imports
As usual, we define the program by importing the packages. Notice something, where it says “slack.slack_commands” and “nlp.nlp_commands”. This would import the python program slack_commands and nlp_commands from slack and nlp folder respectively. In addition, a couple of functions from the config file is imported.
Variables Initialization
User context is maintained in the “context” variable. Once the chat begins, the context variable generated by IBM Watson looks like below,
{'conversation_id': '76e59c57-8257-4390-ae15-ba75e7576476', 'system': {'_node_output_map': {'node_2_1541443578896': [0]}, 'branch_exited': True, 'branch_exited_reason': 'completed', 'dialog_request_counter': 1, 'dialog_stack': [{'dialog_node': 'root'}], 'dialog_turn_counter': 1, 'initialized': True}}
It has a “conversation_id” which is used to track the state (previous/present and future state) of conversation flow. During the start of the conversation it is assigned to a empty dictionary value.
In addition to maintaining a conversation, we also should let the bot know when to stop a conversation. This is achieved by the “current_action” variable. An example of the ending a conversation is shown below.
Whenever the user invokes a “Goodbye” intent, the bot assigns ‘end_conversation’ to “current_action” variable. Later in the main.py program, this variable will be evaluated to reassign context, current_action and session_df variables which is shown below.
Another key variable is the “session_df” dataframe. When a user starts a conversation with the bot a session is created. This ensures that the context between a user and the bot is handled on per-user basis. When the same user talks to the bot in multiple channels, they are handled as different sessions. So, there is no overlap in conversation between bot and user.
When a user asks a random question which the bot cannot handle, it will trigger the “follow_ind” to write the question in a follow up text file. During the start of the conversation, it is assigned to 0. The final two variables “bot_id” and “RTM_READ_DELAY” corresponds to slack. When the bot is invoked, the bot_id is assigned. RTM stands for Real Time Messaging. This variable will wait for a second before it reads the next input message from the user.
Invoke the code
Finally, the rest of the program ensures that the bot is consistently running and looking for input messages from the user. Some of the functions mentioned below — parse_bot_commands, handle_command and output_command will be discussed in detail in the later section.
That’s it. We initiated our Kelly bot. Our next step is to understand the data used for this exercise.
The data for this exercise is taken from the Kaggle link below. The name of the dataset is “movies_metadata.csv”.
www.kaggle.com
The dataset contains a lot of information related to movies with less preprocessing required from users. We import the dataset using Pandas and then prepare our data.
<class 'pandas.core.frame.DataFrame'>RangeIndex: 45466 entries, 0 to 45465Data columns (total 24 columns):adult 45466 non-null objectbelongs_to_collection 4494 non-null objectbudget 45466 non-null objectgenres 45466 non-null objecthomepage 7782 non-null objectid 45466 non-null objectimdb_id 45449 non-null objectoriginal_language 45455 non-null objectoriginal_title 45466 non-null objectoverview 44512 non-null objectpopularity 45461 non-null objectposter_path 45080 non-null objectproduction_companies 45463 non-null objectproduction_countries 45463 non-null objectrelease_date 45379 non-null objectrevenue 45460 non-null float64runtime 45203 non-null float64spoken_languages 45460 non-null objectstatus 45379 non-null objecttagline 20412 non-null objecttitle 45460 non-null objectvideo 45460 non-null objectvote_average 45460 non-null float64vote_count 45460 non-null float64dtypes: float64(4), object(20)memory usage: 8.3+ MB
adult 0belongs_to_collection 40972budget 0genres 0homepage 37684id 0imdb_id 17original_language 11original_title 0overview 954popularity 5poster_path 386production_companies 3production_countries 3release_date 87revenue 6runtime 263spoken_languages 6status 87tagline 25054title 6video 6vote_average 6vote_count 6dtype: int64
It turns out there are a lot of missing values in the data. So we remove the variables with high missing value percentage. Also, I removed a few other variables to keep the data simple. The code below is used to remove variables from the dataset.
“imdb_id” and “poster_path” variable had missing values in them. I had to remove the observations which had missing values for these variables using the code below.
Now, let us look at the genres variables in the dataset.
The genre name is stored in a list of dictionaries format. To make it a clean format, we need to apply a preparation code below.
Pretty nice format right. Now let us move to our final step of creating the IMDB, TMDB and Image url links.
Voila. We are done with the data preparation and finally export the prepared dataset using the code below.
metadata.to_csv('metadata_prep.csv')
The entire data preparation code is available in the notebook below.
github.com
That’s it. This concludes the data preparation process. Our next step is to understand slack process.
Okay, now it is time to understand the slack process and how it is handled in the framework. The first step is to create a slack bot and install it in the workspace. The link below will guide you to create the slack app. In the configuration file, you need to edit the Slack Bot token and Slack verification token. That is all the setup required for slack.
github.com
There are 6 slack functions written for Kelly bot.
parse_bot_commandsparse_direct_mentionoutput_commandfile_uploadslack_tilesmessage_buttons
parse_bot_commands
parse_direct_mention
output_command
file_upload
slack_tiles
message_buttons
Let us look into each of the functions in detail.
parse_bot_commands
When the user types a message in slack, the parse_bot_commands function is invoked. In slack, the Real Time Messaging(RTM) events (slack_events) stores all the information about a particular user conversation. This includes who is asking this question (message_user), which team and channel are they using (team, channel), what is the message or question from the user (message) and are they talking to someone else or the bot (user_id). Because, in slack a user can talk to different users by invoking @ symbol in front of the user name. For example — “@person1 show me the movie Toy Story” and “@Kelly show me the movie Toy Story” are different. The first one is directed to person1 and second one is directed to Kelly bot. Here, the bot will process a user message or question only when the “user_id” matches the “bot_id”.
parse_direct_mention
This is a sub function of parse_bot_commands. The question from the user “@Kelly show me the movie Toy Story” has two parts. The first part is the bot user name “@Kelly” and the second is the question from the user “show me the movie Toy Story”. This function takes the text from slack events (message_text) and separates the user question from the bot user name.
output_command
The output command is used to send the responses back to slack. This function only supports text output (slack_output). The “channel” variable is used to identify the slack channel from which the user is posting the question and use the same channel to direct the response.
In Kelly bot, the slack output produced by the output command function looks like below.
file_upload
File upload can be used to upload files to slack. File upload function supports multiple document types. A few among them would include PDF, Word, Excel, gifs, png etc. The complete list of supported file types can be seen in the link below.
api.slack.com
This function is not used in Kelly Bot. However it is provided here as an additional feature.
slack_tiles
Slack tiles are another way of displaying outputs to user in Slack. I used this function to show movie recommendations. The output of the function looks like below.
Pretty cool right. The images are represented using tiles so that the user attention is immediately grabbed. When you look closer, the movie names are hyperlinked. So when you click on the movie names, it redirects you to the IMDB movie page. Again, a simple and elegant way to display output in slack.
The function takes 5 inputs.
The “channel” variable as discussed before is used to post to the corresponding channel where the user is asking question.The “search_term” variable has the value “Toy Story”. Since I started my bot conversation with the question “show me the movie Toy Story”, the movie name is automatically stored in search_term and the context is maintained each time the user asks questions until the user starts over. Since the context is retained, when I asked the question “recommend me movies similar to this one” it responded in the first line saying “Recommendation for Toy Story”.The “title” variable has the movie title recommendations. Based on the highest scores obtained in the collaborative filtering method(which will be discussed later in Part5:Custom NLP solutions), it chooses the titles and stores them in a python list. This list is then processed in the function while displaying the output.The “title_url” has the corresponding IMDB links for the movie recommendationsThe “image_url” has the corresponding TMDB image links for the movie recommendations.
The “channel” variable as discussed before is used to post to the corresponding channel where the user is asking question.
The “search_term” variable has the value “Toy Story”. Since I started my bot conversation with the question “show me the movie Toy Story”, the movie name is automatically stored in search_term and the context is maintained each time the user asks questions until the user starts over. Since the context is retained, when I asked the question “recommend me movies similar to this one” it responded in the first line saying “Recommendation for Toy Story”.
The “title” variable has the movie title recommendations. Based on the highest scores obtained in the collaborative filtering method(which will be discussed later in Part5:Custom NLP solutions), it chooses the titles and stores them in a python list. This list is then processed in the function while displaying the output.
The “title_url” has the corresponding IMDB links for the movie recommendations
The “image_url” has the corresponding TMDB image links for the movie recommendations.
message_buttons
Message buttons are also a different style of displaying output in Slack. This is similar to slack tiles except that it wont have the images to display. Rather, the output contains buttons that are tied to IMDB links. This features is used in the start, when the user is trying to search a movie. I don’t remember all the movie names that I watched on the top of my head. So, I use keyword based movie search and this functionality is also implemented in the same way. The NLP program that handles the keyword based search (Similarity Search) will be discussed later in Part5:Custom NLP solutions. However, I wanted to show how this works with message buttons.
Here, when I began the movie search I did not mention “Toy Story” rather I started the conversation as “I am looking for a movie with a toy” and it gave me “Toy Story” as my 5th option. This type of search is called similarity search. Now, the user can click on button to ensure whether the movie they are looking for is the same and then proceed next. The button names are stored in the “button” variable and the corresponding IMDB links are stored in the “url” variable.
That’s it. This concludes the slack process. Our next step is to understand Natural language processing using IBM Watson.
A quick and easy way to develop chatbots is to use frameworks. There are lot of frameworks in the market, that can assist us to build bots. A few of them include — IBM Watson, Luis, Wit, Dialogflow, Rasa NLU, Botkit, Microsoft Bot Framework and so on. You can chose any one of the framework to build your bots. Again, the complexity of coding might vary depending upon the framework you choose. For this exercise, I used IBM Watson framework. The link below will assist you to create a Watson User account and getting started with IBM Watson conversation.
github.com
IBM Watson framework is used as an API service to perform Natural language processing. Kelly bot is built in such a way that none of the information is stored in IBM Watson. All the processing of information is happening in your local system. Only the question from the user is processed by IBM Watson service to provide the Intents, Entities, Dialog and Response. Other than that, none of the information is stored in IBM Watson.
These quick courses can get you started with building Intents, Entities and Dialog.
www.coursera.org
developer.ibm.com
For this exercise, you can upload the “bot.json” file that comes with the code in Github and import it to your IBM Watson conversation account to get started. Once you import the json file, the page should look like below.
Intents
Entities
I wanted to talk about a few things on how the connection is established between Watson, Slack and your python code. So, let us take a look at the entities first.
Here, look at the option entity. It can take only 5 possible values. If you can recall in the slack process, we used message buttons to get the movie name option from user.
Dialog
Let us say, if the user selects 6 instead of 5. The bot would then respond saying “Please provide a valid option — 1, 2, 3, 4 or 5”. This is established using the Dialog feature in IBM Watson. So let us look at this feature. The Dialog page should look like below.
We start the conversation by saying “hello”. The Watson would recognize this as “hello” intent, assigns the value “hello” to context variable “currentIntent”. In addition, it sends the response back to python code “Please enter a movie name to begin” and then jumps to evaluate movie name condition.
In the movie name condition evaluation, I have two child nodes as shown below.
The first child node evaluates whether a user has provided response. In IBM Watson, this is captured using “<?input_text?>” option. And then the bot responds to user to select a movie option as shown below.
Finally, based on the user option, it evaluates whether the option is a valid. If not, it would request the user to provide a valid option.
The corresponding slack interface interaction for this Watson conversation setup is shown below.
Python backend
In the python end, this is established by the handle_command function shown below.
When the IBM Watson API service is used, it returns a response which is captured in the “response” variable. Notice we pass the context variable to Watson service each time. This is used to maintain the context for the bot responses. Also, using the response variable we extract the context, entities and the bot response and assign them to “context”, “search_key” and “slack_output” respectively. The “search_term” variable contains the movie name corresponding to user selection. For now, I hope this gives a picture of how the interactions happen between the IBM Watson front end and the backend python code.
That’s it. This concludes this part — NLP using IBM Watson . Our next step is to understand the Custom NLP solutions written for Kelly bot.
Often times, we need to add extra NLP capabilities to enhance the bot skills. Well, this is your time to become more creative and start adding customized solutions. I added two custom solutions for Kelly Bot. (Located in the nlp/nlp_solutions folder).
Metadata based Collaborative filtering for movie recommendationCosine similarity search for identifying the movie titles
Metadata based Collaborative filtering for movie recommendation
Cosine similarity search for identifying the movie titles
The codes for both the function resides in “nlplearn.py” and “onetime_run_file.py”. So let us get started.
onetime_run_file.py
This function has codes that we need to run onetime before we initiate the Kelly bot. This onetime setup makes it easier in situations when the data is changing constantly and the bot needs to adapt to these data changes quickly. All we need to do is to run this file whenever we need without changing any of the internal functions in the bot. Pretty cool right. When the file run is completed, it generates a “onetime.txt” pickle file which will be used by the bot when it is initiated.
Now, let’s discuss the functions available in “nlplearn.py”. It has 5 functions,
text_preparetfidf_fit (Cosine similarity search)similarity_search (Cosine similarity search)metadata_filtering (Metadata based Collaborative filtering)get_recommendations (Metadata based Collaborative filtering)
text_prepare
tfidf_fit (Cosine similarity search)
similarity_search (Cosine similarity search)
metadata_filtering (Metadata based Collaborative filtering)
get_recommendations (Metadata based Collaborative filtering)
text_prepare
This function takes in a single document (“show me ? movie title ` similar to Toy Story######”) and prepares the text by removing spaces and bad characters. In addition, it also removes stop words from the text. The processed text looks something like this “show movie title similar toy story”.
tfidf_fit
This function takes the prepared text from step 1 and creates a tfidf fit. ‘tf’ means Term Frequency and ‘Idf’ means Inverse document frequency. You can read about tdidf in the link here. After the fit is completed, the fit and matrix gets stored in a pickle file for future processing. This is accomplished by the codes in “onetime_run_file.py”.
similarity_search
This function computes cosine similarity between the user query and the movie titles stored in the tfidf_matrix created by the tfidf_fit function. First, it performs a tfidf_fit on the user query and then it computes the cosine distance between the fit and the elements in the tfidf_matrix. The top 5 elements which has the highest cosine similarity score is chosen and sent back to slack interface. This is used in the message buttons in Slack which we discussed before.
metadata_filtering
This function performs metadata based collaborative filtering which is used for movie recommendations. You can read about this function in the link here. The final “cosine_sim” function gets stored in the pickle file for future processing. Again, this is also accomplished by the codes in “onetime_run_file.py”.
get_recommendations
This function is used to get movie recommendation based on the user search. It returns 3 similar movies and sends back to slack interface. This result is used in slack tiles which we discussed before.
Now, let us see how these custom NLP solutions looks like in Slack.
Reference: https://www.datacamp.com/community/tutorials/recommender-systems-python
That’s it. This concludes this part — Custom NLP solutions. Our next step is to understand the logs processing.
As of now, we have implemented all the features that is needed to run the bot. So why do we need to talk about logs? What importance does log files bring to bot framework?
Let us see an example to illustrate its importance. Suppose we have a “feedback” intent and the example user queries in the intent include “I am satisfied with your service”, “I don’t like your service”,”You are awesome”, “You are a disaster” and so on. We only provide a few example when we develop this intent. In future, let us say a user says “boo”. We know that this should be categorized as “feedback” intent. However, our bot is not trained on this response. So it would show it as some other intent resulting in bad user experience. Also, these type of user responses come at random and we need a way to identify and capture them.
The easiest way to collect user queries is via logs. So in the future, if a user asks a question different from the way we defined our intents, we can capture those responses and include them in the intents model training. This way we improve the overall customer experience.
In this bot framework, we have two types of log processing
Log fileFollow up file
Log file
Follow up file
Log file
The output log file looks like below.
As we see here, all the information is captured which makes it easier for future user query processing. Also, it includes the processing time in the log file (second to the last column). Using, this input we can optimize queries which takes more time to process and thus improving the bot efficiency.
Follow up file
The follow up file is also generated as a part of the log file processing. If the bot is not able to assign any intent to the user query (“Anything_else” intent) then the “follow_ind” is invoked. This will write the user query in a new file called ‘followup_file.TXT’ which looks like below.
This file can be later sent to bot developers via email using the code below.
That’s it. This concludes this part — Logs processing.
I assume if you are still reading this article, you have successfully completed this exercise. Great job! Ok, so what’s next?
As I said before, we can experiment by adding new bot features, extending the NLP capabilities and also implement the bot in other messaging platforms. The central idea around this framework is — all the work done can be reused if you need to change platforms and also for easy addition/extension of skills. That being said, I cannot cover all the possible options for you as the application of bots can vary depending upon the user requirements. So it is up to the you to explore and implement them. Good luck!
If you are looking to build some AI/Machine learning based chatbots then refer these links below.
ethancaballero.pythonanywhere.com
chatbotsmagazine.com
github.com
That’s it. This concludes the final part. If you need to discuss anything in particular or you have feedback on any of the modules, please leave a comment or reach out to me via LinkedIn or Twitter.
|
[
{
"code": null,
"e": 542,
"s": 171,
"text": "Did you like what you saw on the Kelly Movie Bot video? If the answer is “Yes” and you want to implement a chatbot, you can start reading this article. This article is very detailed. I split the entire article into parts. So, sit back and relax! We will go through each one of the parts and finally at the end of the article, you should have deployed a chatbot in Slack."
},
{
"code": null,
"e": 671,
"s": 542,
"text": "Part 1: OverviewPart 2: DataPart 3: SlackPart 4: NLP using IBM WatsonPart 5: Custom NLP solutionsPart 6: LogsPart 7: Final Notes"
},
{
"code": null,
"e": 688,
"s": 671,
"text": "Part 1: Overview"
},
{
"code": null,
"e": 701,
"s": 688,
"text": "Part 2: Data"
},
{
"code": null,
"e": 715,
"s": 701,
"text": "Part 3: Slack"
},
{
"code": null,
"e": 744,
"s": 715,
"text": "Part 4: NLP using IBM Watson"
},
{
"code": null,
"e": 773,
"s": 744,
"text": "Part 5: Custom NLP solutions"
},
{
"code": null,
"e": 786,
"s": 773,
"text": "Part 6: Logs"
},
{
"code": null,
"e": 806,
"s": 786,
"text": "Part 7: Final Notes"
},
{
"code": null,
"e": 1093,
"s": 806,
"text": "Audience for this article: I designed a generic chatbot framework and discussed in this article to cover a wide range of audience. Anyone who has a basic knowledge of Python, Jupyter notebooks and can perform pip installations should be able to complete this series and see the results."
},
{
"code": null,
"e": 1364,
"s": 1093,
"text": "The bot framework is modularized which opens up an array of opportunities for the readers to design and implement their own features. Integrations can be done easily in the framework. Also, the probability for failure is minimal since it is designed to be plug and play."
},
{
"code": null,
"e": 1837,
"s": 1364,
"text": "Beginner: An overall idea on how the framework is developed and used for this specific project. You should be able to download the codes from Github and complete the setup successfully. This includes package installations, slack and IBM Watson account creation and setup, run one time files to generate the links and movie recommendations. You can add extra skills in IBM Watson (like a small talk which generate static responses) and see the results in slack environment."
},
{
"code": null,
"e": 2273,
"s": 1837,
"text": "Intermediate: You should be able to use this framework as a template to design your own chatbot which can be deployed on a different domain. In addition, you can extend the knowledge base for the chatbot by adding new data sources which includes writing codes to connect to different databases (Elastic search, SQL databases, Excel and so on..). Also, you can add extra NLP features to the bot and see the results in slack environment."
},
{
"code": null,
"e": 2630,
"s": 2273,
"text": "Expert: You should be able to add/extend bot features by integrating API connections for Slack/NLP. I used IBM Watson to identify question category and to generate static responses. You can replace IBM Watson in the framework by designing your own NLP capabilities. Also, you can extend the bot integrations for different platforms (Web, Skype and so on..)"
},
{
"code": null,
"e": 2849,
"s": 2630,
"text": "Chatbot is a tool to retrieve information and generate humanlike conversation. It is mainly a dialog system aimed to solve/serve a specific purpose. Depending upon the design, chatbots generally fall into 4 categories."
},
{
"code": null,
"e": 2861,
"s": 2849,
"text": "Open Domain"
},
{
"code": null,
"e": 3364,
"s": 2861,
"text": "Open Domain bots are otherwise known as Generalist bots. Today we use Alexa, Google Home, Siri, Cortana which fall under this category(open domain/generative-based). These bots try to imitate humanlike conversation. Again, it answers questions (like FAQ’s) asked by most humans. However, they cannot answer a specific domain based question. For example: How did my company sales division performed in the last quarter? That is one of the reason, open domain/retrieval-based bots is impossible to build."
},
{
"code": null,
"e": 3378,
"s": 3364,
"text": "Closed Domain"
},
{
"code": null,
"e": 4014,
"s": 3378,
"text": "Closed Domain bots are otherwise known as Specialist bots. Depending upon the type, it can be easy (retrieval-based) or hard(generative-based) to develop. The bot discussed in this article is a specialist bot and it falls under the closed domain/retrieval-based category. Other bots in this category include — order a pizza, book flights/restaurants/hotel/appointments. On the other hand, generative bots include customer service chatbots which try to imitate like a agent while answering the questions from customer. These bots are hard to build since the bots try to make the customer believe that they are talking to a actual human."
},
{
"code": null,
"e": 4089,
"s": 4014,
"text": "Chatbots needs to understand the following to respond to an user question."
},
{
"code": null,
"e": 4325,
"s": 4089,
"text": "What is the user talking about? (Intent)Did the user mention anything specific? (Entities)What should the bot ask to get further details from the user? (Dialog/Maintaining Context)How to fulfill the user request? (Response/Fulfillment)"
},
{
"code": null,
"e": 4366,
"s": 4325,
"text": "What is the user talking about? (Intent)"
},
{
"code": null,
"e": 4417,
"s": 4366,
"text": "Did the user mention anything specific? (Entities)"
},
{
"code": null,
"e": 4508,
"s": 4417,
"text": "What should the bot ask to get further details from the user? (Dialog/Maintaining Context)"
},
{
"code": null,
"e": 4564,
"s": 4508,
"text": "How to fulfill the user request? (Response/Fulfillment)"
},
{
"code": null,
"e": 4789,
"s": 4564,
"text": "Let us use a Flight Bot example shown below to understand each of these pieces in detail. The user says “I want to book a ticket from New York to Seattle departing on September 15 and returning on September 19 for 2 people”."
},
{
"code": null,
"e": 4796,
"s": 4789,
"text": "Intent"
},
{
"code": null,
"e": 4839,
"s": 4796,
"text": "The intent of the user is to book flights."
},
{
"code": null,
"e": 4848,
"s": 4839,
"text": "Entities"
},
{
"code": null,
"e": 4928,
"s": 4848,
"text": "Entities are also known as keywords or slots. Here there are multiple entities."
},
{
"code": null,
"e": 4944,
"s": 4928,
"text": "From - New York"
},
{
"code": null,
"e": 4957,
"s": 4944,
"text": "To - Seattle"
},
{
"code": null,
"e": 4987,
"s": 4957,
"text": "Departure date - September 15"
},
{
"code": null,
"e": 5014,
"s": 4987,
"text": "Return date - September 19"
},
{
"code": null,
"e": 5026,
"s": 5014,
"text": "#people - 2"
},
{
"code": null,
"e": 5053,
"s": 5026,
"text": "Dialog/Maintaining Context"
},
{
"code": null,
"e": 5935,
"s": 5053,
"text": "Dialogs are back and forth communication between bot and user. A context let’s the bot know what state the bot is currently in. There are three states — Previous, Present and Future. When the user initiates the dialog, the bot reiterates the user itinerary and then checks with the user “Is this info correct?”. Here the previous state is blank, present state is “user validation” and future state is to “Provide a response based on user validation”. When the user responds “Yes”, then the bot state changes to “User validation”, “Provide a response based on user validation” and “Book a flight” for Previous, present and future state respectively. Without maintaining the context, bots cannot establish the back and forth communication. In the flight bot example, if the context is not maintained the bot would be asking “Is this info correct?” every time until the user gives up."
},
{
"code": null,
"e": 5956,
"s": 5935,
"text": "Response/Fulfillment"
},
{
"code": null,
"e": 6196,
"s": 5956,
"text": "Fulfilling the user request is the final step in the bot conversation. Here the bot provides the results in the form of links “See all results”. So when the user clicks the link, they will be able to see the flights and make a reservation."
},
{
"code": null,
"e": 6357,
"s": 6196,
"text": "Generative-based bots use AI and Machine learning to generate user responses. So they need not have to understand the Intents and Entities to respond to a user."
},
{
"code": null,
"e": 6515,
"s": 6357,
"text": "I found this article which covers a lot of topics that we discussed so far and also the bot frameworks that you can use to build chatbots. It is a good read."
},
{
"code": null,
"e": 6542,
"s": 6515,
"text": "www.datasciencecentral.com"
},
{
"code": null,
"e": 6933,
"s": 6542,
"text": "Okay, now it is time to deploy the Kelly movie bot. It is a simple bot that answers questions about movies. The user can ask about ratings, #people voted for the movie, genre, movie overview, similar movies, imdb and tmdb links, budget, revenue and adult content. The dataset for this exercise is taken from Kaggle — movies_metadata. The entire code for this project can be found in Github."
},
{
"code": null,
"e": 6944,
"s": 6933,
"text": "github.com"
},
{
"code": null,
"e": 7267,
"s": 6944,
"text": "One important thing to note with this design is that, the data and processing is all handled in the local system. Even though we use IBM, it is used as an API service and none of the internal data is sent to IBM. This way the entire design can be implemented in your workplace without having to worry about data transfers."
},
{
"code": null,
"e": 7296,
"s": 7267,
"text": "Step 1 (User asks question):"
},
{
"code": null,
"e": 7417,
"s": 7296,
"text": "Users can interact with Kelly via Slack. Once the user post a question, it is passed to the backend system for analysis."
},
{
"code": null,
"e": 7475,
"s": 7417,
"text": "Step 2 and 3 (NLP processing and Return the NLP results):"
},
{
"code": null,
"e": 7704,
"s": 7475,
"text": "All the natural language processing happens in step 2. This includes IBM Watson processing, similarity search, recommendation based on collaborative filtering. After the NLP processing is completed, we have three outputs from it"
},
{
"code": null,
"e": 7905,
"s": 7704,
"text": "Intents — What the user is trying to ask or query?Entities — What is the exact field or column they are looking for?Dialog/Interaction — Provide the appropriate request/response for the user question."
},
{
"code": null,
"e": 7956,
"s": 7905,
"text": "Intents — What the user is trying to ask or query?"
},
{
"code": null,
"e": 8023,
"s": 7956,
"text": "Entities — What is the exact field or column they are looking for?"
},
{
"code": null,
"e": 8108,
"s": 8023,
"text": "Dialog/Interaction — Provide the appropriate request/response for the user question."
},
{
"code": null,
"e": 8138,
"s": 8108,
"text": "Step 4 and 5(Query the data):"
},
{
"code": null,
"e": 8386,
"s": 8138,
"text": "Currently, the data resides in a excel file. However, you can add multiple databases/excel files if needed, to access different sources. Based on the results from step 3, the appropriate database/excel file is queried and the results are returned."
},
{
"code": null,
"e": 8420,
"s": 8386,
"text": "Step 6 (Post the result to user):"
},
{
"code": null,
"e": 8486,
"s": 8420,
"text": "The results obtained from the backend is posted to user via Slack"
},
{
"code": null,
"e": 8512,
"s": 8486,
"text": "Step 7 (Log maintenance):"
},
{
"code": null,
"e": 8693,
"s": 8512,
"text": "The interactions between the users are logged and stored in a text file. Also, if the bot is not able to identify the user questions it will add those questions to a followup file."
},
{
"code": null,
"e": 8709,
"s": 8693,
"text": "Package Imports"
},
{
"code": null,
"e": 9025,
"s": 8709,
"text": "As usual, we define the program by importing the packages. Notice something, where it says “slack.slack_commands” and “nlp.nlp_commands”. This would import the python program slack_commands and nlp_commands from slack and nlp folder respectively. In addition, a couple of functions from the config file is imported."
},
{
"code": null,
"e": 9050,
"s": 9025,
"text": "Variables Initialization"
},
{
"code": null,
"e": 9189,
"s": 9050,
"text": "User context is maintained in the “context” variable. Once the chat begins, the context variable generated by IBM Watson looks like below,"
},
{
"code": null,
"e": 9497,
"s": 9189,
"text": "{'conversation_id': '76e59c57-8257-4390-ae15-ba75e7576476', 'system': {'_node_output_map': {'node_2_1541443578896': [0]}, 'branch_exited': True, 'branch_exited_reason': 'completed', 'dialog_request_counter': 1, 'dialog_stack': [{'dialog_node': 'root'}], 'dialog_turn_counter': 1, 'initialized': True}}"
},
{
"code": null,
"e": 9696,
"s": 9497,
"text": "It has a “conversation_id” which is used to track the state (previous/present and future state) of conversation flow. During the start of the conversation it is assigned to a empty dictionary value."
},
{
"code": null,
"e": 9907,
"s": 9696,
"text": "In addition to maintaining a conversation, we also should let the bot know when to stop a conversation. This is achieved by the “current_action” variable. An example of the ending a conversation is shown below."
},
{
"code": null,
"e": 10163,
"s": 9907,
"text": "Whenever the user invokes a “Goodbye” intent, the bot assigns ‘end_conversation’ to “current_action” variable. Later in the main.py program, this variable will be evaluated to reassign context, current_action and session_df variables which is shown below."
},
{
"code": null,
"e": 10531,
"s": 10163,
"text": "Another key variable is the “session_df” dataframe. When a user starts a conversation with the bot a session is created. This ensures that the context between a user and the bot is handled on per-user basis. When the same user talks to the bot in multiple channels, they are handled as different sessions. So, there is no overlap in conversation between bot and user."
},
{
"code": null,
"e": 10987,
"s": 10531,
"text": "When a user asks a random question which the bot cannot handle, it will trigger the “follow_ind” to write the question in a follow up text file. During the start of the conversation, it is assigned to 0. The final two variables “bot_id” and “RTM_READ_DELAY” corresponds to slack. When the bot is invoked, the bot_id is assigned. RTM stands for Real Time Messaging. This variable will wait for a second before it reads the next input message from the user."
},
{
"code": null,
"e": 11003,
"s": 10987,
"text": "Invoke the code"
},
{
"code": null,
"e": 11271,
"s": 11003,
"text": "Finally, the rest of the program ensures that the bot is consistently running and looking for input messages from the user. Some of the functions mentioned below — parse_bot_commands, handle_command and output_command will be discussed in detail in the later section."
},
{
"code": null,
"e": 11374,
"s": 11271,
"text": "That’s it. We initiated our Kelly bot. Our next step is to understand the data used for this exercise."
},
{
"code": null,
"e": 11488,
"s": 11374,
"text": "The data for this exercise is taken from the Kaggle link below. The name of the dataset is “movies_metadata.csv”."
},
{
"code": null,
"e": 11503,
"s": 11488,
"text": "www.kaggle.com"
},
{
"code": null,
"e": 11670,
"s": 11503,
"text": "The dataset contains a lot of information related to movies with less preprocessing required from users. We import the dataset using Pandas and then prepare our data."
},
{
"code": null,
"e": 12934,
"s": 11670,
"text": "<class 'pandas.core.frame.DataFrame'>RangeIndex: 45466 entries, 0 to 45465Data columns (total 24 columns):adult 45466 non-null objectbelongs_to_collection 4494 non-null objectbudget 45466 non-null objectgenres 45466 non-null objecthomepage 7782 non-null objectid 45466 non-null objectimdb_id 45449 non-null objectoriginal_language 45455 non-null objectoriginal_title 45466 non-null objectoverview 44512 non-null objectpopularity 45461 non-null objectposter_path 45080 non-null objectproduction_companies 45463 non-null objectproduction_countries 45463 non-null objectrelease_date 45379 non-null objectrevenue 45460 non-null float64runtime 45203 non-null float64spoken_languages 45460 non-null objectstatus 45379 non-null objecttagline 20412 non-null objecttitle 45460 non-null objectvideo 45460 non-null objectvote_average 45460 non-null float64vote_count 45460 non-null float64dtypes: float64(4), object(20)memory usage: 8.3+ MB"
},
{
"code": null,
"e": 13667,
"s": 12934,
"text": "adult 0belongs_to_collection 40972budget 0genres 0homepage 37684id 0imdb_id 17original_language 11original_title 0overview 954popularity 5poster_path 386production_companies 3production_countries 3release_date 87revenue 6runtime 263spoken_languages 6status 87tagline 25054title 6video 6vote_average 6vote_count 6dtype: int64"
},
{
"code": null,
"e": 13914,
"s": 13667,
"text": "It turns out there are a lot of missing values in the data. So we remove the variables with high missing value percentage. Also, I removed a few other variables to keep the data simple. The code below is used to remove variables from the dataset."
},
{
"code": null,
"e": 14079,
"s": 13914,
"text": "“imdb_id” and “poster_path” variable had missing values in them. I had to remove the observations which had missing values for these variables using the code below."
},
{
"code": null,
"e": 14136,
"s": 14079,
"text": "Now, let us look at the genres variables in the dataset."
},
{
"code": null,
"e": 14265,
"s": 14136,
"text": "The genre name is stored in a list of dictionaries format. To make it a clean format, we need to apply a preparation code below."
},
{
"code": null,
"e": 14373,
"s": 14265,
"text": "Pretty nice format right. Now let us move to our final step of creating the IMDB, TMDB and Image url links."
},
{
"code": null,
"e": 14480,
"s": 14373,
"text": "Voila. We are done with the data preparation and finally export the prepared dataset using the code below."
},
{
"code": null,
"e": 14517,
"s": 14480,
"text": "metadata.to_csv('metadata_prep.csv')"
},
{
"code": null,
"e": 14586,
"s": 14517,
"text": "The entire data preparation code is available in the notebook below."
},
{
"code": null,
"e": 14597,
"s": 14586,
"text": "github.com"
},
{
"code": null,
"e": 14699,
"s": 14597,
"text": "That’s it. This concludes the data preparation process. Our next step is to understand slack process."
},
{
"code": null,
"e": 15056,
"s": 14699,
"text": "Okay, now it is time to understand the slack process and how it is handled in the framework. The first step is to create a slack bot and install it in the workspace. The link below will guide you to create the slack app. In the configuration file, you need to edit the Slack Bot token and Slack verification token. That is all the setup required for slack."
},
{
"code": null,
"e": 15067,
"s": 15056,
"text": "github.com"
},
{
"code": null,
"e": 15118,
"s": 15067,
"text": "There are 6 slack functions written for Kelly bot."
},
{
"code": null,
"e": 15208,
"s": 15118,
"text": "parse_bot_commandsparse_direct_mentionoutput_commandfile_uploadslack_tilesmessage_buttons"
},
{
"code": null,
"e": 15227,
"s": 15208,
"text": "parse_bot_commands"
},
{
"code": null,
"e": 15248,
"s": 15227,
"text": "parse_direct_mention"
},
{
"code": null,
"e": 15263,
"s": 15248,
"text": "output_command"
},
{
"code": null,
"e": 15275,
"s": 15263,
"text": "file_upload"
},
{
"code": null,
"e": 15287,
"s": 15275,
"text": "slack_tiles"
},
{
"code": null,
"e": 15303,
"s": 15287,
"text": "message_buttons"
},
{
"code": null,
"e": 15353,
"s": 15303,
"text": "Let us look into each of the functions in detail."
},
{
"code": null,
"e": 15372,
"s": 15353,
"text": "parse_bot_commands"
},
{
"code": null,
"e": 16198,
"s": 15372,
"text": "When the user types a message in slack, the parse_bot_commands function is invoked. In slack, the Real Time Messaging(RTM) events (slack_events) stores all the information about a particular user conversation. This includes who is asking this question (message_user), which team and channel are they using (team, channel), what is the message or question from the user (message) and are they talking to someone else or the bot (user_id). Because, in slack a user can talk to different users by invoking @ symbol in front of the user name. For example — “@person1 show me the movie Toy Story” and “@Kelly show me the movie Toy Story” are different. The first one is directed to person1 and second one is directed to Kelly bot. Here, the bot will process a user message or question only when the “user_id” matches the “bot_id”."
},
{
"code": null,
"e": 16219,
"s": 16198,
"text": "parse_direct_mention"
},
{
"code": null,
"e": 16583,
"s": 16219,
"text": "This is a sub function of parse_bot_commands. The question from the user “@Kelly show me the movie Toy Story” has two parts. The first part is the bot user name “@Kelly” and the second is the question from the user “show me the movie Toy Story”. This function takes the text from slack events (message_text) and separates the user question from the bot user name."
},
{
"code": null,
"e": 16598,
"s": 16583,
"text": "output_command"
},
{
"code": null,
"e": 16872,
"s": 16598,
"text": "The output command is used to send the responses back to slack. This function only supports text output (slack_output). The “channel” variable is used to identify the slack channel from which the user is posting the question and use the same channel to direct the response."
},
{
"code": null,
"e": 16961,
"s": 16872,
"text": "In Kelly bot, the slack output produced by the output command function looks like below."
},
{
"code": null,
"e": 16973,
"s": 16961,
"text": "file_upload"
},
{
"code": null,
"e": 17215,
"s": 16973,
"text": "File upload can be used to upload files to slack. File upload function supports multiple document types. A few among them would include PDF, Word, Excel, gifs, png etc. The complete list of supported file types can be seen in the link below."
},
{
"code": null,
"e": 17229,
"s": 17215,
"text": "api.slack.com"
},
{
"code": null,
"e": 17323,
"s": 17229,
"text": "This function is not used in Kelly Bot. However it is provided here as an additional feature."
},
{
"code": null,
"e": 17335,
"s": 17323,
"text": "slack_tiles"
},
{
"code": null,
"e": 17500,
"s": 17335,
"text": "Slack tiles are another way of displaying outputs to user in Slack. I used this function to show movie recommendations. The output of the function looks like below."
},
{
"code": null,
"e": 17803,
"s": 17500,
"text": "Pretty cool right. The images are represented using tiles so that the user attention is immediately grabbed. When you look closer, the movie names are hyperlinked. So when you click on the movie names, it redirects you to the IMDB movie page. Again, a simple and elegant way to display output in slack."
},
{
"code": null,
"e": 17832,
"s": 17803,
"text": "The function takes 5 inputs."
},
{
"code": null,
"e": 18894,
"s": 17832,
"text": "The “channel” variable as discussed before is used to post to the corresponding channel where the user is asking question.The “search_term” variable has the value “Toy Story”. Since I started my bot conversation with the question “show me the movie Toy Story”, the movie name is automatically stored in search_term and the context is maintained each time the user asks questions until the user starts over. Since the context is retained, when I asked the question “recommend me movies similar to this one” it responded in the first line saying “Recommendation for Toy Story”.The “title” variable has the movie title recommendations. Based on the highest scores obtained in the collaborative filtering method(which will be discussed later in Part5:Custom NLP solutions), it chooses the titles and stores them in a python list. This list is then processed in the function while displaying the output.The “title_url” has the corresponding IMDB links for the movie recommendationsThe “image_url” has the corresponding TMDB image links for the movie recommendations."
},
{
"code": null,
"e": 19017,
"s": 18894,
"text": "The “channel” variable as discussed before is used to post to the corresponding channel where the user is asking question."
},
{
"code": null,
"e": 19471,
"s": 19017,
"text": "The “search_term” variable has the value “Toy Story”. Since I started my bot conversation with the question “show me the movie Toy Story”, the movie name is automatically stored in search_term and the context is maintained each time the user asks questions until the user starts over. Since the context is retained, when I asked the question “recommend me movies similar to this one” it responded in the first line saying “Recommendation for Toy Story”."
},
{
"code": null,
"e": 19795,
"s": 19471,
"text": "The “title” variable has the movie title recommendations. Based on the highest scores obtained in the collaborative filtering method(which will be discussed later in Part5:Custom NLP solutions), it chooses the titles and stores them in a python list. This list is then processed in the function while displaying the output."
},
{
"code": null,
"e": 19874,
"s": 19795,
"text": "The “title_url” has the corresponding IMDB links for the movie recommendations"
},
{
"code": null,
"e": 19960,
"s": 19874,
"text": "The “image_url” has the corresponding TMDB image links for the movie recommendations."
},
{
"code": null,
"e": 19976,
"s": 19960,
"text": "message_buttons"
},
{
"code": null,
"e": 20637,
"s": 19976,
"text": "Message buttons are also a different style of displaying output in Slack. This is similar to slack tiles except that it wont have the images to display. Rather, the output contains buttons that are tied to IMDB links. This features is used in the start, when the user is trying to search a movie. I don’t remember all the movie names that I watched on the top of my head. So, I use keyword based movie search and this functionality is also implemented in the same way. The NLP program that handles the keyword based search (Similarity Search) will be discussed later in Part5:Custom NLP solutions. However, I wanted to show how this works with message buttons."
},
{
"code": null,
"e": 21110,
"s": 20637,
"text": "Here, when I began the movie search I did not mention “Toy Story” rather I started the conversation as “I am looking for a movie with a toy” and it gave me “Toy Story” as my 5th option. This type of search is called similarity search. Now, the user can click on button to ensure whether the movie they are looking for is the same and then proceed next. The button names are stored in the “button” variable and the corresponding IMDB links are stored in the “url” variable."
},
{
"code": null,
"e": 21232,
"s": 21110,
"text": "That’s it. This concludes the slack process. Our next step is to understand Natural language processing using IBM Watson."
},
{
"code": null,
"e": 21788,
"s": 21232,
"text": "A quick and easy way to develop chatbots is to use frameworks. There are lot of frameworks in the market, that can assist us to build bots. A few of them include — IBM Watson, Luis, Wit, Dialogflow, Rasa NLU, Botkit, Microsoft Bot Framework and so on. You can chose any one of the framework to build your bots. Again, the complexity of coding might vary depending upon the framework you choose. For this exercise, I used IBM Watson framework. The link below will assist you to create a Watson User account and getting started with IBM Watson conversation."
},
{
"code": null,
"e": 21799,
"s": 21788,
"text": "github.com"
},
{
"code": null,
"e": 22230,
"s": 21799,
"text": "IBM Watson framework is used as an API service to perform Natural language processing. Kelly bot is built in such a way that none of the information is stored in IBM Watson. All the processing of information is happening in your local system. Only the question from the user is processed by IBM Watson service to provide the Intents, Entities, Dialog and Response. Other than that, none of the information is stored in IBM Watson."
},
{
"code": null,
"e": 22314,
"s": 22230,
"text": "These quick courses can get you started with building Intents, Entities and Dialog."
},
{
"code": null,
"e": 22331,
"s": 22314,
"text": "www.coursera.org"
},
{
"code": null,
"e": 22349,
"s": 22331,
"text": "developer.ibm.com"
},
{
"code": null,
"e": 22572,
"s": 22349,
"text": "For this exercise, you can upload the “bot.json” file that comes with the code in Github and import it to your IBM Watson conversation account to get started. Once you import the json file, the page should look like below."
},
{
"code": null,
"e": 22580,
"s": 22572,
"text": "Intents"
},
{
"code": null,
"e": 22589,
"s": 22580,
"text": "Entities"
},
{
"code": null,
"e": 22752,
"s": 22589,
"text": "I wanted to talk about a few things on how the connection is established between Watson, Slack and your python code. So, let us take a look at the entities first."
},
{
"code": null,
"e": 22925,
"s": 22752,
"text": "Here, look at the option entity. It can take only 5 possible values. If you can recall in the slack process, we used message buttons to get the movie name option from user."
},
{
"code": null,
"e": 22932,
"s": 22925,
"text": "Dialog"
},
{
"code": null,
"e": 23197,
"s": 22932,
"text": "Let us say, if the user selects 6 instead of 5. The bot would then respond saying “Please provide a valid option — 1, 2, 3, 4 or 5”. This is established using the Dialog feature in IBM Watson. So let us look at this feature. The Dialog page should look like below."
},
{
"code": null,
"e": 23497,
"s": 23197,
"text": "We start the conversation by saying “hello”. The Watson would recognize this as “hello” intent, assigns the value “hello” to context variable “currentIntent”. In addition, it sends the response back to python code “Please enter a movie name to begin” and then jumps to evaluate movie name condition."
},
{
"code": null,
"e": 23576,
"s": 23497,
"text": "In the movie name condition evaluation, I have two child nodes as shown below."
},
{
"code": null,
"e": 23783,
"s": 23576,
"text": "The first child node evaluates whether a user has provided response. In IBM Watson, this is captured using “<?input_text?>” option. And then the bot responds to user to select a movie option as shown below."
},
{
"code": null,
"e": 23923,
"s": 23783,
"text": "Finally, based on the user option, it evaluates whether the option is a valid. If not, it would request the user to provide a valid option."
},
{
"code": null,
"e": 24020,
"s": 23923,
"text": "The corresponding slack interface interaction for this Watson conversation setup is shown below."
},
{
"code": null,
"e": 24035,
"s": 24020,
"text": "Python backend"
},
{
"code": null,
"e": 24118,
"s": 24035,
"text": "In the python end, this is established by the handle_command function shown below."
},
{
"code": null,
"e": 24730,
"s": 24118,
"text": "When the IBM Watson API service is used, it returns a response which is captured in the “response” variable. Notice we pass the context variable to Watson service each time. This is used to maintain the context for the bot responses. Also, using the response variable we extract the context, entities and the bot response and assign them to “context”, “search_key” and “slack_output” respectively. The “search_term” variable contains the movie name corresponding to user selection. For now, I hope this gives a picture of how the interactions happen between the IBM Watson front end and the backend python code."
},
{
"code": null,
"e": 24870,
"s": 24730,
"text": "That’s it. This concludes this part — NLP using IBM Watson . Our next step is to understand the Custom NLP solutions written for Kelly bot."
},
{
"code": null,
"e": 25122,
"s": 24870,
"text": "Often times, we need to add extra NLP capabilities to enhance the bot skills. Well, this is your time to become more creative and start adding customized solutions. I added two custom solutions for Kelly Bot. (Located in the nlp/nlp_solutions folder)."
},
{
"code": null,
"e": 25243,
"s": 25122,
"text": "Metadata based Collaborative filtering for movie recommendationCosine similarity search for identifying the movie titles"
},
{
"code": null,
"e": 25307,
"s": 25243,
"text": "Metadata based Collaborative filtering for movie recommendation"
},
{
"code": null,
"e": 25365,
"s": 25307,
"text": "Cosine similarity search for identifying the movie titles"
},
{
"code": null,
"e": 25472,
"s": 25365,
"text": "The codes for both the function resides in “nlplearn.py” and “onetime_run_file.py”. So let us get started."
},
{
"code": null,
"e": 25492,
"s": 25472,
"text": "onetime_run_file.py"
},
{
"code": null,
"e": 25980,
"s": 25492,
"text": "This function has codes that we need to run onetime before we initiate the Kelly bot. This onetime setup makes it easier in situations when the data is changing constantly and the bot needs to adapt to these data changes quickly. All we need to do is to run this file whenever we need without changing any of the internal functions in the bot. Pretty cool right. When the file run is completed, it generates a “onetime.txt” pickle file which will be used by the bot when it is initiated."
},
{
"code": null,
"e": 26061,
"s": 25980,
"text": "Now, let’s discuss the functions available in “nlplearn.py”. It has 5 functions,"
},
{
"code": null,
"e": 26273,
"s": 26061,
"text": "text_preparetfidf_fit (Cosine similarity search)similarity_search (Cosine similarity search)metadata_filtering (Metadata based Collaborative filtering)get_recommendations (Metadata based Collaborative filtering)"
},
{
"code": null,
"e": 26286,
"s": 26273,
"text": "text_prepare"
},
{
"code": null,
"e": 26323,
"s": 26286,
"text": "tfidf_fit (Cosine similarity search)"
},
{
"code": null,
"e": 26368,
"s": 26323,
"text": "similarity_search (Cosine similarity search)"
},
{
"code": null,
"e": 26428,
"s": 26368,
"text": "metadata_filtering (Metadata based Collaborative filtering)"
},
{
"code": null,
"e": 26489,
"s": 26428,
"text": "get_recommendations (Metadata based Collaborative filtering)"
},
{
"code": null,
"e": 26502,
"s": 26489,
"text": "text_prepare"
},
{
"code": null,
"e": 26797,
"s": 26502,
"text": "This function takes in a single document (“show me ? movie title ` similar to Toy Story######”) and prepares the text by removing spaces and bad characters. In addition, it also removes stop words from the text. The processed text looks something like this “show movie title similar toy story”."
},
{
"code": null,
"e": 26807,
"s": 26797,
"text": "tfidf_fit"
},
{
"code": null,
"e": 27154,
"s": 26807,
"text": "This function takes the prepared text from step 1 and creates a tfidf fit. ‘tf’ means Term Frequency and ‘Idf’ means Inverse document frequency. You can read about tdidf in the link here. After the fit is completed, the fit and matrix gets stored in a pickle file for future processing. This is accomplished by the codes in “onetime_run_file.py”."
},
{
"code": null,
"e": 27172,
"s": 27154,
"text": "similarity_search"
},
{
"code": null,
"e": 27644,
"s": 27172,
"text": "This function computes cosine similarity between the user query and the movie titles stored in the tfidf_matrix created by the tfidf_fit function. First, it performs a tfidf_fit on the user query and then it computes the cosine distance between the fit and the elements in the tfidf_matrix. The top 5 elements which has the highest cosine similarity score is chosen and sent back to slack interface. This is used in the message buttons in Slack which we discussed before."
},
{
"code": null,
"e": 27663,
"s": 27644,
"text": "metadata_filtering"
},
{
"code": null,
"e": 27975,
"s": 27663,
"text": "This function performs metadata based collaborative filtering which is used for movie recommendations. You can read about this function in the link here. The final “cosine_sim” function gets stored in the pickle file for future processing. Again, this is also accomplished by the codes in “onetime_run_file.py”."
},
{
"code": null,
"e": 27995,
"s": 27975,
"text": "get_recommendations"
},
{
"code": null,
"e": 28196,
"s": 27995,
"text": "This function is used to get movie recommendation based on the user search. It returns 3 similar movies and sends back to slack interface. This result is used in slack tiles which we discussed before."
},
{
"code": null,
"e": 28264,
"s": 28196,
"text": "Now, let us see how these custom NLP solutions looks like in Slack."
},
{
"code": null,
"e": 28347,
"s": 28264,
"text": "Reference: https://www.datacamp.com/community/tutorials/recommender-systems-python"
},
{
"code": null,
"e": 28459,
"s": 28347,
"text": "That’s it. This concludes this part — Custom NLP solutions. Our next step is to understand the logs processing."
},
{
"code": null,
"e": 28631,
"s": 28459,
"text": "As of now, we have implemented all the features that is needed to run the bot. So why do we need to talk about logs? What importance does log files bring to bot framework?"
},
{
"code": null,
"e": 29270,
"s": 28631,
"text": "Let us see an example to illustrate its importance. Suppose we have a “feedback” intent and the example user queries in the intent include “I am satisfied with your service”, “I don’t like your service”,”You are awesome”, “You are a disaster” and so on. We only provide a few example when we develop this intent. In future, let us say a user says “boo”. We know that this should be categorized as “feedback” intent. However, our bot is not trained on this response. So it would show it as some other intent resulting in bad user experience. Also, these type of user responses come at random and we need a way to identify and capture them."
},
{
"code": null,
"e": 29546,
"s": 29270,
"text": "The easiest way to collect user queries is via logs. So in the future, if a user asks a question different from the way we defined our intents, we can capture those responses and include them in the intents model training. This way we improve the overall customer experience."
},
{
"code": null,
"e": 29605,
"s": 29546,
"text": "In this bot framework, we have two types of log processing"
},
{
"code": null,
"e": 29628,
"s": 29605,
"text": "Log fileFollow up file"
},
{
"code": null,
"e": 29637,
"s": 29628,
"text": "Log file"
},
{
"code": null,
"e": 29652,
"s": 29637,
"text": "Follow up file"
},
{
"code": null,
"e": 29661,
"s": 29652,
"text": "Log file"
},
{
"code": null,
"e": 29699,
"s": 29661,
"text": "The output log file looks like below."
},
{
"code": null,
"e": 30000,
"s": 29699,
"text": "As we see here, all the information is captured which makes it easier for future user query processing. Also, it includes the processing time in the log file (second to the last column). Using, this input we can optimize queries which takes more time to process and thus improving the bot efficiency."
},
{
"code": null,
"e": 30015,
"s": 30000,
"text": "Follow up file"
},
{
"code": null,
"e": 30307,
"s": 30015,
"text": "The follow up file is also generated as a part of the log file processing. If the bot is not able to assign any intent to the user query (“Anything_else” intent) then the “follow_ind” is invoked. This will write the user query in a new file called ‘followup_file.TXT’ which looks like below."
},
{
"code": null,
"e": 30385,
"s": 30307,
"text": "This file can be later sent to bot developers via email using the code below."
},
{
"code": null,
"e": 30440,
"s": 30385,
"text": "That’s it. This concludes this part — Logs processing."
},
{
"code": null,
"e": 30566,
"s": 30440,
"text": "I assume if you are still reading this article, you have successfully completed this exercise. Great job! Ok, so what’s next?"
},
{
"code": null,
"e": 31078,
"s": 30566,
"text": "As I said before, we can experiment by adding new bot features, extending the NLP capabilities and also implement the bot in other messaging platforms. The central idea around this framework is — all the work done can be reused if you need to change platforms and also for easy addition/extension of skills. That being said, I cannot cover all the possible options for you as the application of bots can vary depending upon the user requirements. So it is up to the you to explore and implement them. Good luck!"
},
{
"code": null,
"e": 31176,
"s": 31078,
"text": "If you are looking to build some AI/Machine learning based chatbots then refer these links below."
},
{
"code": null,
"e": 31210,
"s": 31176,
"text": "ethancaballero.pythonanywhere.com"
},
{
"code": null,
"e": 31231,
"s": 31210,
"text": "chatbotsmagazine.com"
},
{
"code": null,
"e": 31242,
"s": 31231,
"text": "github.com"
}
] |
How to set the width of an element's border with JavaScript?
|
To set the width of an element’s border in JavaScript, use the borderWidth property. Set the width using this property.
You can try to run the following code to learn how to set the width of an element’s border −
<!DOCTYPE html>
<html>
<head>
<style>
#box {
border: thick solid gray;
width: 300px;
height: 200px
}
</style>
</head>
<body>
<div id = "box">Demo Text</div>
<br>
<br>
<button type = "button" onclick = "display()">Change border width</button>
<script>
function display() {
document.getElementById("box").style.borderWidth = "thin";
}
</script>
</body>
</html>
|
[
{
"code": null,
"e": 1182,
"s": 1062,
"text": "To set the width of an element’s border in JavaScript, use the borderWidth property. Set the width using this property."
},
{
"code": null,
"e": 1275,
"s": 1182,
"text": "You can try to run the following code to learn how to set the width of an element’s border −"
},
{
"code": null,
"e": 1796,
"s": 1275,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n #box {\n border: thick solid gray;\n width: 300px;\n height: 200px\n }\n </style>\n </head>\n \n <body>\n <div id = \"box\">Demo Text</div>\n <br>\n <br>\n \n <button type = \"button\" onclick = \"display()\">Change border width</button>\n <script>\n function display() {\n document.getElementById(\"box\").style.borderWidth = \"thin\";\n }\n </script>\n \n </body>\n</html>"
}
] |
An Introduction to Making Scientific Publication Plots with Python | by Naveen Venkatesan | Towards Data Science
|
I have been using Python to do scientific computations and make all of my plots for several years now. My primary motivations have been that (1) Python is open source, and (2) the amount of hard drive space taken up by MATLAB (especially on my laptop, where HD space comes at a premium). Also, never having to worry about keeping software licenses up to date has been an added plus. The flurry of trial-and-errors and Google searches I had to conduct until I found the “perfect” parameters for my plots has led me to put together this article — both as an informative tool for outside readers, and a way for me to document things for myself. Aesthetics are subjective, but I hope this tutorial can point out important settings and parameters that will allow you to customize any dataset to your personal preference. This is the first article in what I hope to be a series of tutorials — I will continue adding sections over time for different types of visualizations. I would recommend installing Anaconda if you don’t already have it as it contains all required packages for data analysis and visualization that you will need.
The majority of the functions used are in the matplotlib package (with most of the plotting functions being from matplotlib.pyplot subpackage). Additionally, I typically import numpy for any quick computations and pylab for quickly generating colors from any built-in colormap. Often times, when we import packages, we create a short-form alias (i.e. mpl for matplotlib ) so that we can refer to its functions using the alias instead of typing out matplotlib every single time.
# Import required packagesimport matplotlib as mplimport matplotlib.pyplot as pltimport numpy as npfrom pylab import cm
Since scientific instrument data is typically fairly simple (usually just one independent variable that we control and a measured, dependent variable), we can use numpy.loadtxt to import our data. For more complicated datasets, I highly recommend using pandas , which has incredibly sophisticated functions for loading and sanitizing data for visualizations — a comprehensive documentation can be found here. For this example, I have a file called Absorbance_Data.csv with some absorbance data for two samples collected on a spectrophotometer.
We can load this data into our script with the following command:
# Use numpy.loadtxt to import our datawavelength, samp_1_abs, samp_2_abs = np.loadtxt('Absorbance_Data.csv', unpack=True, delimiter=',', skiprows=1)
We pass our file to the numpy.loadtxt function along with the parameters:
unpack— transposes each column into an array, allowing you to unpack multiple variables at a time ( wavelength , samp_1_abs , samp_2_abs )
delimiter — delimiter character used to separate columns
skiprows — amount of rows to skip at the top of the file (since the first row is the column titles, we want to skip this so skiprows=1 )
Once we have loaded our absorbance data, we can quickly plot and inspect both of the datasets with the following code:
# Create figure and add axes objectfig = plt.figure()ax = fig.add_axes([0, 0, 1, 1])# Plot and show our dataax.plot(wavelength, samp_1_abs)ax.plot(wavelength, samp_2_abs)plt.show()
The data plots properly, but the default matplotlib settings just don’t give the figure that publication quality. As we change some of the parameters below, we will end up with a much better looking plot.
This is a setting that I spend an irrationally large amount of time on — picking the right font for my plots. Your system already comes with a long list of pre-installed fonts, and you can check which fonts are already available to matplotlib with the following:
import matplotlib.font_manager as fm# Collect all the font names available to matplotlibfont_names = [f.name for f in fm.fontManager.ttflist]print(font_names)
If you would like to install a new font to your computer and then use it for your plots, this is also possible. First, you must download and install your desired font — many options can be found here. Once installed, you must rebuild the font cache so that it will be available to matplotlib when you make your figure. We do this as follows:
import matplotlib.font_manager as fm# Rebuild the matplotlib font cachefm._rebuild()
If you now check the list of available fonts, you should see the new font that you just installed.
The three general parameters that I set at the beginning of my plot script are: (1) font, (2) font size, and (3) axis line width. These are essentially global parameters that I do not edit later so setting them at the beginning makes everything easier (i.e. do not have to explicitly set font/sizes for each label down the line). We must add the following code before we generate any figures, so I typically put it near the top of the script immediately after importing packages.
# Edit the font, font size, and axes widthmpl.rcParams['font.family'] = 'Avenir'plt.rcParams['font.size'] = 18plt.rcParams['axes.linewidth'] = 2
If you have a set of colors that you like to use, you are free to skip this step. In this case, since we only have two samples, it is better to manually select two high-constrast colors. But, if you want to generate a list of colors without too much effort on your end, we can use the pylab package we imported to generate a list of them from one of the various matplotlib built-in colormaps, which can be found here. This becomes very useful when you need a large number of colors, as you can generate them programatically.
For our dataset, we are just interested in easily distinguishing between our traces, so we would be best served using one of the colormaps in the qualitative section (I will use “tab10” for this example). We use the following code — the first argument is the colormap name and the second is the number of colors we want to generate:
# Generate 2 colors from the 'tab10' colormapcolors = cm.get_cmap('tab10', 2)
If we were, for example, measuring the temperature-dependence of a single sample and wanted to plot the spectra at different temperatures, we could use a diverging colormap such as “coolwarm”. Ultimately, the colormap you choose will be up to you and based on the type of data you are plotting.
We must create a figure, which is a blank window, and then add an axes object to it for our plot. To generate the figure, we have the following:
# Create figure object and store it in a variable called 'fig'fig = plt.figure(figsize=(3, 3))
figsize — size of our figure (width, height) in inches, with the default being (6.4, 4.8)
Now we must add an axes object to our blank figure by specifying the bottom left coordinate and the width and height in relative coordinates (1 is the full size of the figure window). If we want it to fill our entire figure, we can specify [0, 0, 1, 1] which sets the bottom left corner to (0, 0) and the width and height to 1.
# Add axes object to our figure that takes up entire figureax = fig.add_axes([0, 0, 1, 1])
We can use this axis construction to create paneled figures and insets by making multiple axes objects as follows:
# Add two axes objects to create a paneled figureax1 = fig.add_axes([0, 0, 1, 0.4])ax2 = fig.add_axes([0, 0.6, 1, 0.4])
# Add two axes objects to create an inset figureax1 = fig.add_axes([0, 0, 1, 1])ax2 = fig.add_axes([0.5, 0.5, 0.4, 0.4])
If we do not want our plot entirely enclosed, we can remove the top and right spines as follows:
# Hide the top and right spines of the axisax.spines['right'].set_visible(False)ax.spines['top'].set_visible(False)
We can edit the tick widths and lengths to match our axis parameters with the following code. If we have minor ticks, we can also edit the properties of these:
# Edit the major and minor ticks of the x and y axesax.xaxis.set_tick_params(which='major', size=10, width=2, direction='in', top='on')ax.xaxis.set_tick_params(which='minor', size=7, width=2, direction='in', top='on')ax.yaxis.set_tick_params(which='major', size=10, width=2, direction='in', right='on')ax.yaxis.set_tick_params(which='minor', size=7, width=2, direction='in', right='on')
which — whether we are editing major , minor , or both ticks
size — length of ticks in points
width — line width of ticks (we can set this to the same as our axis line width)
direction — whether ticks will face in , out , or inout (both)
top / right — whether there will be ticks on the secondary axes (top/right)
We can now again plot our data, using the colors that we generated from the colormap to distinguish the samples:
# Plot the two sample absorbances, using previously generated colorsax.plot(wavelength, samp_1_abs, linewidth=2, color=colors(0), label='Sample 1')ax.plot(wavelength, samp_2_abs, linewidth=2, color=colors(1), label='Sample 2')
linewidth — line width of the line in the plot
color — color of the line in the plot
label — label for the trace (reference for the legend)
Now we can set the x and y-axis ranges with the following lines:
# Set the axis limitsax.set_xlim(370, 930)ax.set_ylim(-0.2, 2.2)
We notice that the tick marks seem unbalanced between the two axes — we can also semi-manually edit this using a function called MultipleLocator which will create ticks at every multiple of a base number that we provide. We must edit the major_locator for the major ticks and minor_locator for the minor ticks. We will set major ticks every 100 nm and minor ticks every 50 nm for the x-axis and major ticks every 0.5 and minor ticks every 0.25 for the y-axis.
# Edit the major and minor tick locationsax.xaxis.set_major_locator(mpl.ticker.MultipleLocator(100))ax.xaxis.set_minor_locator(mpl.ticker.MultipleLocator(50))ax.yaxis.set_major_locator(mpl.ticker.MultipleLocator(0.5))ax.yaxis.set_minor_locator(mpl.ticker.MultipleLocator(0.25))
We must add labels to the x and y-axes, which we can easily do with the following code:
# Add the x and y-axis labelsax.set_xlabel('Wavelength (nm)', labelpad=10)ax.set_ylabel('Absorbance (O.D.)', labelpad=10)
labelpad — extra padding between the tick labels and the axis label
If you want to include Greek characters in your labels, you can use LaTeX syntax to do so. We create a raw string by prepending the string with r and enclose the LaTeX command with $$ . However, this will use the default LaTeX font for the Greek characters — if we want to use the same font as the rest of the plot (assuming the character exists), we enclose our command with $\mathregular{'Command goes here'}$.
# Add the x-axis label with λ for wavelengthax.set_xlabel(r'$\mathregular{\lambda}$ (nm)', labelpad=10)
If we want to place ticks on one of the secondary (top/right) axes to show either a different dataset or scaling, we can do so using a parasitic axis. This axes object duplicates one of the axes of the original plot, allowing you to change the scaling on the other. To illustrate this, we can use our absorbance data as an example. The current x-axis is the wavelength of absorbed light, but based on the application, the energy of this light might be the more relevant parameter.
We can create a second x-axis on the top of the plot to show the energy scaling. First, we must create a parasitic axis with either the twinx() or twiny() command to clone the x or y-axes, respectively. In this example, we want the y-axis data constant, so we will clone the y-axis. We also need to match the tick parameters of this new x-axis to the old plot’s x-axis (and remove top='on' from the original x-axis parameters).
# Create new axes object by cloning the y-axis of the first plotax2 = ax.twiny()# Edit the tick parameters of the new x-axisax2.xaxis.set_tick_params(which='major', size=10, width=2, direction='in')ax2.xaxis.set_tick_params(which='minor', size=7, width=2, direction='in')
To make our job of adding ticks in energy units to this axis easier, we can write a function to convert energy to wavelength (since we will place the ticks on the wavelength axis at points that energy values would correspond to). We will treat the input E as an array so we can do all the conversions at once:
# Function to convert energy (eV) to wavelength (nm)def E_to_WL(E): return [1240/i for i in E]
Since this is a non-linear transformation, we cannot easily use the MultipleLocator function, and we will add the tick marks manually, using a function called FixedLocator . To use FixedLocator we provide an array of all the locations at which we want there to be tick marks:
# Add ticks manually to energy axisax2.xaxis.set_major_locator(mpl.ticker.FixedLocator(E_to_WL(np.linspace(1.5, 3.0, 4))))ax2.xaxis.set_minor_locator(mpl.ticker.FixedLocator(E_to_WL(np.linspace(1.4, 3.2, 19))))
Since we added the ticks manually, we must also add the major tick labels manually.
# Add tick labels manually to energy axisax2.set_xticklabels(['1.5', '2.0', '2.5', '3.0'])
Finally, we also want to add an axis label to our new x-axis and make sure the axis limits are the same as the original x-axis:
# Add energy axis labelax2.set_xlabel('Energy (eV)', labelpad=10)# Set energy axis limitsax2.set_xlim(370, 930)
The final thing we must add to our plot is a legend, so that a reader can know which trace corresponds to which sample. To do so, we can use the following code:
# Add legend to plotax.legend(bbox_to_anchor=(1, 1), loc=1, frameon=False, fontsize=16)
bbox_to_anchor — coordinate of the bounding box for our legend
loc — which part of the bounding box to use the coordinate of the bbox_to_anchor value ( 0 for automatic, 1 for top right corner, 2 for top left corner, 3 for bottom left corner, 4 for bottom right corner, 5 for right, 6 for center left, 7 for center right, 8 for lower center, 9 for upper center, and 10 for center)
frameon — whether to draw a frame around the legend
fontsize — font size for legend entries (if different from general parameter)
Lastly, saving your final plot is very simple — we can use the function plt.savefig to do this.
# Save figureplt.savefig('Final_Plot.png', dpi=300, transparent=False, bbox_inches='tight')
dpi — resolution for a rastered image file format (in this case we are saving as .png file so this means that we are saving with a resolution of 300 dots per inch. The other possible file formats you can save are .ps , .pdf , and .svg which are all vector graphics formats, in which case you do not need to specify a dpi value)
transparent — whether to make the figure transparent, or with a white background
bbox_inches — defines the bounding box around the figure ( tight ensures that there is no extra whitespace around the figure)
To actually view our final plot in a figure window, we must add a plt.show() command after saving the figure.
# Show figureplt.show()
That’s it! We have successfully made a publication quality plot using Python! This example and all subsequent examples will be freely available online at this Github repository.
Thanks for reading and I will continue to keep this series up to date with new examples and tutorials! You can follow me on Twitter or connect with me on LinkedIn for more articles and updates.
|
[
{
"code": null,
"e": 1299,
"s": 171,
"text": "I have been using Python to do scientific computations and make all of my plots for several years now. My primary motivations have been that (1) Python is open source, and (2) the amount of hard drive space taken up by MATLAB (especially on my laptop, where HD space comes at a premium). Also, never having to worry about keeping software licenses up to date has been an added plus. The flurry of trial-and-errors and Google searches I had to conduct until I found the “perfect” parameters for my plots has led me to put together this article — both as an informative tool for outside readers, and a way for me to document things for myself. Aesthetics are subjective, but I hope this tutorial can point out important settings and parameters that will allow you to customize any dataset to your personal preference. This is the first article in what I hope to be a series of tutorials — I will continue adding sections over time for different types of visualizations. I would recommend installing Anaconda if you don’t already have it as it contains all required packages for data analysis and visualization that you will need."
},
{
"code": null,
"e": 1777,
"s": 1299,
"text": "The majority of the functions used are in the matplotlib package (with most of the plotting functions being from matplotlib.pyplot subpackage). Additionally, I typically import numpy for any quick computations and pylab for quickly generating colors from any built-in colormap. Often times, when we import packages, we create a short-form alias (i.e. mpl for matplotlib ) so that we can refer to its functions using the alias instead of typing out matplotlib every single time."
},
{
"code": null,
"e": 1897,
"s": 1777,
"text": "# Import required packagesimport matplotlib as mplimport matplotlib.pyplot as pltimport numpy as npfrom pylab import cm"
},
{
"code": null,
"e": 2441,
"s": 1897,
"text": "Since scientific instrument data is typically fairly simple (usually just one independent variable that we control and a measured, dependent variable), we can use numpy.loadtxt to import our data. For more complicated datasets, I highly recommend using pandas , which has incredibly sophisticated functions for loading and sanitizing data for visualizations — a comprehensive documentation can be found here. For this example, I have a file called Absorbance_Data.csv with some absorbance data for two samples collected on a spectrophotometer."
},
{
"code": null,
"e": 2507,
"s": 2441,
"text": "We can load this data into our script with the following command:"
},
{
"code": null,
"e": 2656,
"s": 2507,
"text": "# Use numpy.loadtxt to import our datawavelength, samp_1_abs, samp_2_abs = np.loadtxt('Absorbance_Data.csv', unpack=True, delimiter=',', skiprows=1)"
},
{
"code": null,
"e": 2730,
"s": 2656,
"text": "We pass our file to the numpy.loadtxt function along with the parameters:"
},
{
"code": null,
"e": 2869,
"s": 2730,
"text": "unpack— transposes each column into an array, allowing you to unpack multiple variables at a time ( wavelength , samp_1_abs , samp_2_abs )"
},
{
"code": null,
"e": 2926,
"s": 2869,
"text": "delimiter — delimiter character used to separate columns"
},
{
"code": null,
"e": 3063,
"s": 2926,
"text": "skiprows — amount of rows to skip at the top of the file (since the first row is the column titles, we want to skip this so skiprows=1 )"
},
{
"code": null,
"e": 3182,
"s": 3063,
"text": "Once we have loaded our absorbance data, we can quickly plot and inspect both of the datasets with the following code:"
},
{
"code": null,
"e": 3363,
"s": 3182,
"text": "# Create figure and add axes objectfig = plt.figure()ax = fig.add_axes([0, 0, 1, 1])# Plot and show our dataax.plot(wavelength, samp_1_abs)ax.plot(wavelength, samp_2_abs)plt.show()"
},
{
"code": null,
"e": 3568,
"s": 3363,
"text": "The data plots properly, but the default matplotlib settings just don’t give the figure that publication quality. As we change some of the parameters below, we will end up with a much better looking plot."
},
{
"code": null,
"e": 3831,
"s": 3568,
"text": "This is a setting that I spend an irrationally large amount of time on — picking the right font for my plots. Your system already comes with a long list of pre-installed fonts, and you can check which fonts are already available to matplotlib with the following:"
},
{
"code": null,
"e": 3990,
"s": 3831,
"text": "import matplotlib.font_manager as fm# Collect all the font names available to matplotlibfont_names = [f.name for f in fm.fontManager.ttflist]print(font_names)"
},
{
"code": null,
"e": 4332,
"s": 3990,
"text": "If you would like to install a new font to your computer and then use it for your plots, this is also possible. First, you must download and install your desired font — many options can be found here. Once installed, you must rebuild the font cache so that it will be available to matplotlib when you make your figure. We do this as follows:"
},
{
"code": null,
"e": 4417,
"s": 4332,
"text": "import matplotlib.font_manager as fm# Rebuild the matplotlib font cachefm._rebuild()"
},
{
"code": null,
"e": 4516,
"s": 4417,
"text": "If you now check the list of available fonts, you should see the new font that you just installed."
},
{
"code": null,
"e": 4996,
"s": 4516,
"text": "The three general parameters that I set at the beginning of my plot script are: (1) font, (2) font size, and (3) axis line width. These are essentially global parameters that I do not edit later so setting them at the beginning makes everything easier (i.e. do not have to explicitly set font/sizes for each label down the line). We must add the following code before we generate any figures, so I typically put it near the top of the script immediately after importing packages."
},
{
"code": null,
"e": 5141,
"s": 4996,
"text": "# Edit the font, font size, and axes widthmpl.rcParams['font.family'] = 'Avenir'plt.rcParams['font.size'] = 18plt.rcParams['axes.linewidth'] = 2"
},
{
"code": null,
"e": 5666,
"s": 5141,
"text": "If you have a set of colors that you like to use, you are free to skip this step. In this case, since we only have two samples, it is better to manually select two high-constrast colors. But, if you want to generate a list of colors without too much effort on your end, we can use the pylab package we imported to generate a list of them from one of the various matplotlib built-in colormaps, which can be found here. This becomes very useful when you need a large number of colors, as you can generate them programatically."
},
{
"code": null,
"e": 5999,
"s": 5666,
"text": "For our dataset, we are just interested in easily distinguishing between our traces, so we would be best served using one of the colormaps in the qualitative section (I will use “tab10” for this example). We use the following code — the first argument is the colormap name and the second is the number of colors we want to generate:"
},
{
"code": null,
"e": 6077,
"s": 5999,
"text": "# Generate 2 colors from the 'tab10' colormapcolors = cm.get_cmap('tab10', 2)"
},
{
"code": null,
"e": 6372,
"s": 6077,
"text": "If we were, for example, measuring the temperature-dependence of a single sample and wanted to plot the spectra at different temperatures, we could use a diverging colormap such as “coolwarm”. Ultimately, the colormap you choose will be up to you and based on the type of data you are plotting."
},
{
"code": null,
"e": 6517,
"s": 6372,
"text": "We must create a figure, which is a blank window, and then add an axes object to it for our plot. To generate the figure, we have the following:"
},
{
"code": null,
"e": 6612,
"s": 6517,
"text": "# Create figure object and store it in a variable called 'fig'fig = plt.figure(figsize=(3, 3))"
},
{
"code": null,
"e": 6702,
"s": 6612,
"text": "figsize — size of our figure (width, height) in inches, with the default being (6.4, 4.8)"
},
{
"code": null,
"e": 7030,
"s": 6702,
"text": "Now we must add an axes object to our blank figure by specifying the bottom left coordinate and the width and height in relative coordinates (1 is the full size of the figure window). If we want it to fill our entire figure, we can specify [0, 0, 1, 1] which sets the bottom left corner to (0, 0) and the width and height to 1."
},
{
"code": null,
"e": 7121,
"s": 7030,
"text": "# Add axes object to our figure that takes up entire figureax = fig.add_axes([0, 0, 1, 1])"
},
{
"code": null,
"e": 7236,
"s": 7121,
"text": "We can use this axis construction to create paneled figures and insets by making multiple axes objects as follows:"
},
{
"code": null,
"e": 7356,
"s": 7236,
"text": "# Add two axes objects to create a paneled figureax1 = fig.add_axes([0, 0, 1, 0.4])ax2 = fig.add_axes([0, 0.6, 1, 0.4])"
},
{
"code": null,
"e": 7477,
"s": 7356,
"text": "# Add two axes objects to create an inset figureax1 = fig.add_axes([0, 0, 1, 1])ax2 = fig.add_axes([0.5, 0.5, 0.4, 0.4])"
},
{
"code": null,
"e": 7574,
"s": 7477,
"text": "If we do not want our plot entirely enclosed, we can remove the top and right spines as follows:"
},
{
"code": null,
"e": 7690,
"s": 7574,
"text": "# Hide the top and right spines of the axisax.spines['right'].set_visible(False)ax.spines['top'].set_visible(False)"
},
{
"code": null,
"e": 7850,
"s": 7690,
"text": "We can edit the tick widths and lengths to match our axis parameters with the following code. If we have minor ticks, we can also edit the properties of these:"
},
{
"code": null,
"e": 8237,
"s": 7850,
"text": "# Edit the major and minor ticks of the x and y axesax.xaxis.set_tick_params(which='major', size=10, width=2, direction='in', top='on')ax.xaxis.set_tick_params(which='minor', size=7, width=2, direction='in', top='on')ax.yaxis.set_tick_params(which='major', size=10, width=2, direction='in', right='on')ax.yaxis.set_tick_params(which='minor', size=7, width=2, direction='in', right='on')"
},
{
"code": null,
"e": 8298,
"s": 8237,
"text": "which — whether we are editing major , minor , or both ticks"
},
{
"code": null,
"e": 8331,
"s": 8298,
"text": "size — length of ticks in points"
},
{
"code": null,
"e": 8412,
"s": 8331,
"text": "width — line width of ticks (we can set this to the same as our axis line width)"
},
{
"code": null,
"e": 8475,
"s": 8412,
"text": "direction — whether ticks will face in , out , or inout (both)"
},
{
"code": null,
"e": 8551,
"s": 8475,
"text": "top / right — whether there will be ticks on the secondary axes (top/right)"
},
{
"code": null,
"e": 8664,
"s": 8551,
"text": "We can now again plot our data, using the colors that we generated from the colormap to distinguish the samples:"
},
{
"code": null,
"e": 8891,
"s": 8664,
"text": "# Plot the two sample absorbances, using previously generated colorsax.plot(wavelength, samp_1_abs, linewidth=2, color=colors(0), label='Sample 1')ax.plot(wavelength, samp_2_abs, linewidth=2, color=colors(1), label='Sample 2')"
},
{
"code": null,
"e": 8938,
"s": 8891,
"text": "linewidth — line width of the line in the plot"
},
{
"code": null,
"e": 8976,
"s": 8938,
"text": "color — color of the line in the plot"
},
{
"code": null,
"e": 9031,
"s": 8976,
"text": "label — label for the trace (reference for the legend)"
},
{
"code": null,
"e": 9096,
"s": 9031,
"text": "Now we can set the x and y-axis ranges with the following lines:"
},
{
"code": null,
"e": 9161,
"s": 9096,
"text": "# Set the axis limitsax.set_xlim(370, 930)ax.set_ylim(-0.2, 2.2)"
},
{
"code": null,
"e": 9621,
"s": 9161,
"text": "We notice that the tick marks seem unbalanced between the two axes — we can also semi-manually edit this using a function called MultipleLocator which will create ticks at every multiple of a base number that we provide. We must edit the major_locator for the major ticks and minor_locator for the minor ticks. We will set major ticks every 100 nm and minor ticks every 50 nm for the x-axis and major ticks every 0.5 and minor ticks every 0.25 for the y-axis."
},
{
"code": null,
"e": 9899,
"s": 9621,
"text": "# Edit the major and minor tick locationsax.xaxis.set_major_locator(mpl.ticker.MultipleLocator(100))ax.xaxis.set_minor_locator(mpl.ticker.MultipleLocator(50))ax.yaxis.set_major_locator(mpl.ticker.MultipleLocator(0.5))ax.yaxis.set_minor_locator(mpl.ticker.MultipleLocator(0.25))"
},
{
"code": null,
"e": 9987,
"s": 9899,
"text": "We must add labels to the x and y-axes, which we can easily do with the following code:"
},
{
"code": null,
"e": 10109,
"s": 9987,
"text": "# Add the x and y-axis labelsax.set_xlabel('Wavelength (nm)', labelpad=10)ax.set_ylabel('Absorbance (O.D.)', labelpad=10)"
},
{
"code": null,
"e": 10177,
"s": 10109,
"text": "labelpad — extra padding between the tick labels and the axis label"
},
{
"code": null,
"e": 10590,
"s": 10177,
"text": "If you want to include Greek characters in your labels, you can use LaTeX syntax to do so. We create a raw string by prepending the string with r and enclose the LaTeX command with $$ . However, this will use the default LaTeX font for the Greek characters — if we want to use the same font as the rest of the plot (assuming the character exists), we enclose our command with $\\mathregular{'Command goes here'}$."
},
{
"code": null,
"e": 10694,
"s": 10590,
"text": "# Add the x-axis label with λ for wavelengthax.set_xlabel(r'$\\mathregular{\\lambda}$ (nm)', labelpad=10)"
},
{
"code": null,
"e": 11175,
"s": 10694,
"text": "If we want to place ticks on one of the secondary (top/right) axes to show either a different dataset or scaling, we can do so using a parasitic axis. This axes object duplicates one of the axes of the original plot, allowing you to change the scaling on the other. To illustrate this, we can use our absorbance data as an example. The current x-axis is the wavelength of absorbed light, but based on the application, the energy of this light might be the more relevant parameter."
},
{
"code": null,
"e": 11603,
"s": 11175,
"text": "We can create a second x-axis on the top of the plot to show the energy scaling. First, we must create a parasitic axis with either the twinx() or twiny() command to clone the x or y-axes, respectively. In this example, we want the y-axis data constant, so we will clone the y-axis. We also need to match the tick parameters of this new x-axis to the old plot’s x-axis (and remove top='on' from the original x-axis parameters)."
},
{
"code": null,
"e": 11875,
"s": 11603,
"text": "# Create new axes object by cloning the y-axis of the first plotax2 = ax.twiny()# Edit the tick parameters of the new x-axisax2.xaxis.set_tick_params(which='major', size=10, width=2, direction='in')ax2.xaxis.set_tick_params(which='minor', size=7, width=2, direction='in')"
},
{
"code": null,
"e": 12185,
"s": 11875,
"text": "To make our job of adding ticks in energy units to this axis easier, we can write a function to convert energy to wavelength (since we will place the ticks on the wavelength axis at points that energy values would correspond to). We will treat the input E as an array so we can do all the conversions at once:"
},
{
"code": null,
"e": 12283,
"s": 12185,
"text": "# Function to convert energy (eV) to wavelength (nm)def E_to_WL(E): return [1240/i for i in E]"
},
{
"code": null,
"e": 12559,
"s": 12283,
"text": "Since this is a non-linear transformation, we cannot easily use the MultipleLocator function, and we will add the tick marks manually, using a function called FixedLocator . To use FixedLocator we provide an array of all the locations at which we want there to be tick marks:"
},
{
"code": null,
"e": 12770,
"s": 12559,
"text": "# Add ticks manually to energy axisax2.xaxis.set_major_locator(mpl.ticker.FixedLocator(E_to_WL(np.linspace(1.5, 3.0, 4))))ax2.xaxis.set_minor_locator(mpl.ticker.FixedLocator(E_to_WL(np.linspace(1.4, 3.2, 19))))"
},
{
"code": null,
"e": 12854,
"s": 12770,
"text": "Since we added the ticks manually, we must also add the major tick labels manually."
},
{
"code": null,
"e": 12945,
"s": 12854,
"text": "# Add tick labels manually to energy axisax2.set_xticklabels(['1.5', '2.0', '2.5', '3.0'])"
},
{
"code": null,
"e": 13073,
"s": 12945,
"text": "Finally, we also want to add an axis label to our new x-axis and make sure the axis limits are the same as the original x-axis:"
},
{
"code": null,
"e": 13185,
"s": 13073,
"text": "# Add energy axis labelax2.set_xlabel('Energy (eV)', labelpad=10)# Set energy axis limitsax2.set_xlim(370, 930)"
},
{
"code": null,
"e": 13346,
"s": 13185,
"text": "The final thing we must add to our plot is a legend, so that a reader can know which trace corresponds to which sample. To do so, we can use the following code:"
},
{
"code": null,
"e": 13434,
"s": 13346,
"text": "# Add legend to plotax.legend(bbox_to_anchor=(1, 1), loc=1, frameon=False, fontsize=16)"
},
{
"code": null,
"e": 13497,
"s": 13434,
"text": "bbox_to_anchor — coordinate of the bounding box for our legend"
},
{
"code": null,
"e": 13814,
"s": 13497,
"text": "loc — which part of the bounding box to use the coordinate of the bbox_to_anchor value ( 0 for automatic, 1 for top right corner, 2 for top left corner, 3 for bottom left corner, 4 for bottom right corner, 5 for right, 6 for center left, 7 for center right, 8 for lower center, 9 for upper center, and 10 for center)"
},
{
"code": null,
"e": 13866,
"s": 13814,
"text": "frameon — whether to draw a frame around the legend"
},
{
"code": null,
"e": 13944,
"s": 13866,
"text": "fontsize — font size for legend entries (if different from general parameter)"
},
{
"code": null,
"e": 14040,
"s": 13944,
"text": "Lastly, saving your final plot is very simple — we can use the function plt.savefig to do this."
},
{
"code": null,
"e": 14132,
"s": 14040,
"text": "# Save figureplt.savefig('Final_Plot.png', dpi=300, transparent=False, bbox_inches='tight')"
},
{
"code": null,
"e": 14460,
"s": 14132,
"text": "dpi — resolution for a rastered image file format (in this case we are saving as .png file so this means that we are saving with a resolution of 300 dots per inch. The other possible file formats you can save are .ps , .pdf , and .svg which are all vector graphics formats, in which case you do not need to specify a dpi value)"
},
{
"code": null,
"e": 14541,
"s": 14460,
"text": "transparent — whether to make the figure transparent, or with a white background"
},
{
"code": null,
"e": 14667,
"s": 14541,
"text": "bbox_inches — defines the bounding box around the figure ( tight ensures that there is no extra whitespace around the figure)"
},
{
"code": null,
"e": 14777,
"s": 14667,
"text": "To actually view our final plot in a figure window, we must add a plt.show() command after saving the figure."
},
{
"code": null,
"e": 14801,
"s": 14777,
"text": "# Show figureplt.show()"
},
{
"code": null,
"e": 14979,
"s": 14801,
"text": "That’s it! We have successfully made a publication quality plot using Python! This example and all subsequent examples will be freely available online at this Github repository."
}
] |
CLASSPATH in Java - GeeksforGeeks
|
06 Oct, 2021
Package in Java is a mechanism to encapsulate a group of classes, sub-packages, and interfaces. Packages are used for:
Preventing naming conflicts. For example, there can be two classes with the name Employee in two packages, college.staff.cse.Employee and college.staff.ee.Employee
Making searching/locating and usage of classes, interfaces, enumerations, and annotations easier
Providing controlled access: protected and default have package level access control. A protected member is accessible by classes in the same package and its subclasses. A default member (without any access specifier) is accessible by classes in the same package only.
Packages can be considered as data encapsulation (or data-hiding). Here we will be discussing the responsibility of the CLASSPATH environment variable while programming in Java as we move forward we for sure short need usage of importing statements.
Illustration:
import org.company.Menu
What does this import mean? It makes the Menu class available in the package org.company to our current class. Such that when we call the below command as follows:
Menu menu = new Menu();
Example
Java
// Java Program to Illustrate Usage of importing// Classes from packages and sub-packages // Here we are importing all classes from// java.io (input-output package)import java.io.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Print statement System.out.println("I/O classes are imported from java.io package"); }}
I/O classes are imported from java.io package
This package provides for system input and output through data streams, serialization, and the file system. Unless otherwise noted, passing a null argument to a constructor or method in any class or interface in this package will cause a NullPointerException to be thrown. All the classes listed here are imported or if we want to import a specific one then do use it as stated below.
import java.util.Scanner ;
The JVM knows where to find the class Menu. Now, how will the JVM know this location?
It is impractical for it to go through every folder on your system and search for it. Thus, using the CLASSPATH variable we provide it the place where we want it to look. We put directories and jars in the CLASSPATH variable.
Let’s say the above package resides in the directory dir. The complete path of the Menu class file would be dir/org/company/Menu. We’ll specify only the directory dir in our classpath variable, as the rest information regarding the path is provided by the import statements. Similar for jar, if you create a jar and mention its path in the variable, the VM will look inside the jar file and find the class.
One should know how to set a classpath if not done after configuring JDK in respecting operating systems in order to see it or to it and play with multiple IDE, versions game altogether. One must have an absolutely clear understanding of it.
This article is contributed by ekta1994. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
velociraptoryuzi
solankimayank
java-basics
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
HashMap in Java with Examples
Object Oriented Programming (OOPs) Concept in Java
ArrayList in Java
Initialize an ArrayList in Java
Overriding in Java
How to iterate any Map in Java
LinkedList in Java
Queue Interface In Java
Multithreading in Java
Collections in Java
|
[
{
"code": null,
"e": 24152,
"s": 24124,
"text": "\n06 Oct, 2021"
},
{
"code": null,
"e": 24271,
"s": 24152,
"text": "Package in Java is a mechanism to encapsulate a group of classes, sub-packages, and interfaces. Packages are used for:"
},
{
"code": null,
"e": 24435,
"s": 24271,
"text": "Preventing naming conflicts. For example, there can be two classes with the name Employee in two packages, college.staff.cse.Employee and college.staff.ee.Employee"
},
{
"code": null,
"e": 24532,
"s": 24435,
"text": "Making searching/locating and usage of classes, interfaces, enumerations, and annotations easier"
},
{
"code": null,
"e": 24801,
"s": 24532,
"text": "Providing controlled access: protected and default have package level access control. A protected member is accessible by classes in the same package and its subclasses. A default member (without any access specifier) is accessible by classes in the same package only."
},
{
"code": null,
"e": 25051,
"s": 24801,
"text": "Packages can be considered as data encapsulation (or data-hiding). Here we will be discussing the responsibility of the CLASSPATH environment variable while programming in Java as we move forward we for sure short need usage of importing statements."
},
{
"code": null,
"e": 25065,
"s": 25051,
"text": "Illustration:"
},
{
"code": null,
"e": 25091,
"s": 25065,
"text": " import org.company.Menu "
},
{
"code": null,
"e": 25256,
"s": 25091,
"text": "What does this import mean? It makes the Menu class available in the package org.company to our current class. Such that when we call the below command as follows: "
},
{
"code": null,
"e": 25283,
"s": 25256,
"text": "Menu menu = new Menu(); "
},
{
"code": null,
"e": 25291,
"s": 25283,
"text": "Example"
},
{
"code": null,
"e": 25296,
"s": 25291,
"text": "Java"
},
{
"code": "// Java Program to Illustrate Usage of importing// Classes from packages and sub-packages // Here we are importing all classes from// java.io (input-output package)import java.io.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Print statement System.out.println(\"I/O classes are imported from java.io package\"); }}",
"e": 25689,
"s": 25296,
"text": null
},
{
"code": null,
"e": 25735,
"s": 25689,
"text": "I/O classes are imported from java.io package"
},
{
"code": null,
"e": 26120,
"s": 25735,
"text": "This package provides for system input and output through data streams, serialization, and the file system. Unless otherwise noted, passing a null argument to a constructor or method in any class or interface in this package will cause a NullPointerException to be thrown. All the classes listed here are imported or if we want to import a specific one then do use it as stated below."
},
{
"code": null,
"e": 26147,
"s": 26120,
"text": "import java.util.Scanner ;"
},
{
"code": null,
"e": 26233,
"s": 26147,
"text": "The JVM knows where to find the class Menu. Now, how will the JVM know this location?"
},
{
"code": null,
"e": 26459,
"s": 26233,
"text": "It is impractical for it to go through every folder on your system and search for it. Thus, using the CLASSPATH variable we provide it the place where we want it to look. We put directories and jars in the CLASSPATH variable."
},
{
"code": null,
"e": 26867,
"s": 26459,
"text": "Let’s say the above package resides in the directory dir. The complete path of the Menu class file would be dir/org/company/Menu. We’ll specify only the directory dir in our classpath variable, as the rest information regarding the path is provided by the import statements. Similar for jar, if you create a jar and mention its path in the variable, the VM will look inside the jar file and find the class. "
},
{
"code": null,
"e": 27109,
"s": 26867,
"text": "One should know how to set a classpath if not done after configuring JDK in respecting operating systems in order to see it or to it and play with multiple IDE, versions game altogether. One must have an absolutely clear understanding of it."
},
{
"code": null,
"e": 27526,
"s": 27109,
"text": "This article is contributed by ekta1994. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 27543,
"s": 27526,
"text": "velociraptoryuzi"
},
{
"code": null,
"e": 27557,
"s": 27543,
"text": "solankimayank"
},
{
"code": null,
"e": 27569,
"s": 27557,
"text": "java-basics"
},
{
"code": null,
"e": 27574,
"s": 27569,
"text": "Java"
},
{
"code": null,
"e": 27579,
"s": 27574,
"text": "Java"
},
{
"code": null,
"e": 27677,
"s": 27579,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27686,
"s": 27677,
"text": "Comments"
},
{
"code": null,
"e": 27699,
"s": 27686,
"text": "Old Comments"
},
{
"code": null,
"e": 27729,
"s": 27699,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 27780,
"s": 27729,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 27798,
"s": 27780,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 27830,
"s": 27798,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 27849,
"s": 27830,
"text": "Overriding in Java"
},
{
"code": null,
"e": 27880,
"s": 27849,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 27899,
"s": 27880,
"text": "LinkedList in Java"
},
{
"code": null,
"e": 27923,
"s": 27899,
"text": "Queue Interface In Java"
},
{
"code": null,
"e": 27946,
"s": 27923,
"text": "Multithreading in Java"
}
] |
How to limit an HTML input box so that it only accepts numeric input?
|
To limit an HTML input box to accept numeric input, use the <input type="number">. With this, you will get a numeric input field.
After limiting the input box to number, if a user enters text and press submit button, then the following can be seen “Please enter a number.”
You can try to run the following code to limit an HTML input box so that it only accepts numeric input −
<!DOCTYPE html>
<html>
<head>
<title>HTML input number</title>
</head>
<body>
<form action = "" method = "get">
Enter any number between 1 to 20:
<input type="number" name="num" min="1" max="20"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
|
[
{
"code": null,
"e": 1192,
"s": 1062,
"text": "To limit an HTML input box to accept numeric input, use the <input type=\"number\">. With this, you will get a numeric input field."
},
{
"code": null,
"e": 1335,
"s": 1192,
"text": "After limiting the input box to number, if a user enters text and press submit button, then the following can be seen “Please enter a number.”"
},
{
"code": null,
"e": 1440,
"s": 1335,
"text": "You can try to run the following code to limit an HTML input box so that it only accepts numeric input −"
},
{
"code": null,
"e": 1759,
"s": 1440,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>HTML input number</title>\n </head>\n\n <body>\n <form action = \"\" method = \"get\">\n Enter any number between 1 to 20:\n <input type=\"number\" name=\"num\" min=\"1\" max=\"20\"><br>\n <input type=\"submit\" value=\"Submit\">\n </form>\n </body>\n</html>"
}
] |
5 Most Common Java Pitfalls - GeeksforGeeks
|
08 Oct, 2021
1. Not understanding that String is an immutable class: The Java String class is immutable (Unmodifiable). This is because String objects are cached in a String pool. The object that a String is referencing to can change, but the String objects themselves cannot.
Example:
Java
public class Main { public static void main(String[] args) { String str = "GeeksFor"; // A new string will be returned, but the actual String will remain the same str.concat("Geeks"); // Prints initial value "GeeksFor" System.out.println(str); // Now we change the reference of "str" to point to the new String returned str = str.concat("Geeks"); // Prints the new concatenated String System.out.println(str); }}
Output : GeeksFor
GeeksForGeeks
2. Memory Leaks: One of the core benefits of Java is the Java Garbage Collector, which manages the objects memory on the heap. Whenever an object is unreachable it is automatically freed. However, a common slip for both new and experienced programmers is preventing the memory from being freed, by allowing objects to be reachable that are no longer in use. This can be a very big downside to a project since memory leaks block resources and degrades the application performance. It can even lead to java.lang.OutOfMemoryError.
Common Cases are:
Static Fields Declaring a static field and forgetting to set it to null after its data is not longer needed
Unclosed Streams The Java Virtual Machine allocates memory for every connection opened. Forgetting to close the connection consumes memory. Such connections can be: Input Streams, Database Connections, Sessions, and others.
The finalize() method When we override the finalize() method, the object of that class is not any more directly garbage collected. The Garbage Collector is then waiting for finalization, which is happening at a later point in time.
3. Pre/Post Increment Operator and side-effects: The evaluation order of operators in Java appear to be evaluated from left to right, the side effects can be seen instantly:
Java
public class Main { public static void main(String[] args) { int num = 0; /* First case */ // The increment operator happens after the value is pushed onto the stack and assigned num = num++; // Prints initial value System.out.println(num); /* Second case */ // Increment occurs first, and then it is pushed to the stack and assigned to num num = ++num; System.out.println(num); }}
Output : 0
1
The execution context of the first case is as follows:
Store previous value of operand.Increment the value.Return the previous value
Store previous value of operand.
Increment the value.
Return the previous value
The execution context of the second case is as follows:
Increment the value.Store value of operand (incremented)Return the value
Increment the value.
Store value of operand (incremented)
Return the value
4. Using the relational operator “==” for Objects comparison. Many novice programmers try to use the “==” operator to compare objects and when the behavior of their code is not as expected they are confused. A thing to be aware of is that the relational operator “==” is making a reference comparison, it checks if both objects point to the same location in memory. Using the .equals() method will eliminate the problem since it compares the values inside the objects.
Java
public class Main { public static void main(String[] args) { String s1 = new String("GeeksForGeeks"); String s2 = new String("GeeksForGeeks"); // Comparing using the relational operator if (s1 == s2) { // false System.out.println("Both objects point to the same memory location!"); } // Comparing using the .equals() if (s1.equals(s2)) { // true System.out.println("The value inside the object instances match!"); } // Declaring a string with a reference to s1 String s3 = s1; if (s3 == s1) { // true System.out.println("Both objects point to the same memory location!"); } }}
Output : The value inside the object instances match!
Both objects point to the same memory location!
Although sometimes the “==” operator will give the expected answer:
Java
public class Main { public static void main(String[] args) { String s1 = "GeeksForGeeks"; String s2 = "GeeksForGeeks"; // Comparing using the relational operator if (s1 == s2) { // true System.out.println("The two strings are the same!"); } else { System.out.println("The two strings are the different!"); } }}
Output : The two strings are the same!
The reason is in the Java Language Specification String Literals: ‘Literal strings within the same class in the same package represent references to the same String object’. The condition in the code is true because the literals are consisting of the same characters.
5. Using raw types Before Java started using generic types, there have not been alternatives to raw types (types that are not parameterized). For backward compatibility reasons, it is still possible to define these:
Java
public class Main { public static void main(String[] args) { // Defining a raw list, without specifying its type parameter List geeksList = new ArrayList(); // Due to the unspecified type we can add any data type and the code will compile geeksList.add(100); geeksList.add(200); geeksList.add("GeeksForGeeks"); // When the second element is reached the compiler will throw a runtime error // because we are trying to cast a string to an integer geeksList.forEach(k -> System.out.println((int)k * 2)); }}
Output : 200
400
Exception in thread "main" java.lang.ClassCastException:
java.base/java.lang.String cannot be cast to java.base/java.lang.Integer
This issue can be prevented by defining the generic type of the List:
List geeksList = new ArrayList();
Now the code won’t compile since we are trying to add a String type to a collection of Integer types. Generic Types are created for a reason and prevent programmers from nasty bugs and overheads.
gabaa406
adnanirshad158
anikaseth98
java-basics
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
How to iterate any Map in Java
Interfaces in Java
Initialize an ArrayList in Java
ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java
LinkedList in Java
|
[
{
"code": null,
"e": 24025,
"s": 23997,
"text": "\n08 Oct, 2021"
},
{
"code": null,
"e": 24290,
"s": 24025,
"text": "1. Not understanding that String is an immutable class: The Java String class is immutable (Unmodifiable). This is because String objects are cached in a String pool. The object that a String is referencing to can change, but the String objects themselves cannot. "
},
{
"code": null,
"e": 24300,
"s": 24290,
"text": "Example: "
},
{
"code": null,
"e": 24305,
"s": 24300,
"text": "Java"
},
{
"code": "public class Main { public static void main(String[] args) { String str = \"GeeksFor\"; // A new string will be returned, but the actual String will remain the same str.concat(\"Geeks\"); // Prints initial value \"GeeksFor\" System.out.println(str); // Now we change the reference of \"str\" to point to the new String returned str = str.concat(\"Geeks\"); // Prints the new concatenated String System.out.println(str); }}",
"e": 24790,
"s": 24305,
"text": null
},
{
"code": null,
"e": 24832,
"s": 24790,
"text": "Output : GeeksFor \n GeeksForGeeks"
},
{
"code": null,
"e": 25360,
"s": 24832,
"text": "2. Memory Leaks: One of the core benefits of Java is the Java Garbage Collector, which manages the objects memory on the heap. Whenever an object is unreachable it is automatically freed. However, a common slip for both new and experienced programmers is preventing the memory from being freed, by allowing objects to be reachable that are no longer in use. This can be a very big downside to a project since memory leaks block resources and degrades the application performance. It can even lead to java.lang.OutOfMemoryError."
},
{
"code": null,
"e": 25379,
"s": 25360,
"text": "Common Cases are: "
},
{
"code": null,
"e": 25487,
"s": 25379,
"text": "Static Fields Declaring a static field and forgetting to set it to null after its data is not longer needed"
},
{
"code": null,
"e": 25711,
"s": 25487,
"text": "Unclosed Streams The Java Virtual Machine allocates memory for every connection opened. Forgetting to close the connection consumes memory. Such connections can be: Input Streams, Database Connections, Sessions, and others."
},
{
"code": null,
"e": 25943,
"s": 25711,
"text": "The finalize() method When we override the finalize() method, the object of that class is not any more directly garbage collected. The Garbage Collector is then waiting for finalization, which is happening at a later point in time."
},
{
"code": null,
"e": 26117,
"s": 25943,
"text": "3. Pre/Post Increment Operator and side-effects: The evaluation order of operators in Java appear to be evaluated from left to right, the side effects can be seen instantly:"
},
{
"code": null,
"e": 26122,
"s": 26117,
"text": "Java"
},
{
"code": "public class Main { public static void main(String[] args) { int num = 0; /* First case */ // The increment operator happens after the value is pushed onto the stack and assigned num = num++; // Prints initial value System.out.println(num); /* Second case */ // Increment occurs first, and then it is pushed to the stack and assigned to num num = ++num; System.out.println(num); }}",
"e": 26583,
"s": 26122,
"text": null
},
{
"code": null,
"e": 26607,
"s": 26583,
"text": "Output : 0 \n 1 "
},
{
"code": null,
"e": 26663,
"s": 26607,
"text": "The execution context of the first case is as follows: "
},
{
"code": null,
"e": 26741,
"s": 26663,
"text": "Store previous value of operand.Increment the value.Return the previous value"
},
{
"code": null,
"e": 26774,
"s": 26741,
"text": "Store previous value of operand."
},
{
"code": null,
"e": 26795,
"s": 26774,
"text": "Increment the value."
},
{
"code": null,
"e": 26821,
"s": 26795,
"text": "Return the previous value"
},
{
"code": null,
"e": 26877,
"s": 26821,
"text": "The execution context of the second case is as follows:"
},
{
"code": null,
"e": 26950,
"s": 26877,
"text": "Increment the value.Store value of operand (incremented)Return the value"
},
{
"code": null,
"e": 26971,
"s": 26950,
"text": "Increment the value."
},
{
"code": null,
"e": 27008,
"s": 26971,
"text": "Store value of operand (incremented)"
},
{
"code": null,
"e": 27025,
"s": 27008,
"text": "Return the value"
},
{
"code": null,
"e": 27494,
"s": 27025,
"text": "4. Using the relational operator “==” for Objects comparison. Many novice programmers try to use the “==” operator to compare objects and when the behavior of their code is not as expected they are confused. A thing to be aware of is that the relational operator “==” is making a reference comparison, it checks if both objects point to the same location in memory. Using the .equals() method will eliminate the problem since it compares the values inside the objects."
},
{
"code": null,
"e": 27499,
"s": 27494,
"text": "Java"
},
{
"code": "public class Main { public static void main(String[] args) { String s1 = new String(\"GeeksForGeeks\"); String s2 = new String(\"GeeksForGeeks\"); // Comparing using the relational operator if (s1 == s2) { // false System.out.println(\"Both objects point to the same memory location!\"); } // Comparing using the .equals() if (s1.equals(s2)) { // true System.out.println(\"The value inside the object instances match!\"); } // Declaring a string with a reference to s1 String s3 = s1; if (s3 == s1) { // true System.out.println(\"Both objects point to the same memory location!\"); } }}",
"e": 28202,
"s": 27499,
"text": null
},
{
"code": null,
"e": 28315,
"s": 28202,
"text": "Output : The value inside the object instances match! \n Both objects point to the same memory location! "
},
{
"code": null,
"e": 28384,
"s": 28315,
"text": "Although sometimes the “==” operator will give the expected answer: "
},
{
"code": null,
"e": 28389,
"s": 28384,
"text": "Java"
},
{
"code": "public class Main { public static void main(String[] args) { String s1 = \"GeeksForGeeks\"; String s2 = \"GeeksForGeeks\"; // Comparing using the relational operator if (s1 == s2) { // true System.out.println(\"The two strings are the same!\"); } else { System.out.println(\"The two strings are the different!\"); } }}",
"e": 28780,
"s": 28389,
"text": null
},
{
"code": null,
"e": 28820,
"s": 28780,
"text": "Output : The two strings are the same! "
},
{
"code": null,
"e": 29088,
"s": 28820,
"text": "The reason is in the Java Language Specification String Literals: ‘Literal strings within the same class in the same package represent references to the same String object’. The condition in the code is true because the literals are consisting of the same characters."
},
{
"code": null,
"e": 29304,
"s": 29088,
"text": "5. Using raw types Before Java started using generic types, there have not been alternatives to raw types (types that are not parameterized). For backward compatibility reasons, it is still possible to define these:"
},
{
"code": null,
"e": 29309,
"s": 29304,
"text": "Java"
},
{
"code": "public class Main { public static void main(String[] args) { // Defining a raw list, without specifying its type parameter List geeksList = new ArrayList(); // Due to the unspecified type we can add any data type and the code will compile geeksList.add(100); geeksList.add(200); geeksList.add(\"GeeksForGeeks\"); // When the second element is reached the compiler will throw a runtime error // because we are trying to cast a string to an integer geeksList.forEach(k -> System.out.println((int)k * 2)); }}",
"e": 29885,
"s": 29309,
"text": null
},
{
"code": null,
"e": 30042,
"s": 29885,
"text": "Output : 200\n 400\nException in thread \"main\" java.lang.ClassCastException: \njava.base/java.lang.String cannot be cast to java.base/java.lang.Integer"
},
{
"code": null,
"e": 30113,
"s": 30042,
"text": "This issue can be prevented by defining the generic type of the List: "
},
{
"code": null,
"e": 30147,
"s": 30113,
"text": "List geeksList = new ArrayList();"
},
{
"code": null,
"e": 30343,
"s": 30147,
"text": "Now the code won’t compile since we are trying to add a String type to a collection of Integer types. Generic Types are created for a reason and prevent programmers from nasty bugs and overheads."
},
{
"code": null,
"e": 30352,
"s": 30343,
"text": "gabaa406"
},
{
"code": null,
"e": 30367,
"s": 30352,
"text": "adnanirshad158"
},
{
"code": null,
"e": 30379,
"s": 30367,
"text": "anikaseth98"
},
{
"code": null,
"e": 30391,
"s": 30379,
"text": "java-basics"
},
{
"code": null,
"e": 30396,
"s": 30391,
"text": "Java"
},
{
"code": null,
"e": 30401,
"s": 30396,
"text": "Java"
},
{
"code": null,
"e": 30499,
"s": 30401,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30508,
"s": 30499,
"text": "Comments"
},
{
"code": null,
"e": 30521,
"s": 30508,
"text": "Old Comments"
},
{
"code": null,
"e": 30572,
"s": 30521,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 30602,
"s": 30572,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 30633,
"s": 30602,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 30652,
"s": 30633,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 30684,
"s": 30652,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 30702,
"s": 30684,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 30722,
"s": 30702,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 30754,
"s": 30722,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 30778,
"s": 30754,
"text": "Singleton Class in Java"
}
] |
How to hide Bootstrap modal with JavaScript? - GeeksforGeeks
|
19 Jun, 2019
This article will tell us how the bootstrap executes when the .modal (modal window) gets closed. At some point of time, the modal window – whenever it gets opened (along with the class modal), it is going to get closed.As soon the modal has got finished, after being getting hidden from the user, the event will be fired up. The function will get executed and also the below syntax will be triggered, whenever the modal window gets hidden away. By the way, it will call to the caller/user, before disappearing straight away. Also, this is not managed by the user at all. The Bootstrap library is built-in already, and it is going to do the maximum work for you.
The below syntax will be used when the Bootstrap modal is about to be hidden or to hide the Bootstrap modal.Syntax:
hide.bs.modal
Example: This example shows the usage of hide.bs.modal.
<!DOCTYPE html><html> <head> <h2 style="color:green"> GeeksForGeeks </h2> <h2 style="color:purple"> Hide Bootstrap Modal </h2> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"> </script> <style> #myBtn { width: 300px; padding: 10px; font-size: 20px; position: absolute; margin: 0 auto; right: 0; left: 0; bottom: 50px; z-index: 9999; } </style></head> <body style="text-align:center"> <div class="container"> <h2>Modal Events - hide.bs.modal</h2> <!-- Trigger the modal with a button --> <button type="button" style="color:brown" class="btn btn-info btn-md" id="myBtn"> Hide Modal </button> <!-- Modal --> <div class="modal fade" id="myModal" role="dialog"> <div class="modal-dialog"> <!-- Modal content--> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal"> × </button> <h4 class="modal-title"> Modal Header: GeeksForGeeks </h4> </div> <div class="modal-body"> <p>The <strong>hide.bs.modal</strong> is going to hide the modal.</p> <p>If you wish to trigger the modal and see the modal get hidden, then press the <strong>'HIDE MODAL'</strong> button. </p> </div> </div> </div> </div> </div> <script> $(document).ready(function() { $("#myModal").modal("show"); $("#myBtn").click(function() { $("#myModal").modal("hide"); }); $("#myModal").on('hide.bs.modal', function() { alert('The modal is about to be hidden.'); }); }); </script></body> </html>
Output:When we load the code:
When we click on ‘X’ button:
The popup:
Result:
The working:
Bootstrap-Misc
JavaScript-Misc
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
How to Open URL in New Tab using JavaScript ?
How to read a local text file using JavaScript?
Top 10 Front End Developer Skills That You Need 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": 24295,
"s": 24267,
"text": "\n19 Jun, 2019"
},
{
"code": null,
"e": 24957,
"s": 24295,
"text": "This article will tell us how the bootstrap executes when the .modal (modal window) gets closed. At some point of time, the modal window – whenever it gets opened (along with the class modal), it is going to get closed.As soon the modal has got finished, after being getting hidden from the user, the event will be fired up. The function will get executed and also the below syntax will be triggered, whenever the modal window gets hidden away. By the way, it will call to the caller/user, before disappearing straight away. Also, this is not managed by the user at all. The Bootstrap library is built-in already, and it is going to do the maximum work for you."
},
{
"code": null,
"e": 25073,
"s": 24957,
"text": "The below syntax will be used when the Bootstrap modal is about to be hidden or to hide the Bootstrap modal.Syntax:"
},
{
"code": null,
"e": 25087,
"s": 25073,
"text": "hide.bs.modal"
},
{
"code": null,
"e": 25143,
"s": 25087,
"text": "Example: This example shows the usage of hide.bs.modal."
},
{
"code": "<!DOCTYPE html><html> <head> <h2 style=\"color:green\"> GeeksForGeeks </h2> <h2 style=\"color:purple\"> Hide Bootstrap Modal </h2> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js\"> </script> <style> #myBtn { width: 300px; padding: 10px; font-size: 20px; position: absolute; margin: 0 auto; right: 0; left: 0; bottom: 50px; z-index: 9999; } </style></head> <body style=\"text-align:center\"> <div class=\"container\"> <h2>Modal Events - hide.bs.modal</h2> <!-- Trigger the modal with a button --> <button type=\"button\" style=\"color:brown\" class=\"btn btn-info btn-md\" id=\"myBtn\"> Hide Modal </button> <!-- Modal --> <div class=\"modal fade\" id=\"myModal\" role=\"dialog\"> <div class=\"modal-dialog\"> <!-- Modal content--> <div class=\"modal-content\"> <div class=\"modal-header\"> <button type=\"button\" class=\"close\" data-dismiss=\"modal\"> × </button> <h4 class=\"modal-title\"> Modal Header: GeeksForGeeks </h4> </div> <div class=\"modal-body\"> <p>The <strong>hide.bs.modal</strong> is going to hide the modal.</p> <p>If you wish to trigger the modal and see the modal get hidden, then press the <strong>'HIDE MODAL'</strong> button. </p> </div> </div> </div> </div> </div> <script> $(document).ready(function() { $(\"#myModal\").modal(\"show\"); $(\"#myBtn\").click(function() { $(\"#myModal\").modal(\"hide\"); }); $(\"#myModal\").on('hide.bs.modal', function() { alert('The modal is about to be hidden.'); }); }); </script></body> </html>",
"e": 27774,
"s": 25143,
"text": null
},
{
"code": null,
"e": 27804,
"s": 27774,
"text": "Output:When we load the code:"
},
{
"code": null,
"e": 27833,
"s": 27804,
"text": "When we click on ‘X’ button:"
},
{
"code": null,
"e": 27844,
"s": 27833,
"text": "The popup:"
},
{
"code": null,
"e": 27852,
"s": 27844,
"text": "Result:"
},
{
"code": null,
"e": 27865,
"s": 27852,
"text": "The working:"
},
{
"code": null,
"e": 27880,
"s": 27865,
"text": "Bootstrap-Misc"
},
{
"code": null,
"e": 27896,
"s": 27880,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 27903,
"s": 27896,
"text": "Picked"
},
{
"code": null,
"e": 27914,
"s": 27903,
"text": "JavaScript"
},
{
"code": null,
"e": 27931,
"s": 27914,
"text": "Web Technologies"
},
{
"code": null,
"e": 28029,
"s": 27931,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28038,
"s": 28029,
"text": "Comments"
},
{
"code": null,
"e": 28051,
"s": 28038,
"text": "Old Comments"
},
{
"code": null,
"e": 28112,
"s": 28051,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28157,
"s": 28112,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28229,
"s": 28157,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 28275,
"s": 28229,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 28323,
"s": 28275,
"text": "How to read a local text file using JavaScript?"
},
{
"code": null,
"e": 28379,
"s": 28323,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 28412,
"s": 28379,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28474,
"s": 28412,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 28517,
"s": 28474,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Apache POI Word - Document
|
Here the term 'document' refers to a MS-Word file. After completion of this chapter, you will be able to create new documents and open existing documents using your Java program.
The following simple program is used to create a blank MS-Word document −
import java.io.File;
import java.io.FileOutputStream;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
public class CreateDocument {
public static void main(String[] args)throws Exception {
//Blank Document
XWPFDocument document = new XWPFDocument();
//Write the Document in file system
FileOutputStream out = new FileOutputStream( new File("createdocument.docx"));
document.write(out);
out.close();
System.out.println("createdocument.docx written successully");
}
}
Save the above Java code as CreateDocument.java, and then compile and execute it from the command prompt as follows −
$javac CreateDocument.java
$java CreateDocument
If your system environment is configured with the POI library, it will compile and execute to generate a blank Word document file named createdocument.docx in your current directory and display the following output in the command prompt −
createdocument.docx written successfully
46 Lectures
3.5 hours
Arnab Chakraborty
23 Lectures
1.5 hours
Mukund Kumar Mishra
16 Lectures
1 hours
Nilay Mehta
52 Lectures
1.5 hours
Bigdata Engineer
14 Lectures
1 hours
Bigdata Engineer
23 Lectures
1 hours
Bigdata Engineer
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2065,
"s": 1886,
"text": "Here the term 'document' refers to a MS-Word file. After completion of this chapter, you will be able to create new documents and open existing documents using your Java program."
},
{
"code": null,
"e": 2139,
"s": 2065,
"text": "The following simple program is used to create a blank MS-Word document −"
},
{
"code": null,
"e": 2662,
"s": 2139,
"text": "import java.io.File;\nimport java.io.FileOutputStream;\nimport org.apache.poi.xwpf.usermodel.XWPFDocument;\n\npublic class CreateDocument {\n public static void main(String[] args)throws Exception {\n //Blank Document\n XWPFDocument document = new XWPFDocument(); \n\t\t\n //Write the Document in file system\n FileOutputStream out = new FileOutputStream( new File(\"createdocument.docx\"));\n document.write(out);\n out.close();\n System.out.println(\"createdocument.docx written successully\");\n }\n}"
},
{
"code": null,
"e": 2780,
"s": 2662,
"text": "Save the above Java code as CreateDocument.java, and then compile and execute it from the command prompt as follows −"
},
{
"code": null,
"e": 2830,
"s": 2780,
"text": "$javac CreateDocument.java\n$java CreateDocument\n"
},
{
"code": null,
"e": 3069,
"s": 2830,
"text": "If your system environment is configured with the POI library, it will compile and execute to generate a blank Word document file named createdocument.docx in your current directory and display the following output in the command prompt −"
},
{
"code": null,
"e": 3111,
"s": 3069,
"text": "createdocument.docx written successfully\n"
},
{
"code": null,
"e": 3146,
"s": 3111,
"text": "\n 46 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 3165,
"s": 3146,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3200,
"s": 3165,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3221,
"s": 3200,
"text": " Mukund Kumar Mishra"
},
{
"code": null,
"e": 3254,
"s": 3221,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3267,
"s": 3254,
"text": " Nilay Mehta"
},
{
"code": null,
"e": 3302,
"s": 3267,
"text": "\n 52 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3320,
"s": 3302,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 3353,
"s": 3320,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3371,
"s": 3353,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 3404,
"s": 3371,
"text": "\n 23 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3422,
"s": 3404,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 3429,
"s": 3422,
"text": " Print"
},
{
"code": null,
"e": 3440,
"s": 3429,
"text": " Add Notes"
}
] |
Hierarchical Clustering and Dendrograms in R for Data Science | by Maria Gulzar | Towards Data Science
|
In the early stages of performing data analysis, an important aspect is to get a high level understanding of the multi-dimensional data and find some sort of pattern between the different variables- this is where clustering comes in. A simple way to define hierarchical clustering is:
`partitioning a huge dataset into smaller groups based on similar characteristics that would help make sense of the data in an informative way.`
Hierarchical Clustering can be classified into 2 types:
· Divisive (Top-down) : A clustering technique in which N nodes belong to a single cluster initially and are then broken down into smaller clusters based on a distance metric until the desired number of clusters is achieved down the hierarchical structure.
· Agglomerative (Bottom-up): A set of N observations in which the closest two nodes are grouped together in a separate cluster to be left with N-1 points, followed by the same pattern recursively until we get one single cluster forming a final dendrogram that encases all clusters solutions in a single tree.
This blogpost will focus upon Agglomerative Hierarchical Clustering, its applications and a practical example in R. By now, two questions should arise in your mind. 1) When we say we group the two closest nodes together, how do we define close? And 2) What will be the merging approach to group them?
To compute distance, several approaches can be used (Euclidean distance being the most common):
· Euclidean distance: a continuous straight line similarity i.e Pythogaros’ Theorem
· Continuous Correlation Similarity
· Binary Manhattan Distance: Absolute distance calculated between two vectors (used where distances cannot be define by a straight line i.e city maps)
Let’s start with a small dataset and understand how Dendrograms are formed in RStudio:
Step 1: Generating random data
I have used normal distribution to compute both x and y coordinates for our dataset and also numbered the datapoints for our understanding.
Set.seed(12)x <- rnorm(10, sd = 1)y <- rnorm(10, sd = 1)plot(x, y, col = "red", pch = 19, cex = 2)text(x + 0.07, y + 0.06, labels = as.character(1:10))
Step 2: Readying our plot to create a dendrogram
First, we store our x and y datasets as x- and y-coordinates of a dataframe. Next, we scale the coordinates to normalize our features with mean of 0 and variance of 1 (standardization). Lastly, we use the dist() function to calculate the distance between the rows of the dataframe.
dF <- data.frame(x = x, y = y)dF <- scale(dF)distxy <- dist(dF)
Step 3: Call hclust()
This forms a hierarchical cluster of the data points based on a distance metric (in this case ‘Euclidean’) on the set of objects in the dataset (in this case 10)
cluster <- hclust(distxy)
Step 4: Create a dendrogram
An alternate way to try this is using plot(as.dendrogram(cluster)) which yields the same result.
plot(cluster, ylab = "Height", xlab="Distance", xlim=c(1,10), ylim=c(1,10))
Step 5: Obtaining your desired number of clusters
Depending on the problem at hand, the number of clusters you want out of your dendrogram varies according to where you draw the line. Here, since the line cuts the height at 1, we get 4 clusters.
abline(h=1.0, col= "blue")
Applications:
From the classification of animal/plant species to determining the similarities in the variants of a virus to categorizing customer segmentation for marketing campaigns, Dendrograms has many uses. For example in customer segmentation, group together people with similar traits and their likelihood to purchase. Once you have the groups, you can run trials on each group with a different marketing copy that will help you better target your future campaigns.
The good and the bad:
Dendrograms are1) an easy way to cluster data through an agglomerative approach and 2) helps understand the data quicker. There is 3) no need to have a pre-defined set of clusters and we can 4) see all the possible linkages in the dataset.
However, the biggest issue with dendrogram is 1) scalability. Having a large dataset with a greater number of observations (i.e. 100+ or 1000+ etc.) will not yield conclusive results at all. It is 2) computationally expensive as a poor agglomerative cluster has a time complexity of O(n3).
|
[
{
"code": null,
"e": 457,
"s": 172,
"text": "In the early stages of performing data analysis, an important aspect is to get a high level understanding of the multi-dimensional data and find some sort of pattern between the different variables- this is where clustering comes in. A simple way to define hierarchical clustering is:"
},
{
"code": null,
"e": 602,
"s": 457,
"text": "`partitioning a huge dataset into smaller groups based on similar characteristics that would help make sense of the data in an informative way.`"
},
{
"code": null,
"e": 658,
"s": 602,
"text": "Hierarchical Clustering can be classified into 2 types:"
},
{
"code": null,
"e": 915,
"s": 658,
"text": "· Divisive (Top-down) : A clustering technique in which N nodes belong to a single cluster initially and are then broken down into smaller clusters based on a distance metric until the desired number of clusters is achieved down the hierarchical structure."
},
{
"code": null,
"e": 1224,
"s": 915,
"text": "· Agglomerative (Bottom-up): A set of N observations in which the closest two nodes are grouped together in a separate cluster to be left with N-1 points, followed by the same pattern recursively until we get one single cluster forming a final dendrogram that encases all clusters solutions in a single tree."
},
{
"code": null,
"e": 1525,
"s": 1224,
"text": "This blogpost will focus upon Agglomerative Hierarchical Clustering, its applications and a practical example in R. By now, two questions should arise in your mind. 1) When we say we group the two closest nodes together, how do we define close? And 2) What will be the merging approach to group them?"
},
{
"code": null,
"e": 1621,
"s": 1525,
"text": "To compute distance, several approaches can be used (Euclidean distance being the most common):"
},
{
"code": null,
"e": 1705,
"s": 1621,
"text": "· Euclidean distance: a continuous straight line similarity i.e Pythogaros’ Theorem"
},
{
"code": null,
"e": 1741,
"s": 1705,
"text": "· Continuous Correlation Similarity"
},
{
"code": null,
"e": 1892,
"s": 1741,
"text": "· Binary Manhattan Distance: Absolute distance calculated between two vectors (used where distances cannot be define by a straight line i.e city maps)"
},
{
"code": null,
"e": 1979,
"s": 1892,
"text": "Let’s start with a small dataset and understand how Dendrograms are formed in RStudio:"
},
{
"code": null,
"e": 2010,
"s": 1979,
"text": "Step 1: Generating random data"
},
{
"code": null,
"e": 2150,
"s": 2010,
"text": "I have used normal distribution to compute both x and y coordinates for our dataset and also numbered the datapoints for our understanding."
},
{
"code": null,
"e": 2302,
"s": 2150,
"text": "Set.seed(12)x <- rnorm(10, sd = 1)y <- rnorm(10, sd = 1)plot(x, y, col = \"red\", pch = 19, cex = 2)text(x + 0.07, y + 0.06, labels = as.character(1:10))"
},
{
"code": null,
"e": 2351,
"s": 2302,
"text": "Step 2: Readying our plot to create a dendrogram"
},
{
"code": null,
"e": 2633,
"s": 2351,
"text": "First, we store our x and y datasets as x- and y-coordinates of a dataframe. Next, we scale the coordinates to normalize our features with mean of 0 and variance of 1 (standardization). Lastly, we use the dist() function to calculate the distance between the rows of the dataframe."
},
{
"code": null,
"e": 2697,
"s": 2633,
"text": "dF <- data.frame(x = x, y = y)dF <- scale(dF)distxy <- dist(dF)"
},
{
"code": null,
"e": 2719,
"s": 2697,
"text": "Step 3: Call hclust()"
},
{
"code": null,
"e": 2881,
"s": 2719,
"text": "This forms a hierarchical cluster of the data points based on a distance metric (in this case ‘Euclidean’) on the set of objects in the dataset (in this case 10)"
},
{
"code": null,
"e": 2907,
"s": 2881,
"text": "cluster <- hclust(distxy)"
},
{
"code": null,
"e": 2935,
"s": 2907,
"text": "Step 4: Create a dendrogram"
},
{
"code": null,
"e": 3032,
"s": 2935,
"text": "An alternate way to try this is using plot(as.dendrogram(cluster)) which yields the same result."
},
{
"code": null,
"e": 3108,
"s": 3032,
"text": "plot(cluster, ylab = \"Height\", xlab=\"Distance\", xlim=c(1,10), ylim=c(1,10))"
},
{
"code": null,
"e": 3158,
"s": 3108,
"text": "Step 5: Obtaining your desired number of clusters"
},
{
"code": null,
"e": 3354,
"s": 3158,
"text": "Depending on the problem at hand, the number of clusters you want out of your dendrogram varies according to where you draw the line. Here, since the line cuts the height at 1, we get 4 clusters."
},
{
"code": null,
"e": 3381,
"s": 3354,
"text": "abline(h=1.0, col= \"blue\")"
},
{
"code": null,
"e": 3395,
"s": 3381,
"text": "Applications:"
},
{
"code": null,
"e": 3853,
"s": 3395,
"text": "From the classification of animal/plant species to determining the similarities in the variants of a virus to categorizing customer segmentation for marketing campaigns, Dendrograms has many uses. For example in customer segmentation, group together people with similar traits and their likelihood to purchase. Once you have the groups, you can run trials on each group with a different marketing copy that will help you better target your future campaigns."
},
{
"code": null,
"e": 3875,
"s": 3853,
"text": "The good and the bad:"
},
{
"code": null,
"e": 4115,
"s": 3875,
"text": "Dendrograms are1) an easy way to cluster data through an agglomerative approach and 2) helps understand the data quicker. There is 3) no need to have a pre-defined set of clusters and we can 4) see all the possible linkages in the dataset."
}
] |
ArrayList retainAll() method in Java - GeeksforGeeks
|
26 Nov, 2018
The retainAll() method of ArrayList is used to remove all the array list’s elements that are not contained in the specified collection or retains all matching elements in the current ArrayList instance that match all elements from the Collection list passed as a parameter to the method.Syntax:
public boolean retainAll(Collection C)
Parameters: The C is the collection containing elements to be retained in the list.Return Value: The method returns a boolean value true if the list is changed at all as a result of the call else false.Exceptions:
ClassCastException: If the class of an element of this ArrayList is incompatible with the Passed collection. This is optional.NullPointerException: If the list contains a null element and the passed collection does not permit null elements, or if the specified collection is null. This is also optional.
ClassCastException: If the class of an element of this ArrayList is incompatible with the Passed collection. This is optional.
NullPointerException: If the list contains a null element and the passed collection does not permit null elements, or if the specified collection is null. This is also optional.
Below programs are used to illustrate the Java.util.ArrayList.retainAll() method:Program 1: Passing ArrayList collection as parameter to method.
// Java code to illustrate retainAll() methodimport java.util.ArrayList;public class GFG { public static void main(String[] args) { // Creating an empty array list ArrayList<String> bags = new ArrayList<String>(); // Add values in the bags list. bags.add("pen"); bags.add("pencil"); bags.add("paper"); // Creating another array list ArrayList<String> boxes = new ArrayList<String>(); // Add values in the boxes list. boxes.add("pen"); boxes.add("paper"); boxes.add("books"); boxes.add("rubber"); // Before Applying method print both lists System.out.println("Bags Contains :" + bags); System.out.println("Boxes Contains :" + boxes); // Apply retainAll() method to boxes passing bags as parameter boxes.retainAll(bags); // Displaying both the lists after operation System.out.println("\nAfter Applying retainAll()"+ " method to Boxes\n"); System.out.println("Bags Contains :" + bags); System.out.println("Boxes Contains :" + boxes); }}
Bags Contains :[pen, pencil, paper]
Boxes Contains :[pen, paper, books, rubber]
After Applying retainAll() method to Boxes
Bags Contains :[pen, pencil, paper]
Boxes Contains :[pen, paper]
Program 2: Passing Collection different than ArrayList as parameter to method.
// Program Demonstrate retainAll() method With// Collection different then ArrayList as a parameter of the methodimport java.util.*; public class GFG { public static void main(String[] args) { // Creating an empty array list HashSet<String> bags = new HashSet<String>(); // Add values in the bags Set. bags.add("pen"); bags.add("ink"); bags.add("paper"); // Creating another empty array list ArrayList<String> boxes = new ArrayList<String>(); // Add values in the boxes list. boxes.add("pen"); boxes.add("paper"); boxes.add("books"); boxes.add("rubber"); boxes.add("ink"); // Before Applying method print both list and set. System.out.println("Bags Contains :" + bags); System.out.println("Boxes Contains :" + boxes); // Apply retainAll() method to boxes passing bags as parameter boxes.retainAll(bags); // Displaying both the lists after operation System.out.println("\nAfter Applying retainAll()" + " method to Boxes\n"); System.out.println("Bags Contains :" + bags); System.out.println("Boxes Contains :" + boxes); }}
Bags Contains :[paper, ink, pen]
Boxes Contains :[pen, paper, books, rubber, ink]
After Applying retainAll() method to Boxes
Bags Contains :[paper, ink, pen]
Boxes Contains :[pen, paper, ink]
Program 3: Illustrating the error thrown by retainAll() method
// Program to illustrate error thrown by retainAll() methodimport java.util.*; public class GFG { public static void main(String[] args) { // Creating an empty array list ArrayList<Integer> list1 = null; /// Creating another empty array list ArrayList<String> list2 = new ArrayList<String>(); // Add values in the list2 list. list2.add("pen"); list2.add("paper"); list2.add("books"); list2.add("rubber"); // Before Applying method print both lists System.out.println("list1 Contains :" + list1); System.out.println("list2 Contains :" + list2); // Apply retainAll() method to list2 passing list1 as parameter list2.retainAll(list1); // Displaying both the lists after operation System.out.println("\nAfter Applying retainAll()"+ " method to list2\n"); System.out.println("list1 Contains :" + list1); System.out.println("list2 Contains :" + list2); }}
Output:
list1 Contains :null
list2 Contains :[pen, paper, books, rubber]
Runtime Error:
Exception in thread "main" java.lang.NullPointerException
at java.util.Objects.requireNonNull(Objects.java:203)
at java.util.ArrayList.retainAll(ArrayList.java:714)
at GFG.main(GFG.java:26)
Reference: https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#retainAll(java.util.Collection)
Java - util package
Java-ArrayList
Java-Collections
Java-Functions
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
How to iterate any Map in Java
Interfaces in Java
Initialize an ArrayList in Java
ArrayList in Java
Multidimensional Arrays in Java
Stack Class in Java
Singleton Class in Java
LinkedList in Java
|
[
{
"code": null,
"e": 23836,
"s": 23808,
"text": "\n26 Nov, 2018"
},
{
"code": null,
"e": 24131,
"s": 23836,
"text": "The retainAll() method of ArrayList is used to remove all the array list’s elements that are not contained in the specified collection or retains all matching elements in the current ArrayList instance that match all elements from the Collection list passed as a parameter to the method.Syntax:"
},
{
"code": null,
"e": 24170,
"s": 24131,
"text": "public boolean retainAll(Collection C)"
},
{
"code": null,
"e": 24384,
"s": 24170,
"text": "Parameters: The C is the collection containing elements to be retained in the list.Return Value: The method returns a boolean value true if the list is changed at all as a result of the call else false.Exceptions:"
},
{
"code": null,
"e": 24688,
"s": 24384,
"text": "ClassCastException: If the class of an element of this ArrayList is incompatible with the Passed collection. This is optional.NullPointerException: If the list contains a null element and the passed collection does not permit null elements, or if the specified collection is null. This is also optional."
},
{
"code": null,
"e": 24815,
"s": 24688,
"text": "ClassCastException: If the class of an element of this ArrayList is incompatible with the Passed collection. This is optional."
},
{
"code": null,
"e": 24993,
"s": 24815,
"text": "NullPointerException: If the list contains a null element and the passed collection does not permit null elements, or if the specified collection is null. This is also optional."
},
{
"code": null,
"e": 25138,
"s": 24993,
"text": "Below programs are used to illustrate the Java.util.ArrayList.retainAll() method:Program 1: Passing ArrayList collection as parameter to method."
},
{
"code": "// Java code to illustrate retainAll() methodimport java.util.ArrayList;public class GFG { public static void main(String[] args) { // Creating an empty array list ArrayList<String> bags = new ArrayList<String>(); // Add values in the bags list. bags.add(\"pen\"); bags.add(\"pencil\"); bags.add(\"paper\"); // Creating another array list ArrayList<String> boxes = new ArrayList<String>(); // Add values in the boxes list. boxes.add(\"pen\"); boxes.add(\"paper\"); boxes.add(\"books\"); boxes.add(\"rubber\"); // Before Applying method print both lists System.out.println(\"Bags Contains :\" + bags); System.out.println(\"Boxes Contains :\" + boxes); // Apply retainAll() method to boxes passing bags as parameter boxes.retainAll(bags); // Displaying both the lists after operation System.out.println(\"\\nAfter Applying retainAll()\"+ \" method to Boxes\\n\"); System.out.println(\"Bags Contains :\" + bags); System.out.println(\"Boxes Contains :\" + boxes); }}",
"e": 26255,
"s": 25138,
"text": null
},
{
"code": null,
"e": 26446,
"s": 26255,
"text": "Bags Contains :[pen, pencil, paper]\nBoxes Contains :[pen, paper, books, rubber]\n\nAfter Applying retainAll() method to Boxes\n\nBags Contains :[pen, pencil, paper]\nBoxes Contains :[pen, paper]\n"
},
{
"code": null,
"e": 26525,
"s": 26446,
"text": "Program 2: Passing Collection different than ArrayList as parameter to method."
},
{
"code": "// Program Demonstrate retainAll() method With// Collection different then ArrayList as a parameter of the methodimport java.util.*; public class GFG { public static void main(String[] args) { // Creating an empty array list HashSet<String> bags = new HashSet<String>(); // Add values in the bags Set. bags.add(\"pen\"); bags.add(\"ink\"); bags.add(\"paper\"); // Creating another empty array list ArrayList<String> boxes = new ArrayList<String>(); // Add values in the boxes list. boxes.add(\"pen\"); boxes.add(\"paper\"); boxes.add(\"books\"); boxes.add(\"rubber\"); boxes.add(\"ink\"); // Before Applying method print both list and set. System.out.println(\"Bags Contains :\" + bags); System.out.println(\"Boxes Contains :\" + boxes); // Apply retainAll() method to boxes passing bags as parameter boxes.retainAll(bags); // Displaying both the lists after operation System.out.println(\"\\nAfter Applying retainAll()\" + \" method to Boxes\\n\"); System.out.println(\"Bags Contains :\" + bags); System.out.println(\"Boxes Contains :\" + boxes); }}",
"e": 27741,
"s": 26525,
"text": null
},
{
"code": null,
"e": 27936,
"s": 27741,
"text": "Bags Contains :[paper, ink, pen]\nBoxes Contains :[pen, paper, books, rubber, ink]\n\nAfter Applying retainAll() method to Boxes\n\nBags Contains :[paper, ink, pen]\nBoxes Contains :[pen, paper, ink]\n"
},
{
"code": null,
"e": 27999,
"s": 27936,
"text": "Program 3: Illustrating the error thrown by retainAll() method"
},
{
"code": "// Program to illustrate error thrown by retainAll() methodimport java.util.*; public class GFG { public static void main(String[] args) { // Creating an empty array list ArrayList<Integer> list1 = null; /// Creating another empty array list ArrayList<String> list2 = new ArrayList<String>(); // Add values in the list2 list. list2.add(\"pen\"); list2.add(\"paper\"); list2.add(\"books\"); list2.add(\"rubber\"); // Before Applying method print both lists System.out.println(\"list1 Contains :\" + list1); System.out.println(\"list2 Contains :\" + list2); // Apply retainAll() method to list2 passing list1 as parameter list2.retainAll(list1); // Displaying both the lists after operation System.out.println(\"\\nAfter Applying retainAll()\"+ \" method to list2\\n\"); System.out.println(\"list1 Contains :\" + list1); System.out.println(\"list2 Contains :\" + list2); }}",
"e": 29007,
"s": 27999,
"text": null
},
{
"code": null,
"e": 29015,
"s": 29007,
"text": "Output:"
},
{
"code": null,
"e": 29080,
"s": 29015,
"text": "list1 Contains :null\nlist2 Contains :[pen, paper, books, rubber]"
},
{
"code": null,
"e": 29095,
"s": 29080,
"text": "Runtime Error:"
},
{
"code": null,
"e": 29297,
"s": 29095,
"text": "Exception in thread \"main\" java.lang.NullPointerException\n at java.util.Objects.requireNonNull(Objects.java:203)\n at java.util.ArrayList.retainAll(ArrayList.java:714)\n at GFG.main(GFG.java:26)"
},
{
"code": null,
"e": 29407,
"s": 29297,
"text": "Reference: https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#retainAll(java.util.Collection)"
},
{
"code": null,
"e": 29427,
"s": 29407,
"text": "Java - util package"
},
{
"code": null,
"e": 29442,
"s": 29427,
"text": "Java-ArrayList"
},
{
"code": null,
"e": 29459,
"s": 29442,
"text": "Java-Collections"
},
{
"code": null,
"e": 29474,
"s": 29459,
"text": "Java-Functions"
},
{
"code": null,
"e": 29479,
"s": 29474,
"text": "Java"
},
{
"code": null,
"e": 29484,
"s": 29479,
"text": "Java"
},
{
"code": null,
"e": 29501,
"s": 29484,
"text": "Java-Collections"
},
{
"code": null,
"e": 29599,
"s": 29501,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29608,
"s": 29599,
"text": "Comments"
},
{
"code": null,
"e": 29621,
"s": 29608,
"text": "Old Comments"
},
{
"code": null,
"e": 29672,
"s": 29621,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 29702,
"s": 29672,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 29733,
"s": 29702,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 29752,
"s": 29733,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 29784,
"s": 29752,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 29802,
"s": 29784,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 29834,
"s": 29802,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 29854,
"s": 29834,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 29878,
"s": 29854,
"text": "Singleton Class in Java"
}
] |
BabelJS - Babel Polyfill
|
Babel Polyfill adds support to the web browsers for features, which are not available. Babel compiles the code from recent ecma version to the one, which we want. It changes the syntax as per the preset, but cannot do anything for the objects or methods used. We have to use polyfill for those features for backward compatibility.
Following is the list of features that need polyfill support when used in older browsers −
Promises
Map
Set
Symbol
Weakmap
Weakset
Array.from, Array.includes, Array.of, Array#find, Array.buffer, Array#findIndex
Object.assign, Object.entries, Object.values
We will create project setup and also see the working of babel polyfill.
npm init
We will now install the packages required for babel.
npm install babel-cli babel-core babel-preset-es2015 --save-dev
npm install @babel/cli @babel/core @babel/preset-env --save-dev
Here is the final package.json −
We will also add es2015 to the presets, as we want to compile the code to es5.
.babelrc for babel 6
.babelrc for babel 7
{
"presets":["@babel/env"]
}
We will install a lite-serve so that we can test our code in browser −
npm install --save-dev lite-server
Let us add babel command to compile our code in package.json −
We have also added the build command which calls the lite-server.
Babel-polyfill gets installed along with the babel-core package. The babel-polyfill will be available in node modules as shown below −
We will further work on promises and use babel-polyfill along with it.
let timingpromise = new Promise((resolve, reject) => {
setTimeout(function() {
resolve("Promise is resolved!");
}, 1000);
});
timingpromise.then((msg) => {
console.log("%c"+msg, "font-size:25px;color:red;");
});
npx babel promise.js --out-file promise_es5.js
"use strict";
var timingpromise = new Promise(function (resolve, reject) {
setTimeout(function () {
resolve("Promise is resolved!");
}, 1000);
});
timingpromise.then(function (msg) {
console.log("%c"+msg, "font-size:25px;color:red;");
});
The compilation need not change anything. The code for promise has been transpiled as it is. But browsers which do not support promises will throw an error even though we have compiled the code to es5.
To solve this issue, we need to add polyfill along with the final es5 compiled code. To run the code in browser, we will take the babel-polyfill file from node modules and add it to the .html file where we want to use promises as shown below −
<html>
<head>
</head>
<body>
<h1>Babel Polyfill Testing</h1>
<script type="text/javascript" src="node_modules/babel-polyfill/dist/polyfill.min.js"></script>
<script type="text/javascript" src="promise_es5.js"></script>
</body>
</html>
In index.html file, we have used the polyfill.min.js file from node_modules followed by promise_es5.js −
<script type="text/javascript" src="node_modules/babel-polyfill/dist/polyfill.min.js"></script>
<script type="text/javascript" src="promise_es5.js"></script>
Note − Polyfill file has to be used at the start before the main javascript call.
String padding adds another string from the left side as per the length specified. The syntax for string padding is as shown below −
str.padStart(length, string);
str.padEnd(length, string);
const str = 'abc';
console.log(str.padStart(8, '_'));
console.log(str.padEnd(8, '_'));
_____abc
abc_____
npx babel strpad.js --out-file strpad_es5.js
'use strict';
var str = 'abc';
console.log(str.padStart(8, '_'));
console.log(str.padEnd(8, '_'));
The js has to be used along with babel-polyfill as shown below −
<!DOCTYPE html>
<html>
<head>
<title>BabelJs Testing </title>
</head>
<body>
<script src="node_modules/babel-polyfill/dist/polyfill.min.js" type="text/javascript"></script>
<script type="text/javascript" src="strpad_es5.js"></script>
</body>
</html>
In this section, we will learn aboutMap, Set, WeakSet, WeakMap.
Map is a object with key / value pair.
Map is a object with key / value pair.
Set is also a object but with unique values.
Set is also a object but with unique values.
WeakMap and WeakSet iare also objects with key/value pairs.
WeakMap and WeakSet iare also objects with key/value pairs.
Map, Set, WeakMap and WeakSet are new features added to ES6. To transpile it to be used in older browsers, we need to make use of polyfill. We will work on an example and use polyfill to compile the code.
let m = new Map(); //map example
m.set("0","A");
m.set("1","B");
console.log(m);
let set = new Set(); //set example
set.add('A');
set.add('B');
set.add('A');
set.add('B');
console.log(set);
let ws = new WeakSet(); //weakset example
let x = {};
let y = {};
ws.add(x);
console.log(ws.has(x));
console.log(ws.has(y));
let wm = new WeakMap(); //weakmap example
let a = {};
wm.set(a, "hello");
console.log(wm.get(a));
Map(2) {"0" => "A", "1" => "B"}
Set(2) {"A", "B"}
true
false
hello
npx babel set.js --out-file set_es5.js
"use strict";
var m = new Map(); //map example
m.set("0", "A");
m.set("1", "B");
console.log(m);
var set = new Set(); //set example
set.add('A');
set.add('B');
set.add('A');
set.add('B');
console.log(set);
var ws = new WeakSet(); //weakset example
var x = {};
var y = {};
ws.add(x);
console.log(ws.has(x));
console.log(ws.has(y));
var wm = new WeakMap(); //weakmap example
var a = {};
wm.set(a, "hello");
console.log(wm.get(a));
The js has to be used along with babel-polyfill as shown below −
<!DOCTYPE html>
<html>
<head>
<title>BabelJs Testing</title>
</head>
<body>
<script src="node_modules/babel-polyfill/dist/polyfill.min.js" type="text/javascript"></script>
<script type="text/javascript" src="set_es5.js"></script>
</body>
</html>
Many properties and methods can be used on array; for example, array.from, array.includes, etc.
Let us consider working on the following example to understand this better.
arraymethods.js
var arrNum = [1, 2, 3];
console.log(arrNum.includes(2));
console.log(Array.from([3, 4, 5], x => x + x));
Output
true
[6, 8, 10]
npx babel arraymethods.js --out-file arraymethods_es5.js
"use strict";
var arrNum = [1, 2, 3];
console.log(arrNum.includes(2));
console.log(Array.from([3, 4, 5], function (x) {
return x + x;
}));
The methods used on the array are printed as they are. To make them work on older browsers, we need to add polyfill file at the start as shown below −
<html>
<head></head>
<body>
<h1>Babel Polyfill Testing</h1>
<script type="text/javascript" src="node_modules/babel-polyfill/dist/polyfill.min.js"></script>
<script type="text/javascript" src="arraymethods_es5.js"></script>
</body>
</html>
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2426,
"s": 2095,
"text": "Babel Polyfill adds support to the web browsers for features, which are not available. Babel compiles the code from recent ecma version to the one, which we want. It changes the syntax as per the preset, but cannot do anything for the objects or methods used. We have to use polyfill for those features for backward compatibility."
},
{
"code": null,
"e": 2517,
"s": 2426,
"text": "Following is the list of features that need polyfill support when used in older browsers −"
},
{
"code": null,
"e": 2526,
"s": 2517,
"text": "Promises"
},
{
"code": null,
"e": 2530,
"s": 2526,
"text": "Map"
},
{
"code": null,
"e": 2534,
"s": 2530,
"text": "Set"
},
{
"code": null,
"e": 2541,
"s": 2534,
"text": "Symbol"
},
{
"code": null,
"e": 2549,
"s": 2541,
"text": "Weakmap"
},
{
"code": null,
"e": 2557,
"s": 2549,
"text": "Weakset"
},
{
"code": null,
"e": 2637,
"s": 2557,
"text": "Array.from, Array.includes, Array.of, Array#find, Array.buffer, Array#findIndex"
},
{
"code": null,
"e": 2682,
"s": 2637,
"text": "Object.assign, Object.entries, Object.values"
},
{
"code": null,
"e": 2755,
"s": 2682,
"text": "We will create project setup and also see the working of babel polyfill."
},
{
"code": null,
"e": 2765,
"s": 2755,
"text": "npm init\n"
},
{
"code": null,
"e": 2818,
"s": 2765,
"text": "We will now install the packages required for babel."
},
{
"code": null,
"e": 2883,
"s": 2818,
"text": "npm install babel-cli babel-core babel-preset-es2015 --save-dev\n"
},
{
"code": null,
"e": 2948,
"s": 2883,
"text": "npm install @babel/cli @babel/core @babel/preset-env --save-dev\n"
},
{
"code": null,
"e": 2981,
"s": 2948,
"text": "Here is the final package.json −"
},
{
"code": null,
"e": 3060,
"s": 2981,
"text": "We will also add es2015 to the presets, as we want to compile the code to es5."
},
{
"code": null,
"e": 3081,
"s": 3060,
"text": ".babelrc for babel 6"
},
{
"code": null,
"e": 3102,
"s": 3081,
"text": ".babelrc for babel 7"
},
{
"code": null,
"e": 3134,
"s": 3102,
"text": "{\n \"presets\":[\"@babel/env\"]\n}"
},
{
"code": null,
"e": 3205,
"s": 3134,
"text": "We will install a lite-serve so that we can test our code in browser −"
},
{
"code": null,
"e": 3241,
"s": 3205,
"text": "npm install --save-dev lite-server\n"
},
{
"code": null,
"e": 3304,
"s": 3241,
"text": "Let us add babel command to compile our code in package.json −"
},
{
"code": null,
"e": 3370,
"s": 3304,
"text": "We have also added the build command which calls the lite-server."
},
{
"code": null,
"e": 3505,
"s": 3370,
"text": "Babel-polyfill gets installed along with the babel-core package. The babel-polyfill will be available in node modules as shown below −"
},
{
"code": null,
"e": 3576,
"s": 3505,
"text": "We will further work on promises and use babel-polyfill along with it."
},
{
"code": null,
"e": 3804,
"s": 3576,
"text": "let timingpromise = new Promise((resolve, reject) => {\n setTimeout(function() {\n resolve(\"Promise is resolved!\");\n }, 1000);\n});\n\ntimingpromise.then((msg) => {\n console.log(\"%c\"+msg, \"font-size:25px;color:red;\");\n});"
},
{
"code": null,
"e": 3852,
"s": 3804,
"text": "npx babel promise.js --out-file promise_es5.js\n"
},
{
"code": null,
"e": 4108,
"s": 3852,
"text": "\"use strict\";\n\nvar timingpromise = new Promise(function (resolve, reject) {\n setTimeout(function () {\n resolve(\"Promise is resolved!\");\n }, 1000);\n});\n\ntimingpromise.then(function (msg) {\n console.log(\"%c\"+msg, \"font-size:25px;color:red;\");\n});"
},
{
"code": null,
"e": 4310,
"s": 4108,
"text": "The compilation need not change anything. The code for promise has been transpiled as it is. But browsers which do not support promises will throw an error even though we have compiled the code to es5."
},
{
"code": null,
"e": 4554,
"s": 4310,
"text": "To solve this issue, we need to add polyfill along with the final es5 compiled code. To run the code in browser, we will take the babel-polyfill file from node modules and add it to the .html file where we want to use promises as shown below −"
},
{
"code": null,
"e": 4819,
"s": 4554,
"text": "<html>\n <head>\n </head>\n <body>\n <h1>Babel Polyfill Testing</h1>\n <script type=\"text/javascript\" src=\"node_modules/babel-polyfill/dist/polyfill.min.js\"></script>\n <script type=\"text/javascript\" src=\"promise_es5.js\"></script>\n </body>\n</html>"
},
{
"code": null,
"e": 4924,
"s": 4819,
"text": "In index.html file, we have used the polyfill.min.js file from node_modules followed by promise_es5.js −"
},
{
"code": null,
"e": 5083,
"s": 4924,
"text": "<script type=\"text/javascript\" src=\"node_modules/babel-polyfill/dist/polyfill.min.js\"></script>\n\n<script type=\"text/javascript\" src=\"promise_es5.js\"></script>"
},
{
"code": null,
"e": 5165,
"s": 5083,
"text": "Note − Polyfill file has to be used at the start before the main javascript call."
},
{
"code": null,
"e": 5298,
"s": 5165,
"text": "String padding adds another string from the left side as per the length specified. The syntax for string padding is as shown below −"
},
{
"code": null,
"e": 5357,
"s": 5298,
"text": "str.padStart(length, string);\nstr.padEnd(length, string);\n"
},
{
"code": null,
"e": 5445,
"s": 5357,
"text": "const str = 'abc';\n\nconsole.log(str.padStart(8, '_'));\nconsole.log(str.padEnd(8, '_'));"
},
{
"code": null,
"e": 5464,
"s": 5445,
"text": "_____abc\nabc_____\n"
},
{
"code": null,
"e": 5509,
"s": 5464,
"text": "npx babel strpad.js --out-file strpad_es5.js"
},
{
"code": null,
"e": 5611,
"s": 5509,
"text": "'use strict';\n\nvar str = 'abc';\n\nconsole.log(str.padStart(8, '_'));\nconsole.log(str.padEnd(8, '_'));\n"
},
{
"code": null,
"e": 5676,
"s": 5611,
"text": "The js has to be used along with babel-polyfill as shown below −"
},
{
"code": null,
"e": 5956,
"s": 5676,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>BabelJs Testing </title>\n </head>\n <body>\n <script src=\"node_modules/babel-polyfill/dist/polyfill.min.js\" type=\"text/javascript\"></script>\n <script type=\"text/javascript\" src=\"strpad_es5.js\"></script>\n </body>\n</html>"
},
{
"code": null,
"e": 6020,
"s": 5956,
"text": "In this section, we will learn aboutMap, Set, WeakSet, WeakMap."
},
{
"code": null,
"e": 6059,
"s": 6020,
"text": "Map is a object with key / value pair."
},
{
"code": null,
"e": 6098,
"s": 6059,
"text": "Map is a object with key / value pair."
},
{
"code": null,
"e": 6143,
"s": 6098,
"text": "Set is also a object but with unique values."
},
{
"code": null,
"e": 6188,
"s": 6143,
"text": "Set is also a object but with unique values."
},
{
"code": null,
"e": 6248,
"s": 6188,
"text": "WeakMap and WeakSet iare also objects with key/value pairs."
},
{
"code": null,
"e": 6308,
"s": 6248,
"text": "WeakMap and WeakSet iare also objects with key/value pairs."
},
{
"code": null,
"e": 6513,
"s": 6308,
"text": "Map, Set, WeakMap and WeakSet are new features added to ES6. To transpile it to be used in older browsers, we need to make use of polyfill. We will work on an example and use polyfill to compile the code."
},
{
"code": null,
"e": 6929,
"s": 6513,
"text": "let m = new Map(); //map example\nm.set(\"0\",\"A\");\nm.set(\"1\",\"B\");\nconsole.log(m);\n\nlet set = new Set(); //set example\nset.add('A');\nset.add('B');\nset.add('A');\nset.add('B');\nconsole.log(set);\n\nlet ws = new WeakSet(); //weakset example\nlet x = {};\nlet y = {};\nws.add(x);\nconsole.log(ws.has(x));\nconsole.log(ws.has(y));\n\nlet wm = new WeakMap(); //weakmap example\nlet a = {};\nwm.set(a, \"hello\");\nconsole.log(wm.get(a));"
},
{
"code": null,
"e": 6997,
"s": 6929,
"text": "Map(2) {\"0\" => \"A\", \"1\" => \"B\"}\nSet(2) {\"A\", \"B\"}\ntrue\nfalse\nhello\n"
},
{
"code": null,
"e": 7037,
"s": 6997,
"text": "npx babel set.js --out-file set_es5.js\n"
},
{
"code": null,
"e": 7470,
"s": 7037,
"text": "\"use strict\";\n\nvar m = new Map(); //map example\nm.set(\"0\", \"A\");\nm.set(\"1\", \"B\");\nconsole.log(m);\n\nvar set = new Set(); //set example\nset.add('A');\nset.add('B');\nset.add('A');\nset.add('B');\nconsole.log(set);\n\nvar ws = new WeakSet(); //weakset example\nvar x = {};\nvar y = {};\nws.add(x);\nconsole.log(ws.has(x));\nconsole.log(ws.has(y));\n\nvar wm = new WeakMap(); //weakmap example\nvar a = {};\nwm.set(a, \"hello\");\nconsole.log(wm.get(a));"
},
{
"code": null,
"e": 7535,
"s": 7470,
"text": "The js has to be used along with babel-polyfill as shown below −"
},
{
"code": null,
"e": 7811,
"s": 7535,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>BabelJs Testing</title>\n </head>\n <body>\n <script src=\"node_modules/babel-polyfill/dist/polyfill.min.js\" type=\"text/javascript\"></script>\n <script type=\"text/javascript\" src=\"set_es5.js\"></script>\n </body>\n</html>"
},
{
"code": null,
"e": 7907,
"s": 7811,
"text": "Many properties and methods can be used on array; for example, array.from, array.includes, etc."
},
{
"code": null,
"e": 7983,
"s": 7907,
"text": "Let us consider working on the following example to understand this better."
},
{
"code": null,
"e": 7999,
"s": 7983,
"text": "arraymethods.js"
},
{
"code": null,
"e": 8105,
"s": 7999,
"text": "var arrNum = [1, 2, 3];\n\nconsole.log(arrNum.includes(2));\nconsole.log(Array.from([3, 4, 5], x => x + x));"
},
{
"code": null,
"e": 8112,
"s": 8105,
"text": "Output"
},
{
"code": null,
"e": 8129,
"s": 8112,
"text": "true\n[6, 8, 10]\n"
},
{
"code": null,
"e": 8187,
"s": 8129,
"text": "npx babel arraymethods.js --out-file arraymethods_es5.js\n"
},
{
"code": null,
"e": 8328,
"s": 8187,
"text": "\"use strict\";\n\nvar arrNum = [1, 2, 3];\n\nconsole.log(arrNum.includes(2));\nconsole.log(Array.from([3, 4, 5], function (x) {\nreturn x + x;\n}));"
},
{
"code": null,
"e": 8479,
"s": 8328,
"text": "The methods used on the array are printed as they are. To make them work on older browsers, we need to add polyfill file at the start as shown below −"
},
{
"code": null,
"e": 8745,
"s": 8479,
"text": "<html>\n <head></head>\n <body>\n <h1>Babel Polyfill Testing</h1>\n <script type=\"text/javascript\" src=\"node_modules/babel-polyfill/dist/polyfill.min.js\"></script>\n <script type=\"text/javascript\" src=\"arraymethods_es5.js\"></script>\n </body>\n</html>"
},
{
"code": null,
"e": 8752,
"s": 8745,
"text": " Print"
},
{
"code": null,
"e": 8763,
"s": 8752,
"text": " Add Notes"
}
] |
Scalable Machine Learning with Dask on Google Cloud | by Jiahao Weng | Towards Data Science
|
Updated on 13 Nov 2021 to reflect latest steps to setup Dask cluster on Google Cloud
Dask has been reviewed by many and compared to various other tools, including Spark, Ray and Vaex. Developed in coordination with other community projects like Numpy, Pandas, and Scikit-Learn, it is definitely a great tool for scaling machine learning.
Hence, the purpose of this article is not to compare the pros and cons of Dask (for that, you can refer to the reference links at the end of this article), but rather to add to existing documentation on the deployment of Dask on cloud and specifically Google Cloud. It definitely also helps that Google Cloud has a free trial for new signups, so you can experiment at no cost.
We list down first the general steps to take before detailing each of the steps with screenshots (feel free to click on each step to navigate). Having a Google Cloud account is the only prerequisite for following this article.
Creating a Kubernetes clusterSetting up HelmDeploying Dask processes and JupyterConnecting to Dask and JupyterConfiguring environmentRemoving your cluster
Creating a Kubernetes cluster
Setting up Helm
Deploying Dask processes and Jupyter
Connecting to Dask and Jupyter
Configuring environment
Removing your cluster
Our first step is to set up a Kubernetes Cluster through Google Kubernetes Engine (GKE).
a) Enable the Kubernetes Engine API after logging in to your Google Cloud console
b) Start Google Cloud Shell
You should see a button similar to the one in red box below in the top right corner of your console page. Click on it and a terminal will pop out. The virtual machine behind this terminal has various tools preinstalled, most importantly kubectl, which is a tool for controlling Kubernetes clusters.
c) Create a managed Kubernetes cluster
Key in the following into Google Cloud Shell to create a managed Kubernetes cluster, replacing <CLUSTERNAME> with a name that can be referred to later.
gcloud container clusters create \ --machine-type n1-standard-4 \ --num-nodes 2 \ --zone us-central1-a \ --cluster-version latest \ <CLUSTERNAME>
A brief description of the parameters in the code above:
machine-type specifies the amount of CPU and RAM for each node. You can choose other types from this list.
num-nodes determines the number of nodes to spin up.
zone refers to the data center zone that your cluster resides in. You can choose somewhere that is not too far away from your users.
While your cluster is initializing, you can also see it spinning up on the Kubernetes Clusters page:
Key in kubernetes clusters in the search bar at the top of your console page.
Select Kubernetes Clusters from the drop down list.
Your cluster with the <CLUSTERNAME> specified can be seen spinning up. Wait till a green tick appears and your cluster is ready.
Alternatively, you can also verify if your cluster is initialized by running:
kubectl get node
When your cluster is deployed, you should see the status as Ready.
d) Provide account permissions to cluster
kubectl create clusterrolebinding cluster-admin-binding \ --clusterrole=cluster-admin \ --user=<GOOGLE-EMAIL-ACCOUNT>
Replace <GOOGLE-EMAIL-ACCOUNT> with the email of the Google account you used to login to Google Cloud.
We will use Helm for installing, upgrading and managing applications on a Kubernetes cluster.
a) Install Helm by running installer script in Google Cloud Shell
curl https://raw.githubusercontent.com/helm/helm/HEAD/scripts/get-helm-3 | bash
b) Verify that Helm is installed properly
helm version
Make sure the version is at least 3.5.
We are almost there... Just a couple more steps before we can start running our machine learning code.
a) Add and update packages information with Dask’s Helm chart repository
helm repo add dask https://helm.dask.org/helm repo update
b) Launch Dask on Kubernetes cluster
helm install my-dask dask/dask --set scheduler.serviceType=LoadBalancer --set jupyter.serviceType=LoadBalancer
This deploys a dask-scheduler, three dask-workers, and also a Jupyter server by default.
Depending on your use case, you may amend the options in the code above:
my-dask is used to reference your Dask setup and you can change to other names.
— set will set the parameters scheduler.serviceType and jupyter.serviceType to the value LoadBalancer. This is necessary to have external IP addresses that we can use to access the Dask dashboard and Jupyter server. Without this option, only cluster IP will be set up by default as mentioned in this Stack Overflow post.
In the previous step, we launched Dask on the cluster. However, it may take a minute to deploy and you can check the status with kubectl after a while:
kubectl get services
Once ready,the external IPs will show up for your Jupyter server (my-dask-jupyter) and Dask scheduler (my-dask-scheduler). If you see <pending> under EXTERNAL-IP, just wait a while more before running the above code again.
Entering the external IP addresses for my-dask-jupyter and my-dask-scheduler in your web browser will allow you to access your Jupyter server and Dask dashboard respectively.
For the Jupyter server, you can log in with default password dask. To change this password, please see the next section.
Congratulations! You can now start running your Dask code :)
Note: If you face 404 error when accessing Jupyter, just click on the Jupyter logo at the top to be directed to the login page.
You may be able to perform some basic Dask code after step 4 but what if you would like to run dask-ml? That is not installed by default. And what if you would like to launch more than the default three workers? How about changing your Jupyter server password?
Hence, we need a way to customize our environment and we can configure it by creating a yaml file. The values in this yaml file will then overwrite the default values of the corresponding parameters in the standard configuration file.
For our illustration, we shall be using the values.yaml below. In general, the configurations are separated into three main sections; one each for the Scheduler, Worker and Jupyter.
To update the configurations, simply perform the following:
In your Google Cloud Shell, run nano values.yaml to create the file values.yaml.
Copy paste the template above (feel free to amend accordingly) and save.
Update your deployment to use this configuration file:
helm upgrade my-dask dask/dask -f values.yaml
Note that you may need to wait a while for the updates to be ready.
Overview of configurations
We also provide below a general description of the commonly used configurations in our template.
a) Install libraries
Under Worker and Jupyter, you can find the sub-section on env. Notice that installation can be via conda or pip and packages are separated by space.
env: # Environment variables. - name: EXTRA_CONDA_PACKAGES value: dask-ml shap -c conda-forge - name: EXTRA_PIP_PACKAGES value: dask-lightgbm --upgrade
b) Number of workers
Number of workers can be specified through replicas parameter. In our case, we requested 4 workers.
worker: replicas: 4 # Number of workers.
c) Resource allocated
Depending on your needs, you can increase the amount of memory or CPUs allocated to your scheduler, workers and/or Jupyter through the resources sub-section.
resources: limits: cpu: 1 memory: 4G requests: cpu: 1 memory: 4G
c) Jupyter password
The Jupyter password is a hashed value under password parameter. You can change your password by replacing this field.
jupyter: password: 'sha1:aae8550c0a44:9507d45e087d5ee481a5ce9f4f16f37a0867318c'
To generate the hashed value of your new password,
Launch a terminal in your Jupyter Launcher first.
Run jupyter notebook password in the command-line and key in your new password. The hashed password will be written to a file named jupyter_notebook_config.json.
View and copy the hashed password.
Replace the password field in values.yaml.
To remove your Helm deployment, execute in Google Cloud Shell:
helm del --purge my-dask
Note that this does not destroy the Kubernetes cluster. To do so, you can delete your cluster from the Kubernetes Cluster page.
Through the guide above, we hope that you are now able to deploy Dask on Google Cloud.
Thanks for reading and I hope the article was useful :) Please also feel free to comment with any questions or suggestions that you may have.
|
[
{
"code": null,
"e": 257,
"s": 172,
"text": "Updated on 13 Nov 2021 to reflect latest steps to setup Dask cluster on Google Cloud"
},
{
"code": null,
"e": 510,
"s": 257,
"text": "Dask has been reviewed by many and compared to various other tools, including Spark, Ray and Vaex. Developed in coordination with other community projects like Numpy, Pandas, and Scikit-Learn, it is definitely a great tool for scaling machine learning."
},
{
"code": null,
"e": 887,
"s": 510,
"text": "Hence, the purpose of this article is not to compare the pros and cons of Dask (for that, you can refer to the reference links at the end of this article), but rather to add to existing documentation on the deployment of Dask on cloud and specifically Google Cloud. It definitely also helps that Google Cloud has a free trial for new signups, so you can experiment at no cost."
},
{
"code": null,
"e": 1114,
"s": 887,
"text": "We list down first the general steps to take before detailing each of the steps with screenshots (feel free to click on each step to navigate). Having a Google Cloud account is the only prerequisite for following this article."
},
{
"code": null,
"e": 1269,
"s": 1114,
"text": "Creating a Kubernetes clusterSetting up HelmDeploying Dask processes and JupyterConnecting to Dask and JupyterConfiguring environmentRemoving your cluster"
},
{
"code": null,
"e": 1299,
"s": 1269,
"text": "Creating a Kubernetes cluster"
},
{
"code": null,
"e": 1315,
"s": 1299,
"text": "Setting up Helm"
},
{
"code": null,
"e": 1352,
"s": 1315,
"text": "Deploying Dask processes and Jupyter"
},
{
"code": null,
"e": 1383,
"s": 1352,
"text": "Connecting to Dask and Jupyter"
},
{
"code": null,
"e": 1407,
"s": 1383,
"text": "Configuring environment"
},
{
"code": null,
"e": 1429,
"s": 1407,
"text": "Removing your cluster"
},
{
"code": null,
"e": 1518,
"s": 1429,
"text": "Our first step is to set up a Kubernetes Cluster through Google Kubernetes Engine (GKE)."
},
{
"code": null,
"e": 1600,
"s": 1518,
"text": "a) Enable the Kubernetes Engine API after logging in to your Google Cloud console"
},
{
"code": null,
"e": 1628,
"s": 1600,
"text": "b) Start Google Cloud Shell"
},
{
"code": null,
"e": 1927,
"s": 1628,
"text": "You should see a button similar to the one in red box below in the top right corner of your console page. Click on it and a terminal will pop out. The virtual machine behind this terminal has various tools preinstalled, most importantly kubectl, which is a tool for controlling Kubernetes clusters."
},
{
"code": null,
"e": 1966,
"s": 1927,
"text": "c) Create a managed Kubernetes cluster"
},
{
"code": null,
"e": 2118,
"s": 1966,
"text": "Key in the following into Google Cloud Shell to create a managed Kubernetes cluster, replacing <CLUSTERNAME> with a name that can be referred to later."
},
{
"code": null,
"e": 2269,
"s": 2118,
"text": "gcloud container clusters create \\ --machine-type n1-standard-4 \\ --num-nodes 2 \\ --zone us-central1-a \\ --cluster-version latest \\ <CLUSTERNAME>"
},
{
"code": null,
"e": 2326,
"s": 2269,
"text": "A brief description of the parameters in the code above:"
},
{
"code": null,
"e": 2433,
"s": 2326,
"text": "machine-type specifies the amount of CPU and RAM for each node. You can choose other types from this list."
},
{
"code": null,
"e": 2486,
"s": 2433,
"text": "num-nodes determines the number of nodes to spin up."
},
{
"code": null,
"e": 2619,
"s": 2486,
"text": "zone refers to the data center zone that your cluster resides in. You can choose somewhere that is not too far away from your users."
},
{
"code": null,
"e": 2720,
"s": 2619,
"text": "While your cluster is initializing, you can also see it spinning up on the Kubernetes Clusters page:"
},
{
"code": null,
"e": 2798,
"s": 2720,
"text": "Key in kubernetes clusters in the search bar at the top of your console page."
},
{
"code": null,
"e": 2850,
"s": 2798,
"text": "Select Kubernetes Clusters from the drop down list."
},
{
"code": null,
"e": 2979,
"s": 2850,
"text": "Your cluster with the <CLUSTERNAME> specified can be seen spinning up. Wait till a green tick appears and your cluster is ready."
},
{
"code": null,
"e": 3057,
"s": 2979,
"text": "Alternatively, you can also verify if your cluster is initialized by running:"
},
{
"code": null,
"e": 3074,
"s": 3057,
"text": "kubectl get node"
},
{
"code": null,
"e": 3141,
"s": 3074,
"text": "When your cluster is deployed, you should see the status as Ready."
},
{
"code": null,
"e": 3183,
"s": 3141,
"text": "d) Provide account permissions to cluster"
},
{
"code": null,
"e": 3303,
"s": 3183,
"text": "kubectl create clusterrolebinding cluster-admin-binding \\ --clusterrole=cluster-admin \\ --user=<GOOGLE-EMAIL-ACCOUNT>"
},
{
"code": null,
"e": 3406,
"s": 3303,
"text": "Replace <GOOGLE-EMAIL-ACCOUNT> with the email of the Google account you used to login to Google Cloud."
},
{
"code": null,
"e": 3500,
"s": 3406,
"text": "We will use Helm for installing, upgrading and managing applications on a Kubernetes cluster."
},
{
"code": null,
"e": 3566,
"s": 3500,
"text": "a) Install Helm by running installer script in Google Cloud Shell"
},
{
"code": null,
"e": 3646,
"s": 3566,
"text": "curl https://raw.githubusercontent.com/helm/helm/HEAD/scripts/get-helm-3 | bash"
},
{
"code": null,
"e": 3688,
"s": 3646,
"text": "b) Verify that Helm is installed properly"
},
{
"code": null,
"e": 3701,
"s": 3688,
"text": "helm version"
},
{
"code": null,
"e": 3740,
"s": 3701,
"text": "Make sure the version is at least 3.5."
},
{
"code": null,
"e": 3843,
"s": 3740,
"text": "We are almost there... Just a couple more steps before we can start running our machine learning code."
},
{
"code": null,
"e": 3916,
"s": 3843,
"text": "a) Add and update packages information with Dask’s Helm chart repository"
},
{
"code": null,
"e": 3974,
"s": 3916,
"text": "helm repo add dask https://helm.dask.org/helm repo update"
},
{
"code": null,
"e": 4011,
"s": 3974,
"text": "b) Launch Dask on Kubernetes cluster"
},
{
"code": null,
"e": 4122,
"s": 4011,
"text": "helm install my-dask dask/dask --set scheduler.serviceType=LoadBalancer --set jupyter.serviceType=LoadBalancer"
},
{
"code": null,
"e": 4211,
"s": 4122,
"text": "This deploys a dask-scheduler, three dask-workers, and also a Jupyter server by default."
},
{
"code": null,
"e": 4284,
"s": 4211,
"text": "Depending on your use case, you may amend the options in the code above:"
},
{
"code": null,
"e": 4364,
"s": 4284,
"text": "my-dask is used to reference your Dask setup and you can change to other names."
},
{
"code": null,
"e": 4685,
"s": 4364,
"text": "— set will set the parameters scheduler.serviceType and jupyter.serviceType to the value LoadBalancer. This is necessary to have external IP addresses that we can use to access the Dask dashboard and Jupyter server. Without this option, only cluster IP will be set up by default as mentioned in this Stack Overflow post."
},
{
"code": null,
"e": 4837,
"s": 4685,
"text": "In the previous step, we launched Dask on the cluster. However, it may take a minute to deploy and you can check the status with kubectl after a while:"
},
{
"code": null,
"e": 4858,
"s": 4837,
"text": "kubectl get services"
},
{
"code": null,
"e": 5081,
"s": 4858,
"text": "Once ready,the external IPs will show up for your Jupyter server (my-dask-jupyter) and Dask scheduler (my-dask-scheduler). If you see <pending> under EXTERNAL-IP, just wait a while more before running the above code again."
},
{
"code": null,
"e": 5256,
"s": 5081,
"text": "Entering the external IP addresses for my-dask-jupyter and my-dask-scheduler in your web browser will allow you to access your Jupyter server and Dask dashboard respectively."
},
{
"code": null,
"e": 5377,
"s": 5256,
"text": "For the Jupyter server, you can log in with default password dask. To change this password, please see the next section."
},
{
"code": null,
"e": 5438,
"s": 5377,
"text": "Congratulations! You can now start running your Dask code :)"
},
{
"code": null,
"e": 5566,
"s": 5438,
"text": "Note: If you face 404 error when accessing Jupyter, just click on the Jupyter logo at the top to be directed to the login page."
},
{
"code": null,
"e": 5827,
"s": 5566,
"text": "You may be able to perform some basic Dask code after step 4 but what if you would like to run dask-ml? That is not installed by default. And what if you would like to launch more than the default three workers? How about changing your Jupyter server password?"
},
{
"code": null,
"e": 6062,
"s": 5827,
"text": "Hence, we need a way to customize our environment and we can configure it by creating a yaml file. The values in this yaml file will then overwrite the default values of the corresponding parameters in the standard configuration file."
},
{
"code": null,
"e": 6244,
"s": 6062,
"text": "For our illustration, we shall be using the values.yaml below. In general, the configurations are separated into three main sections; one each for the Scheduler, Worker and Jupyter."
},
{
"code": null,
"e": 6304,
"s": 6244,
"text": "To update the configurations, simply perform the following:"
},
{
"code": null,
"e": 6385,
"s": 6304,
"text": "In your Google Cloud Shell, run nano values.yaml to create the file values.yaml."
},
{
"code": null,
"e": 6458,
"s": 6385,
"text": "Copy paste the template above (feel free to amend accordingly) and save."
},
{
"code": null,
"e": 6513,
"s": 6458,
"text": "Update your deployment to use this configuration file:"
},
{
"code": null,
"e": 6559,
"s": 6513,
"text": "helm upgrade my-dask dask/dask -f values.yaml"
},
{
"code": null,
"e": 6627,
"s": 6559,
"text": "Note that you may need to wait a while for the updates to be ready."
},
{
"code": null,
"e": 6654,
"s": 6627,
"text": "Overview of configurations"
},
{
"code": null,
"e": 6751,
"s": 6654,
"text": "We also provide below a general description of the commonly used configurations in our template."
},
{
"code": null,
"e": 6772,
"s": 6751,
"text": "a) Install libraries"
},
{
"code": null,
"e": 6921,
"s": 6772,
"text": "Under Worker and Jupyter, you can find the sub-section on env. Notice that installation can be via conda or pip and packages are separated by space."
},
{
"code": null,
"e": 7082,
"s": 6921,
"text": "env: # Environment variables. - name: EXTRA_CONDA_PACKAGES value: dask-ml shap -c conda-forge - name: EXTRA_PIP_PACKAGES value: dask-lightgbm --upgrade"
},
{
"code": null,
"e": 7103,
"s": 7082,
"text": "b) Number of workers"
},
{
"code": null,
"e": 7203,
"s": 7103,
"text": "Number of workers can be specified through replicas parameter. In our case, we requested 4 workers."
},
{
"code": null,
"e": 7246,
"s": 7203,
"text": "worker: replicas: 4 # Number of workers."
},
{
"code": null,
"e": 7268,
"s": 7246,
"text": "c) Resource allocated"
},
{
"code": null,
"e": 7426,
"s": 7268,
"text": "Depending on your needs, you can increase the amount of memory or CPUs allocated to your scheduler, workers and/or Jupyter through the resources sub-section."
},
{
"code": null,
"e": 7505,
"s": 7426,
"text": "resources: limits: cpu: 1 memory: 4G requests: cpu: 1 memory: 4G"
},
{
"code": null,
"e": 7525,
"s": 7505,
"text": "c) Jupyter password"
},
{
"code": null,
"e": 7644,
"s": 7525,
"text": "The Jupyter password is a hashed value under password parameter. You can change your password by replacing this field."
},
{
"code": null,
"e": 7725,
"s": 7644,
"text": "jupyter: password: 'sha1:aae8550c0a44:9507d45e087d5ee481a5ce9f4f16f37a0867318c'"
},
{
"code": null,
"e": 7776,
"s": 7725,
"text": "To generate the hashed value of your new password,"
},
{
"code": null,
"e": 7826,
"s": 7776,
"text": "Launch a terminal in your Jupyter Launcher first."
},
{
"code": null,
"e": 7988,
"s": 7826,
"text": "Run jupyter notebook password in the command-line and key in your new password. The hashed password will be written to a file named jupyter_notebook_config.json."
},
{
"code": null,
"e": 8023,
"s": 7988,
"text": "View and copy the hashed password."
},
{
"code": null,
"e": 8066,
"s": 8023,
"text": "Replace the password field in values.yaml."
},
{
"code": null,
"e": 8129,
"s": 8066,
"text": "To remove your Helm deployment, execute in Google Cloud Shell:"
},
{
"code": null,
"e": 8154,
"s": 8129,
"text": "helm del --purge my-dask"
},
{
"code": null,
"e": 8282,
"s": 8154,
"text": "Note that this does not destroy the Kubernetes cluster. To do so, you can delete your cluster from the Kubernetes Cluster page."
},
{
"code": null,
"e": 8369,
"s": 8282,
"text": "Through the guide above, we hope that you are now able to deploy Dask on Google Cloud."
}
] |
Convert C/C++ code to assembly language - GeeksforGeeks
|
30 Aug, 2021
We use g++ compiler to turn provided C code into assembly language. To see the assembly code generated by the C compiler, we can use the “-S” option on the command line:
Syntax:
$ gcc -S filename.c
This will cause gcc to run the compiler, generating an assembly file. Suppose we write a C code and store it in a file name “geeks.c” .
C
// C code stored in geeks.c file#include <stdio.h> // global stringchar s[] = "GeeksforGeeks"; // Driver Codeint main(){ // Declaring variables int a = 2000, b =17; // Printing statement printf("%s %d \n", s, a+b);}
Running the command:
$ gcc -S geeks.c
This will cause gcc to run the compiler, generating an assembly file geeks.s, and go no further. (Normally it would then invoke the assembler to generate an object- code file.)The assembly-code file contains various declarations including the set of lines:
CPP
.section __TEXT, __text, regular, pure_instructions .macosx_version_min 10, 12 .global _main .align 4, 0x90_main: ## @main .cfi_startproc## BB#0: pushq %rbpLtmp0: .cfi_def_cfa_offset 16Ltmp1: .cfi_offset %rbp, -16 movq %rsp, %rbpLtmp2: .cfi_def_cfa_register %rbp subq $16, %rsp leaq L_.str(%rip), %rdi leaq _s(%rip), %rsi movl $2000, -4(%rbp) ## imm = 0x7D0 movl $17, -8(%rbp) movl -4(%rbp), %eax addl -8(%rbp), %eax movl %eax, %edx movb $0, %al callq _printf xorl %edx, %edx movl %eax, -12(%rbp) ## 4-byte Spill movl %edx, %eax addq $16, %rsp popq %rbp retq .cfi_endproc .section __DATA, __data .global _s ## @s_s: .asciz "GeeksforGeeks" .section __TEXT, __cstring, cstring_literalsL_.str: ## @.str .asciz "%s %d \n" .subsections_via_symbols
Each indented line in the above code corresponds to a single machine instruction. For example, the pushq instruction indicates that the contents of register %rbp should be pushed onto the program stack. All information about local variable names or data types has been stripped away. We still see a reference to the global variable s[]= “GeeksforGeeks”, since the compiler has not yet determined where in memory this variable will be stored.This article is contributed by Sahil Rajput. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
sagar0719kumar
system-programming
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
fork() in C
Command line arguments in C/C++
Function Pointer in C
Substring in C++
Structures in C
Vector in C++ STL
Initialize a vector in C++ (6 different ways)
Inheritance in C++
Map in C++ Standard Template Library (STL)
C++ Classes and Objects
|
[
{
"code": null,
"e": 24878,
"s": 24850,
"text": "\n30 Aug, 2021"
},
{
"code": null,
"e": 25050,
"s": 24878,
"text": "We use g++ compiler to turn provided C code into assembly language. To see the assembly code generated by the C compiler, we can use the “-S” option on the command line: "
},
{
"code": null,
"e": 25060,
"s": 25050,
"text": "Syntax: "
},
{
"code": null,
"e": 25080,
"s": 25060,
"text": "$ gcc -S filename.c"
},
{
"code": null,
"e": 25218,
"s": 25080,
"text": "This will cause gcc to run the compiler, generating an assembly file. Suppose we write a C code and store it in a file name “geeks.c” . "
},
{
"code": null,
"e": 25220,
"s": 25218,
"text": "C"
},
{
"code": "// C code stored in geeks.c file#include <stdio.h> // global stringchar s[] = \"GeeksforGeeks\"; // Driver Codeint main(){ // Declaring variables int a = 2000, b =17; // Printing statement printf(\"%s %d \\n\", s, a+b);}",
"e": 25453,
"s": 25220,
"text": null
},
{
"code": null,
"e": 25475,
"s": 25453,
"text": "Running the command: "
},
{
"code": null,
"e": 25492,
"s": 25475,
"text": "$ gcc -S geeks.c"
},
{
"code": null,
"e": 25750,
"s": 25492,
"text": "This will cause gcc to run the compiler, generating an assembly file geeks.s, and go no further. (Normally it would then invoke the assembler to generate an object- code file.)The assembly-code file contains various declarations including the set of lines: "
},
{
"code": null,
"e": 25754,
"s": 25750,
"text": "CPP"
},
{
"code": " .section __TEXT, __text, regular, pure_instructions .macosx_version_min 10, 12 .global _main .align 4, 0x90_main: ## @main .cfi_startproc## BB#0: pushq %rbpLtmp0: .cfi_def_cfa_offset 16Ltmp1: .cfi_offset %rbp, -16 movq %rsp, %rbpLtmp2: .cfi_def_cfa_register %rbp subq $16, %rsp leaq L_.str(%rip), %rdi leaq _s(%rip), %rsi movl $2000, -4(%rbp) ## imm = 0x7D0 movl $17, -8(%rbp) movl -4(%rbp), %eax addl -8(%rbp), %eax movl %eax, %edx movb $0, %al callq _printf xorl %edx, %edx movl %eax, -12(%rbp) ## 4-byte Spill movl %edx, %eax addq $16, %rsp popq %rbp retq .cfi_endproc .section __DATA, __data .global _s ## @s_s: .asciz \"GeeksforGeeks\" .section __TEXT, __cstring, cstring_literalsL_.str: ## @.str .asciz \"%s %d \\n\" .subsections_via_symbols",
"e": 26774,
"s": 25754,
"text": null
},
{
"code": null,
"e": 27635,
"s": 26774,
"text": "Each indented line in the above code corresponds to a single machine instruction. For example, the pushq instruction indicates that the contents of register %rbp should be pushed onto the program stack. All information about local variable names or data types has been stripped away. We still see a reference to the global variable s[]= “GeeksforGeeks”, since the compiler has not yet determined where in memory this variable will be stored.This article is contributed by Sahil Rajput. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 27650,
"s": 27635,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 27669,
"s": 27650,
"text": "system-programming"
},
{
"code": null,
"e": 27680,
"s": 27669,
"text": "C Language"
},
{
"code": null,
"e": 27684,
"s": 27680,
"text": "C++"
},
{
"code": null,
"e": 27688,
"s": 27684,
"text": "CPP"
},
{
"code": null,
"e": 27786,
"s": 27688,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27798,
"s": 27786,
"text": "fork() in C"
},
{
"code": null,
"e": 27830,
"s": 27798,
"text": "Command line arguments in C/C++"
},
{
"code": null,
"e": 27852,
"s": 27830,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 27869,
"s": 27852,
"text": "Substring in C++"
},
{
"code": null,
"e": 27885,
"s": 27869,
"text": "Structures in C"
},
{
"code": null,
"e": 27903,
"s": 27885,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 27949,
"s": 27903,
"text": "Initialize a vector in C++ (6 different ways)"
},
{
"code": null,
"e": 27968,
"s": 27949,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 28011,
"s": 27968,
"text": "Map in C++ Standard Template Library (STL)"
}
] |
GATE | GATE-CS-2016 (Set 1) | Question 51 - GeeksforGeeks
|
28 Jun, 2021
Let Q denote a queue containing sixteen numbers and S be an empty stack. Head(Q) returns the element at the head of the queue Q without removing it from Q. Similarly Top(S) returns the element at the top of S without removing it from S. Consider the algorithm given below.
The maximum possible number of iterations of the while loop in the algorithm is______
[This Question was originally a Fill-in-the-Blanks question](A) 16(B) 32(C) 256(D) 64Answer: (C)Explanation: The worst case happens when the queue is sorted in decreasing order. In worst case, loop runs n*n times.
Queue: 4 3 2 1
Stack: Empty
3 2 1
4
3 2 1 4
Empty
2 1 4
3
2 1 4 3
Empty
1 4 3
2
1 4 3 2
Empty
4 3 2
1
3 2
1 4
3 2 4
1
2 4
1 3
2 4 3
1
4 3
1 2
3
1 2 4
3 4
1 2
4
1 2 3
Empty
1 2 3 4
Quiz of this QuestionPlease comment below if you find anything wrong in the above post
GATE-CS-2016 (Set 1)
GATE-GATE-CS-2016 (Set 1)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE MOCK 2017 | Question 24
GATE | GATE-CS-2006 | Question 47
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90
|
[
{
"code": null,
"e": 25763,
"s": 25735,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 26036,
"s": 25763,
"text": "Let Q denote a queue containing sixteen numbers and S be an empty stack. Head(Q) returns the element at the head of the queue Q without removing it from Q. Similarly Top(S) returns the element at the top of S without removing it from S. Consider the algorithm given below."
},
{
"code": null,
"e": 26122,
"s": 26036,
"text": "The maximum possible number of iterations of the while loop in the algorithm is______"
},
{
"code": null,
"e": 26336,
"s": 26122,
"text": "[This Question was originally a Fill-in-the-Blanks question](A) 16(B) 32(C) 256(D) 64Answer: (C)Explanation: The worst case happens when the queue is sorted in decreasing order. In worst case, loop runs n*n times."
},
{
"code": null,
"e": 26534,
"s": 26336,
"text": "Queue: 4 3 2 1\nStack: Empty\n\n3 2 1\n4\n\n3 2 1 4\nEmpty\n\n2 1 4\n3\n\n2 1 4 3\nEmpty\n\n1 4 3\n2\n\n1 4 3 2\nEmpty\n\n4 3 2\n1\n\n3 2\n1 4\n\n3 2 4\n1\n\n2 4\n1 3\n\n2 4 3\n1\n\n4 3\n1 2\n\n3 \n1 2 4\n\n3 4 \n1 2\n\n4\n1 2 3\n\nEmpty\n1 2 3 4"
},
{
"code": null,
"e": 26621,
"s": 26534,
"text": "Quiz of this QuestionPlease comment below if you find anything wrong in the above post"
},
{
"code": null,
"e": 26642,
"s": 26621,
"text": "GATE-CS-2016 (Set 1)"
},
{
"code": null,
"e": 26668,
"s": 26642,
"text": "GATE-GATE-CS-2016 (Set 1)"
},
{
"code": null,
"e": 26673,
"s": 26668,
"text": "GATE"
},
{
"code": null,
"e": 26771,
"s": 26673,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26805,
"s": 26771,
"text": "GATE | Gate IT 2007 | Question 25"
},
{
"code": null,
"e": 26839,
"s": 26805,
"text": "GATE | GATE-CS-2001 | Question 39"
},
{
"code": null,
"e": 26873,
"s": 26839,
"text": "GATE | GATE-CS-2000 | Question 41"
},
{
"code": null,
"e": 26906,
"s": 26873,
"text": "GATE | GATE-CS-2005 | Question 6"
},
{
"code": null,
"e": 26942,
"s": 26906,
"text": "GATE | GATE MOCK 2017 | Question 21"
},
{
"code": null,
"e": 26978,
"s": 26942,
"text": "GATE | GATE MOCK 2017 | Question 24"
},
{
"code": null,
"e": 27012,
"s": 26978,
"text": "GATE | GATE-CS-2006 | Question 47"
},
{
"code": null,
"e": 27046,
"s": 27012,
"text": "GATE | Gate IT 2008 | Question 43"
},
{
"code": null,
"e": 27080,
"s": 27046,
"text": "GATE | GATE-CS-2009 | Question 38"
}
] |
GATE | GATE-CS-2003 | Question 64 - GeeksforGeeks
|
28 Jun, 2021
Let S be a stack of size n ≥ 1. Starting with the empty stack, suppose we push the first n natural numbers in sequence, and then perform n pop operations. Assume that Push and pop operation take X seconds each, and Y seconds elapse between the end of one such stack operation and the start of the next operation. For m ≥ 1, define the stack-life of m as the time elapsed from the end of Push(m) to the start of the pop operation that removes m from S. The average stack-life of an element of this stack is(A) n (X + Y)(B) 3Y + 2X(C) n (X + Y) – X(D) Y + 2XAnswer: (C)Explanation: Background required – Stack and Basic Maths
Let Tn be time span of nth element of stack. Let us first find out the sum of Tn for n = 1 to n
Stack Lifetime of last element, Tn = Y (Since it is popped as soon
as it is pushed on the stack)
Stack Lifetime of last element, Tn-1 = Tn + 2X + 2Y
(The time needed to push and then
pop nth element plus two pauses Y each).
= 2X + 3Y
Stack Lifetime of last element, Tn-2 = Tn-1 + 2X + 2Y (Using the Same reasoning above)
= 4X + 5Y
.
.
.
Stack Lifetime of 1st element = 2(n-1)X + (2n-1)Y (Generalizing the pattern)
Sum of all the time spans of all the elements = (Σ 2(n-1)X) + (Σ (2n-1)Y)
for n = 1 to n
= 2X(1 + 2 + . . . + n-1) + Y(1 + 3 + 5 + . . . + (2n-1))
Using 2 identities
Sum of n natural numbers = (n*(n+1))/2 for the first summation
Sn = (n/2)(a+l) Sum of AP series with a as first term and l being last for second summation
Above sum is,
= (2X(n-1)n)/2 + Y(n/2)*(1 + 2n-1)
= n(n(X+Y)-X)
Therefore Average = Sum/n = n(X+Y)-X . Hence Option (c)
This explanation has been contributed by Pranjul Ahuja.Quiz of this Question
GATE-CS-2003
GATE-GATE-CS-2003
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE-CS-2006 | Question 47
GATE | GATE MOCK 2017 | Question 24
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90
|
[
{
"code": null,
"e": 25719,
"s": 25691,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 26343,
"s": 25719,
"text": "Let S be a stack of size n ≥ 1. Starting with the empty stack, suppose we push the first n natural numbers in sequence, and then perform n pop operations. Assume that Push and pop operation take X seconds each, and Y seconds elapse between the end of one such stack operation and the start of the next operation. For m ≥ 1, define the stack-life of m as the time elapsed from the end of Push(m) to the start of the pop operation that removes m from S. The average stack-life of an element of this stack is(A) n (X + Y)(B) 3Y + 2X(C) n (X + Y) – X(D) Y + 2XAnswer: (C)Explanation: Background required – Stack and Basic Maths"
},
{
"code": null,
"e": 26439,
"s": 26343,
"text": "Let Tn be time span of nth element of stack. Let us first find out the sum of Tn for n = 1 to n"
},
{
"code": null,
"e": 27249,
"s": 26439,
"text": "Stack Lifetime of last element, Tn = Y (Since it is popped as soon \n as it is pushed on the stack)\n\nStack Lifetime of last element, Tn-1 = Tn + 2X + 2Y \n (The time needed to push and then\n pop nth element plus two pauses Y each).\n = 2X + 3Y \n\nStack Lifetime of last element, Tn-2 = Tn-1 + 2X + 2Y (Using the Same reasoning above)\n = 4X + 5Y\n.\n.\n.\nStack Lifetime of 1st element = 2(n-1)X + (2n-1)Y (Generalizing the pattern)\n\nSum of all the time spans of all the elements = (Σ 2(n-1)X) + (Σ (2n-1)Y) \n for n = 1 to n\n\n= 2X(1 + 2 + . . . + n-1) + Y(1 + 3 + 5 + . . . + (2n-1))\n\n"
},
{
"code": null,
"e": 27268,
"s": 27249,
"text": "Using 2 identities"
},
{
"code": null,
"e": 27331,
"s": 27268,
"text": "Sum of n natural numbers = (n*(n+1))/2 for the first summation"
},
{
"code": null,
"e": 27423,
"s": 27331,
"text": "Sn = (n/2)(a+l) Sum of AP series with a as first term and l being last for second summation"
},
{
"code": null,
"e": 27437,
"s": 27423,
"text": "Above sum is,"
},
{
"code": null,
"e": 27472,
"s": 27437,
"text": "= (2X(n-1)n)/2 + Y(n/2)*(1 + 2n-1)"
},
{
"code": null,
"e": 27486,
"s": 27472,
"text": "= n(n(X+Y)-X)"
},
{
"code": null,
"e": 27542,
"s": 27486,
"text": "Therefore Average = Sum/n = n(X+Y)-X . Hence Option (c)"
},
{
"code": null,
"e": 27619,
"s": 27542,
"text": "This explanation has been contributed by Pranjul Ahuja.Quiz of this Question"
},
{
"code": null,
"e": 27632,
"s": 27619,
"text": "GATE-CS-2003"
},
{
"code": null,
"e": 27650,
"s": 27632,
"text": "GATE-GATE-CS-2003"
},
{
"code": null,
"e": 27655,
"s": 27650,
"text": "GATE"
},
{
"code": null,
"e": 27753,
"s": 27655,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27787,
"s": 27753,
"text": "GATE | Gate IT 2007 | Question 25"
},
{
"code": null,
"e": 27821,
"s": 27787,
"text": "GATE | GATE-CS-2001 | Question 39"
},
{
"code": null,
"e": 27855,
"s": 27821,
"text": "GATE | GATE-CS-2000 | Question 41"
},
{
"code": null,
"e": 27888,
"s": 27855,
"text": "GATE | GATE-CS-2005 | Question 6"
},
{
"code": null,
"e": 27924,
"s": 27888,
"text": "GATE | GATE MOCK 2017 | Question 21"
},
{
"code": null,
"e": 27958,
"s": 27924,
"text": "GATE | GATE-CS-2006 | Question 47"
},
{
"code": null,
"e": 27994,
"s": 27958,
"text": "GATE | GATE MOCK 2017 | Question 24"
},
{
"code": null,
"e": 28028,
"s": 27994,
"text": "GATE | Gate IT 2008 | Question 43"
},
{
"code": null,
"e": 28062,
"s": 28028,
"text": "GATE | GATE-CS-2009 | Question 38"
}
] |
Convert date string to timestamp in Python - GeeksforGeeks
|
29 Dec, 2020
The Most Common way we use to store dates and times into a Database is in the form of a timestamp. When we receive a date and time in form of a string before storing it into a database, we convert that date and time string into a timestamp. Python provides various ways of converting the date to timestamp. Few of them discussed in this article are:
Using timetuple()
Using timestamp()
Approach:
import datetime is use to import the date and time modules
After importing date time module next step is to accept date string as an input and then store it into a variable
Then we use strptime method. This method takes two arguments:First argument is the string format of the date and timeSecond argument is the format of the input string
First argument is the string format of the date and time
Second argument is the format of the input string
We convert date and time string into a date object
Then we use timetuple() to convert date object into tuple
At the end we use mktime(tuple) to convert the Date tuple into a timestamp.
Example 1:
# Python program to convert # date to timestamp import timeimport datetime string = "20/01/2020"print(time.mktime(datetime.datetime.strptime(string, "%d/%m/%Y").timetuple()))
Output:
1579458600.0
Example 2:
# Python program to convert # date to timestamp import timeimport datetime string = "20/01/2020" element = datetime.datetime.strptime(string,"%d/%m/%Y") tuple = element.timetuple()timestamp = time.mktime(tuple) print(timestamp)
Output:
1579458600.0
Approach:
import datetime is use to import the date and time modules
After importing date time module next step is to accept date string as an input and then store it into a variable
Then we use strptime method. This method takes two argumentsFirst arguments s the string format of the date and timeSecond argument is the format of the input string
First arguments s the string format of the date and time
Second argument is the format of the input string
Then it returns date and time value in timestamp format and we stored this in timestamp variable.
Example 1:
# Python program to convert # date to timestamp import timeimport datetime string = "20/01/2020" element = datetime.datetime.strptime(string,"%d/%m/%Y") timestamp = datetime.datetime.timestamp(element)print(timestamp)
Output:
1579458600.0
Python datetime-program
Python-datetime
Technical Scripter 2019
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
sum() function in Python
|
[
{
"code": null,
"e": 26127,
"s": 26099,
"text": "\n29 Dec, 2020"
},
{
"code": null,
"e": 26477,
"s": 26127,
"text": "The Most Common way we use to store dates and times into a Database is in the form of a timestamp. When we receive a date and time in form of a string before storing it into a database, we convert that date and time string into a timestamp. Python provides various ways of converting the date to timestamp. Few of them discussed in this article are:"
},
{
"code": null,
"e": 26495,
"s": 26477,
"text": "Using timetuple()"
},
{
"code": null,
"e": 26513,
"s": 26495,
"text": "Using timestamp()"
},
{
"code": null,
"e": 26523,
"s": 26513,
"text": "Approach:"
},
{
"code": null,
"e": 26582,
"s": 26523,
"text": "import datetime is use to import the date and time modules"
},
{
"code": null,
"e": 26696,
"s": 26582,
"text": "After importing date time module next step is to accept date string as an input and then store it into a variable"
},
{
"code": null,
"e": 26863,
"s": 26696,
"text": "Then we use strptime method. This method takes two arguments:First argument is the string format of the date and timeSecond argument is the format of the input string"
},
{
"code": null,
"e": 26920,
"s": 26863,
"text": "First argument is the string format of the date and time"
},
{
"code": null,
"e": 26970,
"s": 26920,
"text": "Second argument is the format of the input string"
},
{
"code": null,
"e": 27021,
"s": 26970,
"text": "We convert date and time string into a date object"
},
{
"code": null,
"e": 27079,
"s": 27021,
"text": "Then we use timetuple() to convert date object into tuple"
},
{
"code": null,
"e": 27155,
"s": 27079,
"text": "At the end we use mktime(tuple) to convert the Date tuple into a timestamp."
},
{
"code": null,
"e": 27166,
"s": 27155,
"text": "Example 1:"
},
{
"code": "# Python program to convert # date to timestamp import timeimport datetime string = \"20/01/2020\"print(time.mktime(datetime.datetime.strptime(string, \"%d/%m/%Y\").timetuple()))",
"e": 27391,
"s": 27166,
"text": null
},
{
"code": null,
"e": 27399,
"s": 27391,
"text": "Output:"
},
{
"code": null,
"e": 27413,
"s": 27399,
"text": "1579458600.0\n"
},
{
"code": null,
"e": 27424,
"s": 27413,
"text": "Example 2:"
},
{
"code": "# Python program to convert # date to timestamp import timeimport datetime string = \"20/01/2020\" element = datetime.datetime.strptime(string,\"%d/%m/%Y\") tuple = element.timetuple()timestamp = time.mktime(tuple) print(timestamp)",
"e": 27663,
"s": 27424,
"text": null
},
{
"code": null,
"e": 27671,
"s": 27663,
"text": "Output:"
},
{
"code": null,
"e": 27685,
"s": 27671,
"text": "1579458600.0\n"
},
{
"code": null,
"e": 27695,
"s": 27685,
"text": "Approach:"
},
{
"code": null,
"e": 27754,
"s": 27695,
"text": "import datetime is use to import the date and time modules"
},
{
"code": null,
"e": 27868,
"s": 27754,
"text": "After importing date time module next step is to accept date string as an input and then store it into a variable"
},
{
"code": null,
"e": 28034,
"s": 27868,
"text": "Then we use strptime method. This method takes two argumentsFirst arguments s the string format of the date and timeSecond argument is the format of the input string"
},
{
"code": null,
"e": 28091,
"s": 28034,
"text": "First arguments s the string format of the date and time"
},
{
"code": null,
"e": 28141,
"s": 28091,
"text": "Second argument is the format of the input string"
},
{
"code": null,
"e": 28239,
"s": 28141,
"text": "Then it returns date and time value in timestamp format and we stored this in timestamp variable."
},
{
"code": null,
"e": 28250,
"s": 28239,
"text": "Example 1:"
},
{
"code": "# Python program to convert # date to timestamp import timeimport datetime string = \"20/01/2020\" element = datetime.datetime.strptime(string,\"%d/%m/%Y\") timestamp = datetime.datetime.timestamp(element)print(timestamp)",
"e": 28478,
"s": 28250,
"text": null
},
{
"code": null,
"e": 28486,
"s": 28478,
"text": "Output:"
},
{
"code": null,
"e": 28500,
"s": 28486,
"text": "1579458600.0\n"
},
{
"code": null,
"e": 28524,
"s": 28500,
"text": "Python datetime-program"
},
{
"code": null,
"e": 28540,
"s": 28524,
"text": "Python-datetime"
},
{
"code": null,
"e": 28564,
"s": 28540,
"text": "Technical Scripter 2019"
},
{
"code": null,
"e": 28571,
"s": 28564,
"text": "Python"
},
{
"code": null,
"e": 28590,
"s": 28571,
"text": "Technical Scripter"
},
{
"code": null,
"e": 28688,
"s": 28590,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28706,
"s": 28688,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28738,
"s": 28706,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28760,
"s": 28738,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28802,
"s": 28760,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28831,
"s": 28802,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 28868,
"s": 28831,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 28904,
"s": 28868,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 28946,
"s": 28904,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28988,
"s": 28946,
"text": "How To Convert Python Dictionary To JSON?"
}
] |
How to compare columns in two different tables in SQL - GeeksforGeeks
|
28 Apr, 2022
Here we are going to see how we can compare the columns of two different tables in SQL. We will be taking a few examples to see how we can do this in different ways.
Overview :In this, we will understand overview of SQL query for required operation to perform How to compare columns in two different tables in SQL. We will understand each concept with the help of examples.
Step-1: Creating database :To create the database use the following SQL query as follows.
Syntax –
create database_name;
Example –
create STUDENTS_DATA
Step-2: Using the database :To use this database as follows.
Syntax –
use database_name;
Example –
use STUDENT_DATA
Step-3: Creating table :Creating Table for making queries as follows.
Table-1: Syntax –
create table table_name
(
column1 type,
column2 type,
...
);
Example –
create table studentData1
(
roll_number int primary key,
firstname varchar(100),
lastname varchar(100),
marks int
);
Step-4: Inserting records :Inserting records in table studentData1 as follows.Syntax –
insert into table_name(column1, column2 ...) values (value1, value2 ...);
Inserting into studentData1 table –
insert into studentData1 (roll_number, firstname, lastname, marks)
values (1, 'albert', 'einstein',356);
insert into studentData1 (roll_number, firstname, lastname, marks)
values (2, 'isaac', 'newton',412);
insert into studentData1 (roll_number, firstname, lastname, marks)
values (3, 'marie', 'curie',436);
insert into studentData1 (roll_number, firstname, lastname, marks)
values (4, 'philip', 'jsam',389);
insert into studentData1 (roll_number, firstname, lastname, marks)
values (5, 'tom', 'jsam',452);
insert into studentData1 (roll_number, firstname, lastname, marks)
values (6, 'tucker', 'jose',412);
insert into studentData1 (roll_number, firstname, lastname, marks)
values (7, 'drawn', 'caste',389);
Step-5: Creating table2 :Here, we will create the studentData2 using SQL query as follows.
create table studentData2
(
id int primary key,
firstname varchar(100),
lastname varchar(100),
marks int
);
Step-6: Inserting records :Inserting records in the table studentData2 as follows.
insert into studentData2 (id, firstname, lastname, marks)
values (2, 'isaac', 'newton',412);
insert into studentData2 (id, firstname, lastname, marks)
values (3, 'marie', 'curie',436);
insert into studentData2 (id, firstname, lastname, marks)
values (6, 'tucker', 'jose',412);
insert into studentData2 (id, firstname, lastname, marks)
values (4, 'philip', 'jsam',389);
Example-1 :Using the where clause to compare columns of two different tables. It cannot handle the null values.Syntax :(to select all the records with all columns)
select * from table1, table
where
table1.col1 = table2.col2 and table1.col1 > someValue;
Syntax(Alternative) :(to select specific columns from the tables)
select t1.col1, t2.col2,t3. col3 ...., t2.col1, t2.col2, t2.col3....
from table1 t1, table t2 where t1.col1 = t2.col2 and t1.col1 <> t2.col2;
Query –
select * from studentData1, studentData2
where studentData1.roll_number = studentData2.id;
Output :Result based on the comparison of roll_number and id as follows.
Example-2 :Using joins to compare columns by priority among the table. For example, left join returns all values from the first table and null value for the not-matched records from the second table. Similarly, we can use right join, inner join, full join and self join as per our requirements. In the below example we have compared two tables based on the columns roll_number and id using the left join.
Syntax –
select t1.col1, t1.col2... , t2.col1, t2.col2... ,
from table1 as t1 left
join table2 as t2 on
tabe1.col1 = table2.col1;
Query –
select a.roll_number, a.firstname, b.id
from studentData1 as a left
join
studentData2 as b on
a.roll_number = b.id;
Output :Join based on left table i.e. sutdentData1 as follows.
Example-3 :UNION allows us to compare two same types of tables or datasets. We can use union to compare the columns once we can have the union of both the tables. It can quickly check what are the data missing or changed in either table. It is capable of handling null values which cannot be handled by where clause.
Note – This is only used when we have the same type of tables.
Syntax –
select col1, col2, col3 ....
from (select col1, col2, col3 ...
from Table1 union all select col1, col2, col3 ...
from Table2)
cmpr order by ID;
Example –
select * from
(select * from studentData1
where roll_number > 4
union all
select * from studentData2 where id < 6)
cmpr order by marks;
Output :Compared same records where roll_number > 4 and id < 6 as follows.
kk773572498
sumitgumber28
DBMS-SQL
Picked
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
How to Create a Table With Multiple Foreign Keys in SQL?
What is Temporary Table in SQL?
SQL | Subquery
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL Query to Convert VARCHAR to INT
SQL using Python
How to Write a SQL Query For a Specific Date Range and Date Time?
How to Select Data Between Two Dates and Times in SQL Server?
SQL Query to Compare Two Dates
|
[
{
"code": null,
"e": 25513,
"s": 25485,
"text": "\n28 Apr, 2022"
},
{
"code": null,
"e": 25679,
"s": 25513,
"text": "Here we are going to see how we can compare the columns of two different tables in SQL. We will be taking a few examples to see how we can do this in different ways."
},
{
"code": null,
"e": 25888,
"s": 25679,
"text": "Overview :In this, we will understand overview of SQL query for required operation to perform How to compare columns in two different tables in SQL. We will understand each concept with the help of examples. "
},
{
"code": null,
"e": 25978,
"s": 25888,
"text": "Step-1: Creating database :To create the database use the following SQL query as follows."
},
{
"code": null,
"e": 25988,
"s": 25978,
"text": "Syntax –"
},
{
"code": null,
"e": 26010,
"s": 25988,
"text": "create database_name;"
},
{
"code": null,
"e": 26020,
"s": 26010,
"text": "Example –"
},
{
"code": null,
"e": 26041,
"s": 26020,
"text": "create STUDENTS_DATA"
},
{
"code": null,
"e": 26102,
"s": 26041,
"text": "Step-2: Using the database :To use this database as follows."
},
{
"code": null,
"e": 26111,
"s": 26102,
"text": "Syntax –"
},
{
"code": null,
"e": 26130,
"s": 26111,
"text": "use database_name;"
},
{
"code": null,
"e": 26140,
"s": 26130,
"text": "Example –"
},
{
"code": null,
"e": 26157,
"s": 26140,
"text": "use STUDENT_DATA"
},
{
"code": null,
"e": 26227,
"s": 26157,
"text": "Step-3: Creating table :Creating Table for making queries as follows."
},
{
"code": null,
"e": 26246,
"s": 26227,
"text": "Table-1: Syntax – "
},
{
"code": null,
"e": 26310,
"s": 26246,
"text": "create table table_name\n(\ncolumn1 type, \ncolumn2 type, \n... \n);"
},
{
"code": null,
"e": 26320,
"s": 26310,
"text": "Example –"
},
{
"code": null,
"e": 26441,
"s": 26320,
"text": "create table studentData1 \n(\nroll_number int primary key, \nfirstname varchar(100), \nlastname varchar(100), \nmarks int\n);"
},
{
"code": null,
"e": 26528,
"s": 26441,
"text": "Step-4: Inserting records :Inserting records in table studentData1 as follows.Syntax –"
},
{
"code": null,
"e": 26602,
"s": 26528,
"text": "insert into table_name(column1, column2 ...) values (value1, value2 ...);"
},
{
"code": null,
"e": 26638,
"s": 26602,
"text": "Inserting into studentData1 table –"
},
{
"code": null,
"e": 27354,
"s": 26638,
"text": "insert into studentData1 (roll_number, firstname, lastname, marks) \nvalues (1, 'albert', 'einstein',356);\ninsert into studentData1 (roll_number, firstname, lastname, marks) \nvalues (2, 'isaac', 'newton',412);\ninsert into studentData1 (roll_number, firstname, lastname, marks) \nvalues (3, 'marie', 'curie',436);\ninsert into studentData1 (roll_number, firstname, lastname, marks) \nvalues (4, 'philip', 'jsam',389);\ninsert into studentData1 (roll_number, firstname, lastname, marks) \nvalues (5, 'tom', 'jsam',452);\ninsert into studentData1 (roll_number, firstname, lastname, marks) \nvalues (6, 'tucker', 'jose',412);\ninsert into studentData1 (roll_number, firstname, lastname, marks) \nvalues (7, 'drawn', 'caste',389);"
},
{
"code": null,
"e": 27445,
"s": 27354,
"text": "Step-5: Creating table2 :Here, we will create the studentData2 using SQL query as follows."
},
{
"code": null,
"e": 27557,
"s": 27445,
"text": "create table studentData2 \n(\nid int primary key, \nfirstname varchar(100), \nlastname varchar(100), \nmarks int\n);"
},
{
"code": null,
"e": 27640,
"s": 27557,
"text": "Step-6: Inserting records :Inserting records in the table studentData2 as follows."
},
{
"code": null,
"e": 28013,
"s": 27640,
"text": "insert into studentData2 (id, firstname, lastname, marks) \nvalues (2, 'isaac', 'newton',412);\ninsert into studentData2 (id, firstname, lastname, marks) \nvalues (3, 'marie', 'curie',436);\ninsert into studentData2 (id, firstname, lastname, marks) \nvalues (6, 'tucker', 'jose',412);\ninsert into studentData2 (id, firstname, lastname, marks) \nvalues (4, 'philip', 'jsam',389);"
},
{
"code": null,
"e": 28177,
"s": 28013,
"text": "Example-1 :Using the where clause to compare columns of two different tables. It cannot handle the null values.Syntax :(to select all the records with all columns)"
},
{
"code": null,
"e": 28268,
"s": 28177,
"text": "select * from table1, table \nwhere \ntable1.col1 = table2.col2 and table1.col1 > someValue;"
},
{
"code": null,
"e": 28334,
"s": 28268,
"text": "Syntax(Alternative) :(to select specific columns from the tables)"
},
{
"code": null,
"e": 28478,
"s": 28334,
"text": "select t1.col1, t2.col2,t3. col3 ...., t2.col1, t2.col2, t2.col3.... \nfrom table1 t1, table t2 where t1.col1 = t2.col2 and t1.col1 <> t2.col2;"
},
{
"code": null,
"e": 28486,
"s": 28478,
"text": "Query –"
},
{
"code": null,
"e": 28578,
"s": 28486,
"text": "select * from studentData1, studentData2 \nwhere studentData1.roll_number = studentData2.id;"
},
{
"code": null,
"e": 28651,
"s": 28578,
"text": "Output :Result based on the comparison of roll_number and id as follows."
},
{
"code": null,
"e": 29056,
"s": 28651,
"text": "Example-2 :Using joins to compare columns by priority among the table. For example, left join returns all values from the first table and null value for the not-matched records from the second table. Similarly, we can use right join, inner join, full join and self join as per our requirements. In the below example we have compared two tables based on the columns roll_number and id using the left join."
},
{
"code": null,
"e": 29065,
"s": 29056,
"text": "Syntax –"
},
{
"code": null,
"e": 29189,
"s": 29065,
"text": "select t1.col1, t1.col2... , t2.col1, t2.col2... , \nfrom table1 as t1 left \njoin table2 as t2 on \ntabe1.col1 = table2.col1;"
},
{
"code": null,
"e": 29197,
"s": 29189,
"text": "Query –"
},
{
"code": null,
"e": 29317,
"s": 29197,
"text": "select a.roll_number, a.firstname, b.id \nfrom studentData1 as a left \njoin \nstudentData2 as b on \na.roll_number = b.id;"
},
{
"code": null,
"e": 29380,
"s": 29317,
"text": "Output :Join based on left table i.e. sutdentData1 as follows."
},
{
"code": null,
"e": 29697,
"s": 29380,
"text": "Example-3 :UNION allows us to compare two same types of tables or datasets. We can use union to compare the columns once we can have the union of both the tables. It can quickly check what are the data missing or changed in either table. It is capable of handling null values which cannot be handled by where clause."
},
{
"code": null,
"e": 29760,
"s": 29697,
"text": "Note – This is only used when we have the same type of tables."
},
{
"code": null,
"e": 29769,
"s": 29760,
"text": "Syntax –"
},
{
"code": null,
"e": 29918,
"s": 29769,
"text": "select col1, col2, col3 .... \nfrom (select col1, col2, col3 ... \nfrom Table1 union all select col1, col2, col3 ... \nfrom Table2) \ncmpr order by ID;"
},
{
"code": null,
"e": 29928,
"s": 29918,
"text": "Example –"
},
{
"code": null,
"e": 30069,
"s": 29928,
"text": "select * from \n(select * from studentData1 \nwhere roll_number > 4 \nunion all \nselect * from studentData2 where id < 6) \ncmpr order by marks;"
},
{
"code": null,
"e": 30144,
"s": 30069,
"text": "Output :Compared same records where roll_number > 4 and id < 6 as follows."
},
{
"code": null,
"e": 30156,
"s": 30144,
"text": "kk773572498"
},
{
"code": null,
"e": 30170,
"s": 30156,
"text": "sumitgumber28"
},
{
"code": null,
"e": 30179,
"s": 30170,
"text": "DBMS-SQL"
},
{
"code": null,
"e": 30186,
"s": 30179,
"text": "Picked"
},
{
"code": null,
"e": 30190,
"s": 30186,
"text": "SQL"
},
{
"code": null,
"e": 30194,
"s": 30190,
"text": "SQL"
},
{
"code": null,
"e": 30292,
"s": 30194,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30358,
"s": 30292,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 30415,
"s": 30358,
"text": "How to Create a Table With Multiple Foreign Keys in SQL?"
},
{
"code": null,
"e": 30447,
"s": 30415,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 30462,
"s": 30447,
"text": "SQL | Subquery"
},
{
"code": null,
"e": 30540,
"s": 30462,
"text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter"
},
{
"code": null,
"e": 30576,
"s": 30540,
"text": "SQL Query to Convert VARCHAR to INT"
},
{
"code": null,
"e": 30593,
"s": 30576,
"text": "SQL using Python"
},
{
"code": null,
"e": 30659,
"s": 30593,
"text": "How to Write a SQL Query For a Specific Date Range and Date Time?"
},
{
"code": null,
"e": 30721,
"s": 30659,
"text": "How to Select Data Between Two Dates and Times in SQL Server?"
}
] |
Python-Quizzes | Python List Quiz | Question 2 - GeeksforGeeks
|
17 Sep, 2020
Question 2: Find the output of the following program:
nameList = ['Harsh', 'Pratik', 'Bob', 'Dhruv'] print nameList[1][-1]
(A) r(B) b(C) D(D) kAnswer: (D)Explanation: The index position -1 represents either the last element in a list or the last character in a String. In the above given list of names “nameList”, the index 1 represents the second element i.e, the second string “Pratik” and the index -1 represents the last character in the string “Pratik”. So, the output is “k”.Quiz of this Question
Python-Quizzes
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python-Quizzes | Python List Quiz | Question 4
Python-Quizzes | Python Dictionary Quiz | Question 25
Python-Quizzes | Python List Quiz | Question 5
Python-Quizzes | Python Dictionary Quiz | Question 23
Python | Miscellaneous | Question 1
Python-Quizzes | Miscellaneous | Question 7
Python | Animated Banner showing 'GeeksForGeeks'
Python-Quizzes | Miscellaneous | Question 9
Why do people prefer Selenium with Python?
Output of Python Program - Dictionary (set 25)
|
[
{
"code": null,
"e": 25531,
"s": 25503,
"text": "\n17 Sep, 2020"
},
{
"code": null,
"e": 25585,
"s": 25531,
"text": "Question 2: Find the output of the following program:"
},
{
"code": "nameList = ['Harsh', 'Pratik', 'Bob', 'Dhruv'] print nameList[1][-1] ",
"e": 25657,
"s": 25585,
"text": null
},
{
"code": null,
"e": 26037,
"s": 25657,
"text": "(A) r(B) b(C) D(D) kAnswer: (D)Explanation: The index position -1 represents either the last element in a list or the last character in a String. In the above given list of names “nameList”, the index 1 represents the second element i.e, the second string “Pratik” and the index -1 represents the last character in the string “Pratik”. So, the output is “k”.Quiz of this Question"
},
{
"code": null,
"e": 26052,
"s": 26037,
"text": "Python-Quizzes"
},
{
"code": null,
"e": 26150,
"s": 26052,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26197,
"s": 26150,
"text": "Python-Quizzes | Python List Quiz | Question 4"
},
{
"code": null,
"e": 26251,
"s": 26197,
"text": "Python-Quizzes | Python Dictionary Quiz | Question 25"
},
{
"code": null,
"e": 26298,
"s": 26251,
"text": "Python-Quizzes | Python List Quiz | Question 5"
},
{
"code": null,
"e": 26352,
"s": 26298,
"text": "Python-Quizzes | Python Dictionary Quiz | Question 23"
},
{
"code": null,
"e": 26388,
"s": 26352,
"text": "Python | Miscellaneous | Question 1"
},
{
"code": null,
"e": 26432,
"s": 26388,
"text": "Python-Quizzes | Miscellaneous | Question 7"
},
{
"code": null,
"e": 26481,
"s": 26432,
"text": "Python | Animated Banner showing 'GeeksForGeeks'"
},
{
"code": null,
"e": 26525,
"s": 26481,
"text": "Python-Quizzes | Miscellaneous | Question 9"
},
{
"code": null,
"e": 26568,
"s": 26525,
"text": "Why do people prefer Selenium with Python?"
}
] |
FloatField - Django Models - GeeksforGeeks
|
12 Feb, 2020
FloatField is a floating-point number represented in Python by a float instance. This field is generally used to store huge floating point numbers in the database. The default form widget for this field is a NumberInput when localize is False or TextInput otherwise.
Syntax:
field_name = models.FloatField(**options)
Illustration of FloatField using an Example. Consider a project named geeksforgeeks having an app named geeks.
Refer to the following articles to check how to create a project and an app in Django.
How to Create a Basic Project using MVT in Django?
How to Create an App in Django ?
Enter the following code into models.py file of geeks app.
from django.db import modelsfrom django.db.models import Model# Create your models here. class GeeksModel(Model): geeks_field = models.FloatField()
Add the geeks app to INSTALLED_APPS
# Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'geeks',]
Now when we run makemigrations command from the terminal,
Python manage.py makemigrations
A new folder named migrations would be created in geeks directory with a file named 0001_initial.py
# Generated by Django 2.2.5 on 2019-09-25 06:00 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name ='GeeksModel', fields =[ ('id', models.AutoField( auto_created = True, primary_key = True, serialize = False, verbose_name ='ID' )), ('geeks_field', models.FloatField()), ], ), ]
Now run,
Python manage.py migrate
Thus, an geeks_field FloatField is created when you run migrations on the project. It is a field to store a floating-point number.
FloatField is used for storing a floating-point number represented in Python by a float instance. To know more about float, visit float() in Python. Let’s try to save a flating number in FlatField.
# importing the model# from geeks appfrom geeks.models import GeeksModel # creating an instance of# floatd = float(21.89) # creating a instance of # GeeksModelgeek_object = GeeksModel.objects.create(geeks_field = d)geek_object.save()
Now let’s check it in admin server. We have created an instance of GeeksModel.
Field Options are the arguments given to each field for applying some constraint or imparting a particular characteristic to a particular Field. For example, adding an argument null = True to FloatField will enable it to store empty values for that table in relational database.Here are the field options and attributes that an FloatField can use.
NaveenArora
Django-models
Python Django
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
|
[
{
"code": null,
"e": 25567,
"s": 25539,
"text": "\n12 Feb, 2020"
},
{
"code": null,
"e": 25834,
"s": 25567,
"text": "FloatField is a floating-point number represented in Python by a float instance. This field is generally used to store huge floating point numbers in the database. The default form widget for this field is a NumberInput when localize is False or TextInput otherwise."
},
{
"code": null,
"e": 25842,
"s": 25834,
"text": "Syntax:"
},
{
"code": null,
"e": 25884,
"s": 25842,
"text": "field_name = models.FloatField(**options)"
},
{
"code": null,
"e": 25995,
"s": 25884,
"text": "Illustration of FloatField using an Example. Consider a project named geeksforgeeks having an app named geeks."
},
{
"code": null,
"e": 26082,
"s": 25995,
"text": "Refer to the following articles to check how to create a project and an app in Django."
},
{
"code": null,
"e": 26133,
"s": 26082,
"text": "How to Create a Basic Project using MVT in Django?"
},
{
"code": null,
"e": 26166,
"s": 26133,
"text": "How to Create an App in Django ?"
},
{
"code": null,
"e": 26225,
"s": 26166,
"text": "Enter the following code into models.py file of geeks app."
},
{
"code": "from django.db import modelsfrom django.db.models import Model# Create your models here. class GeeksModel(Model): geeks_field = models.FloatField()",
"e": 26377,
"s": 26225,
"text": null
},
{
"code": null,
"e": 26413,
"s": 26377,
"text": "Add the geeks app to INSTALLED_APPS"
},
{
"code": "# Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'geeks',]",
"e": 26651,
"s": 26413,
"text": null
},
{
"code": null,
"e": 26709,
"s": 26651,
"text": "Now when we run makemigrations command from the terminal,"
},
{
"code": null,
"e": 26741,
"s": 26709,
"text": "Python manage.py makemigrations"
},
{
"code": null,
"e": 26841,
"s": 26741,
"text": "A new folder named migrations would be created in geeks directory with a file named 0001_initial.py"
},
{
"code": "# Generated by Django 2.2.5 on 2019-09-25 06:00 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name ='GeeksModel', fields =[ ('id', models.AutoField( auto_created = True, primary_key = True, serialize = False, verbose_name ='ID' )), ('geeks_field', models.FloatField()), ], ), ]",
"e": 27446,
"s": 26841,
"text": null
},
{
"code": null,
"e": 27455,
"s": 27446,
"text": "Now run,"
},
{
"code": null,
"e": 27480,
"s": 27455,
"text": "Python manage.py migrate"
},
{
"code": null,
"e": 27611,
"s": 27480,
"text": "Thus, an geeks_field FloatField is created when you run migrations on the project. It is a field to store a floating-point number."
},
{
"code": null,
"e": 27809,
"s": 27611,
"text": "FloatField is used for storing a floating-point number represented in Python by a float instance. To know more about float, visit float() in Python. Let’s try to save a flating number in FlatField."
},
{
"code": "# importing the model# from geeks appfrom geeks.models import GeeksModel # creating an instance of# floatd = float(21.89) # creating a instance of # GeeksModelgeek_object = GeeksModel.objects.create(geeks_field = d)geek_object.save()",
"e": 28045,
"s": 27809,
"text": null
},
{
"code": null,
"e": 28124,
"s": 28045,
"text": "Now let’s check it in admin server. We have created an instance of GeeksModel."
},
{
"code": null,
"e": 28472,
"s": 28124,
"text": "Field Options are the arguments given to each field for applying some constraint or imparting a particular characteristic to a particular Field. For example, adding an argument null = True to FloatField will enable it to store empty values for that table in relational database.Here are the field options and attributes that an FloatField can use."
},
{
"code": null,
"e": 28484,
"s": 28472,
"text": "NaveenArora"
},
{
"code": null,
"e": 28498,
"s": 28484,
"text": "Django-models"
},
{
"code": null,
"e": 28512,
"s": 28498,
"text": "Python Django"
},
{
"code": null,
"e": 28519,
"s": 28512,
"text": "Python"
},
{
"code": null,
"e": 28617,
"s": 28519,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28635,
"s": 28617,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28670,
"s": 28635,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28702,
"s": 28670,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28744,
"s": 28702,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28774,
"s": 28744,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 28800,
"s": 28774,
"text": "Python String | replace()"
},
{
"code": null,
"e": 28829,
"s": 28800,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 28873,
"s": 28829,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 28910,
"s": 28873,
"text": "Create a Pandas DataFrame from Lists"
}
] |
PyQt5 QCalendarWidget - Selection Changed signal - GeeksforGeeks
|
08 Jul, 2021
In this article, we will see how we can get the selection changed signal from the QCalendarWidget. Selection changed signal is emitted when the currently selected date is changed. The currently selected date can be changed by the user using the mouse or keyboard.
In order to do this we will use selectionChanged method with the QCalendarWidget object.Syntax : calendar.selectionChanged.connect(lambda: print(“Selection Changed”))Argument : It takes method as argumentAction Performed : It will print the message whenever activated signal get emitted
Below is the implementation
Python3
# importing librariesfrom PyQt5.QtWidgets import *from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import *from PyQt5.QtCore import *import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a QCalendarWidget object calendar = QCalendarWidget(self) # setting geometry to the calendar calendar.setGeometry(10, 10, 400, 250) # creating a label label = QLabel(self) # setting geometry to the label label.setGeometry(100, 280, 250, 60) # making label multi line label.setWordWrap(True) # text text = "Selection Changed signal (No.) : " # current count self.count = 0 # getting the selection change signal and # when receives the signal printing the message calendar.selectionChanged.connect(lambda: label.setText(text + str(get_count()))) # method to increase the count value def get_count(): self.count += 1 return self.count # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :
clintra
Python PyQt-QCalendarWidget
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n08 Jul, 2021"
},
{
"code": null,
"e": 25802,
"s": 25537,
"text": "In this article, we will see how we can get the selection changed signal from the QCalendarWidget. Selection changed signal is emitted when the currently selected date is changed. The currently selected date can be changed by the user using the mouse or keyboard. "
},
{
"code": null,
"e": 26091,
"s": 25802,
"text": "In order to do this we will use selectionChanged method with the QCalendarWidget object.Syntax : calendar.selectionChanged.connect(lambda: print(“Selection Changed”))Argument : It takes method as argumentAction Performed : It will print the message whenever activated signal get emitted "
},
{
"code": null,
"e": 26121,
"s": 26091,
"text": "Below is the implementation "
},
{
"code": null,
"e": 26129,
"s": 26121,
"text": "Python3"
},
{
"code": "# importing librariesfrom PyQt5.QtWidgets import *from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import *from PyQt5.QtCore import *import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a QCalendarWidget object calendar = QCalendarWidget(self) # setting geometry to the calendar calendar.setGeometry(10, 10, 400, 250) # creating a label label = QLabel(self) # setting geometry to the label label.setGeometry(100, 280, 250, 60) # making label multi line label.setWordWrap(True) # text text = \"Selection Changed signal (No.) : \" # current count self.count = 0 # getting the selection change signal and # when receives the signal printing the message calendar.selectionChanged.connect(lambda: label.setText(text + str(get_count()))) # method to increase the count value def get_count(): self.count += 1 return self.count # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())",
"e": 27587,
"s": 26129,
"text": null
},
{
"code": null,
"e": 27598,
"s": 27587,
"text": "Output : "
},
{
"code": null,
"e": 27608,
"s": 27600,
"text": "clintra"
},
{
"code": null,
"e": 27636,
"s": 27608,
"text": "Python PyQt-QCalendarWidget"
},
{
"code": null,
"e": 27647,
"s": 27636,
"text": "Python-gui"
},
{
"code": null,
"e": 27659,
"s": 27647,
"text": "Python-PyQt"
},
{
"code": null,
"e": 27666,
"s": 27659,
"text": "Python"
},
{
"code": null,
"e": 27764,
"s": 27666,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27796,
"s": 27764,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27838,
"s": 27796,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27880,
"s": 27838,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27907,
"s": 27880,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27963,
"s": 27907,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27985,
"s": 27963,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28024,
"s": 27985,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 28055,
"s": 28024,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 28084,
"s": 28055,
"text": "Create a directory in Python"
}
] |
How to read excel file in R ? - GeeksforGeeks
|
26 Mar, 2021
In this article, we will be discussing two different techniques to read or import an excel file in R.
Approach
Import module
Pass path of the file to required function
Read file
Display content
read_excel() function is basically used to import/read an excel file and it can only be accessed after importing of the readxl library in R language..
Syntax:
read_excel(path)
Example:
R
library(readxl) Data_gfg <- read_excel("Data_gfg.xlsx") Data_gfg
Output:
read.xlsx() function is imported from the xlsx library of R language and used to read/import an excel file in R language.
Syntax:
read.xlsx(path)
Example:
R
install.packages("xlsx") Data_gfg <-read.xlsx('Data_gfg.xlsx') Data_gfg
Output:
Picked
R-Excel
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
How to import an Excel File into R ?
Time Series Analysis in R
R - if statement
How to filter R dataframe by multiple conditions?
|
[
{
"code": null,
"e": 26487,
"s": 26459,
"text": "\n26 Mar, 2021"
},
{
"code": null,
"e": 26589,
"s": 26487,
"text": "In this article, we will be discussing two different techniques to read or import an excel file in R."
},
{
"code": null,
"e": 26598,
"s": 26589,
"text": "Approach"
},
{
"code": null,
"e": 26612,
"s": 26598,
"text": "Import module"
},
{
"code": null,
"e": 26655,
"s": 26612,
"text": "Pass path of the file to required function"
},
{
"code": null,
"e": 26665,
"s": 26655,
"text": "Read file"
},
{
"code": null,
"e": 26681,
"s": 26665,
"text": "Display content"
},
{
"code": null,
"e": 26832,
"s": 26681,
"text": "read_excel() function is basically used to import/read an excel file and it can only be accessed after importing of the readxl library in R language.."
},
{
"code": null,
"e": 26840,
"s": 26832,
"text": "Syntax:"
},
{
"code": null,
"e": 26857,
"s": 26840,
"text": "read_excel(path)"
},
{
"code": null,
"e": 26866,
"s": 26857,
"text": "Example:"
},
{
"code": null,
"e": 26868,
"s": 26866,
"text": "R"
},
{
"code": "library(readxl) Data_gfg <- read_excel(\"Data_gfg.xlsx\") Data_gfg",
"e": 26935,
"s": 26868,
"text": null
},
{
"code": null,
"e": 26943,
"s": 26935,
"text": "Output:"
},
{
"code": null,
"e": 27065,
"s": 26943,
"text": "read.xlsx() function is imported from the xlsx library of R language and used to read/import an excel file in R language."
},
{
"code": null,
"e": 27073,
"s": 27065,
"text": "Syntax:"
},
{
"code": null,
"e": 27089,
"s": 27073,
"text": "read.xlsx(path)"
},
{
"code": null,
"e": 27098,
"s": 27089,
"text": "Example:"
},
{
"code": null,
"e": 27100,
"s": 27098,
"text": "R"
},
{
"code": "install.packages(\"xlsx\") Data_gfg <-read.xlsx('Data_gfg.xlsx') Data_gfg",
"e": 27174,
"s": 27100,
"text": null
},
{
"code": null,
"e": 27182,
"s": 27174,
"text": "Output:"
},
{
"code": null,
"e": 27189,
"s": 27182,
"text": "Picked"
},
{
"code": null,
"e": 27197,
"s": 27189,
"text": "R-Excel"
},
{
"code": null,
"e": 27208,
"s": 27197,
"text": "R Language"
},
{
"code": null,
"e": 27306,
"s": 27208,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27358,
"s": 27306,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 27393,
"s": 27358,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 27431,
"s": 27393,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 27489,
"s": 27431,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 27532,
"s": 27489,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 27581,
"s": 27532,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 27618,
"s": 27581,
"text": "How to import an Excel File into R ?"
},
{
"code": null,
"e": 27644,
"s": 27618,
"text": "Time Series Analysis in R"
},
{
"code": null,
"e": 27661,
"s": 27644,
"text": "R - if statement"
}
] |
GATE | GATE-CS-2000 | Question 38 - GeeksforGeeks
|
10 Jul, 2018
Suppose you are given an array s[1..n] and a procedure reverse (s, i, j) which reverses the order of elements in a between positions i and j (both inclusive). What does the following sequence do, where 1 <= k <= n:
reverse(s, 1, k) ;
reverse(s, k + 1, n);
reverse(s, l, n);
(A) Rotates s left by k positions(B) Leaves s unchanged
(C) Reverses all elements of s(D) None of the aboveAnswer: (A)Explanation: Effect of the above 3 reversals for any k is equivalent to left rotation of the array of size n by k. Please see this post for details.If we rotate an array n times for k = 1 to n, we get the same array back.Quiz of this Question
GATE-CS-2000
GATE-GATE-CS-2000
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE-CS-2006 | Question 47
GATE | GATE MOCK 2017 | Question 24
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90
|
[
{
"code": null,
"e": 25455,
"s": 25427,
"text": "\n10 Jul, 2018"
},
{
"code": null,
"e": 25670,
"s": 25455,
"text": "Suppose you are given an array s[1..n] and a procedure reverse (s, i, j) which reverses the order of elements in a between positions i and j (both inclusive). What does the following sequence do, where 1 <= k <= n:"
},
{
"code": null,
"e": 25730,
"s": 25670,
"text": "reverse(s, 1, k) ;\nreverse(s, k + 1, n);\nreverse(s, l, n); "
},
{
"code": null,
"e": 25786,
"s": 25730,
"text": "(A) Rotates s left by k positions(B) Leaves s unchanged"
},
{
"code": null,
"e": 26091,
"s": 25786,
"text": "(C) Reverses all elements of s(D) None of the aboveAnswer: (A)Explanation: Effect of the above 3 reversals for any k is equivalent to left rotation of the array of size n by k. Please see this post for details.If we rotate an array n times for k = 1 to n, we get the same array back.Quiz of this Question"
},
{
"code": null,
"e": 26104,
"s": 26091,
"text": "GATE-CS-2000"
},
{
"code": null,
"e": 26122,
"s": 26104,
"text": "GATE-GATE-CS-2000"
},
{
"code": null,
"e": 26127,
"s": 26122,
"text": "GATE"
},
{
"code": null,
"e": 26225,
"s": 26127,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26259,
"s": 26225,
"text": "GATE | Gate IT 2007 | Question 25"
},
{
"code": null,
"e": 26293,
"s": 26259,
"text": "GATE | GATE-CS-2001 | Question 39"
},
{
"code": null,
"e": 26327,
"s": 26293,
"text": "GATE | GATE-CS-2000 | Question 41"
},
{
"code": null,
"e": 26360,
"s": 26327,
"text": "GATE | GATE-CS-2005 | Question 6"
},
{
"code": null,
"e": 26396,
"s": 26360,
"text": "GATE | GATE MOCK 2017 | Question 21"
},
{
"code": null,
"e": 26430,
"s": 26396,
"text": "GATE | GATE-CS-2006 | Question 47"
},
{
"code": null,
"e": 26466,
"s": 26430,
"text": "GATE | GATE MOCK 2017 | Question 24"
},
{
"code": null,
"e": 26500,
"s": 26466,
"text": "GATE | Gate IT 2008 | Question 43"
},
{
"code": null,
"e": 26534,
"s": 26500,
"text": "GATE | GATE-CS-2009 | Question 38"
}
] |
Different types of range-based for loop iterators in C++ - GeeksforGeeks
|
16 Sep, 2021
Range-Based ‘for’ loops have been included in the language since C++11. It automatically iterates (loops) over the iterable (container). This is very efficient when used with the standard library container (as will be used in this article) as there will be no wrong access to memory outside the scope of the iterable. The loop will automatically start and end at the right place.
Syntax :
for ( range_declaration : range_expression )
loop_statement
There are three different types of range-based ‘for’ loops iterators, which are:
1. Normal Iterators:In normal iterator, an ordinary temporary variable is declared as the iterator, and the iterator gets a copy of the current loop item by value. Any changes made to the temporary copy will not get reflected in the original iterable.
Syntax :
for (datatype iterator : list)
{
// operation are performed here
}
The iterator used is a normal iterator of any data type like int, float, double, etc, which is used to iterate over any type of container.
list can be any type of container.
Here is the implementation of the normal range based iterators :
C++
// C++ program to implements// normal iterators #include <iostream>#include <vector>using namespace std; // Function to implements// normal iteratorsvoid normal_iterator(vector<int> my_iterable){ // Printing the iterable before making // any changes cout << "Value before modification: "; for (int my_iterator : my_iterable) { cout << my_iterator << " "; } // Case where the iterator // makes a temporary copy // of the current loop item for (int my_iterator : my_iterable) { // changing the value of the iterator my_iterator += 1; } cout << "\nValue after modification : "; // Printing the iterable // to see if any changes // has been made in the // original container or not for (int my_iterator : my_iterable) { cout << my_iterator << " "; }}// Driver Codeint main(){ // Initialising a standard // template container vector<int> my_iterable; my_iterable.push_back(101); my_iterable.push_back(102); my_iterable.push_back(103); my_iterable.push_back(104); normal_iterator(my_iterable); return 0;}
Value before modification: 101 102 103 104
Value after modification : 101 102 103 104
2. Reference Iterators :Reference iterators are declared as a reference variable, and the iterator gets the value of the current item by reference. So the changes made inside the loop are definitely get affected in the original container itself.
Syntax :
for (datatype & iterator : list)
{
// operation are performed here
}
The iterator used is a normal iterator of any data type like int, float, double, etc, which is used to iterate over any type of container.
list can be any type of container.
Here is the implementation of the normal range based iterators :
C++
// C++ program to implements// reference iterators #include <iostream>#include <vector>using namespace std; // Function to implements// reference iteratorsvoid reference_iterator(vector<int> my_iterable){ // Printing the iterable before // making any changes cout << "Value before modification: "; for (int my_iterator : my_iterable) { cout << my_iterator << " "; } // Iterating the container // using reference iterator // and updating the value for (int& my_iterator : my_iterable) { my_iterator += 1; } cout << "\nValue after modification : "; for (int my_iterator : my_iterable) { cout << my_iterator << " "; }} // Driver Codeint main(){ // Initialising a standard // template container vector<int> my_iterable; my_iterable.push_back(101); my_iterable.push_back(102); my_iterable.push_back(103); my_iterable.push_back(104); reference_iterator(my_iterable); return 0;}
Value before modification: 101 102 103 104
Value after modification : 102 103 104 105
3. Constant Iterators :Constant iterators are declared as a reference to a constant and in this case, no copy of the current loop item will be made making the execution faster as compared to the above two cases. This is useful in cases where we don’t want any accidental changes in the iterator value or if we are iterating over large items in a container. If we will try to modify the existing value then the compiler will show errors.
Syntax :
for (const datatype iterator : list)
{
// operation are performed here
}
The iterator used is a normal iterator of any data type like int, float, double, etc, which is used to iterate over any type of container.
list can be any type of container.
Here is the implementation of the normal range based iterators :
C++
// C++ program to implements// constant iterators #include <iostream>#include <vector>using namespace std; // Function to implements// constant iteratorsvoid reference_iterator(vector<int> my_iterable){ // Printing the iterable // using constant iterator for (const int& my_iterator : my_iterable) { cout << my_iterator << " "; // Uncomment below line to see the error // my_iterator += 1 ; }} // Driver Codeint main(){ // Initialising a standard // template container vector<int> my_iterable; my_iterable.push_back(101); my_iterable.push_back(102); my_iterable.push_back(103); my_iterable.push_back(104); reference_iterator(my_iterable); return 0;}
101 102 103 104
kk9826225
cpp-iterator
cpp-references
Loops & Control Structure
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Sorting a vector in C++
Friend class and function in C++
std::string class in C++
Pair in C++ Standard Template Library (STL)
Queue in C++ Standard Template Library (STL)
Inline Functions in C++
Array of Strings in C++ (5 Different Ways to Create)
Convert string to char array in C++
|
[
{
"code": null,
"e": 25343,
"s": 25315,
"text": "\n16 Sep, 2021"
},
{
"code": null,
"e": 25724,
"s": 25343,
"text": "Range-Based ‘for’ loops have been included in the language since C++11. It automatically iterates (loops) over the iterable (container). This is very efficient when used with the standard library container (as will be used in this article) as there will be no wrong access to memory outside the scope of the iterable. The loop will automatically start and end at the right place. "
},
{
"code": null,
"e": 25733,
"s": 25724,
"text": "Syntax :"
},
{
"code": null,
"e": 25798,
"s": 25733,
"text": "for ( range_declaration : range_expression ) \n loop_statement"
},
{
"code": null,
"e": 25879,
"s": 25798,
"text": "There are three different types of range-based ‘for’ loops iterators, which are:"
},
{
"code": null,
"e": 26131,
"s": 25879,
"text": "1. Normal Iterators:In normal iterator, an ordinary temporary variable is declared as the iterator, and the iterator gets a copy of the current loop item by value. Any changes made to the temporary copy will not get reflected in the original iterable."
},
{
"code": null,
"e": 26140,
"s": 26131,
"text": "Syntax :"
},
{
"code": null,
"e": 26210,
"s": 26140,
"text": "for (datatype iterator : list)\n{\n // operation are performed here \n}"
},
{
"code": null,
"e": 26349,
"s": 26210,
"text": "The iterator used is a normal iterator of any data type like int, float, double, etc, which is used to iterate over any type of container."
},
{
"code": null,
"e": 26384,
"s": 26349,
"text": "list can be any type of container."
},
{
"code": null,
"e": 26449,
"s": 26384,
"text": "Here is the implementation of the normal range based iterators :"
},
{
"code": null,
"e": 26453,
"s": 26449,
"text": "C++"
},
{
"code": "// C++ program to implements// normal iterators #include <iostream>#include <vector>using namespace std; // Function to implements// normal iteratorsvoid normal_iterator(vector<int> my_iterable){ // Printing the iterable before making // any changes cout << \"Value before modification: \"; for (int my_iterator : my_iterable) { cout << my_iterator << \" \"; } // Case where the iterator // makes a temporary copy // of the current loop item for (int my_iterator : my_iterable) { // changing the value of the iterator my_iterator += 1; } cout << \"\\nValue after modification : \"; // Printing the iterable // to see if any changes // has been made in the // original container or not for (int my_iterator : my_iterable) { cout << my_iterator << \" \"; }}// Driver Codeint main(){ // Initialising a standard // template container vector<int> my_iterable; my_iterable.push_back(101); my_iterable.push_back(102); my_iterable.push_back(103); my_iterable.push_back(104); normal_iterator(my_iterable); return 0;}",
"e": 27564,
"s": 26453,
"text": null
},
{
"code": null,
"e": 27651,
"s": 27564,
"text": "Value before modification: 101 102 103 104 \nValue after modification : 101 102 103 104"
},
{
"code": null,
"e": 27899,
"s": 27653,
"text": "2. Reference Iterators :Reference iterators are declared as a reference variable, and the iterator gets the value of the current item by reference. So the changes made inside the loop are definitely get affected in the original container itself."
},
{
"code": null,
"e": 27908,
"s": 27899,
"text": "Syntax :"
},
{
"code": null,
"e": 27980,
"s": 27908,
"text": "for (datatype & iterator : list)\n{\n // operation are performed here \n}"
},
{
"code": null,
"e": 28119,
"s": 27980,
"text": "The iterator used is a normal iterator of any data type like int, float, double, etc, which is used to iterate over any type of container."
},
{
"code": null,
"e": 28154,
"s": 28119,
"text": "list can be any type of container."
},
{
"code": null,
"e": 28219,
"s": 28154,
"text": "Here is the implementation of the normal range based iterators :"
},
{
"code": null,
"e": 28223,
"s": 28219,
"text": "C++"
},
{
"code": "// C++ program to implements// reference iterators #include <iostream>#include <vector>using namespace std; // Function to implements// reference iteratorsvoid reference_iterator(vector<int> my_iterable){ // Printing the iterable before // making any changes cout << \"Value before modification: \"; for (int my_iterator : my_iterable) { cout << my_iterator << \" \"; } // Iterating the container // using reference iterator // and updating the value for (int& my_iterator : my_iterable) { my_iterator += 1; } cout << \"\\nValue after modification : \"; for (int my_iterator : my_iterable) { cout << my_iterator << \" \"; }} // Driver Codeint main(){ // Initialising a standard // template container vector<int> my_iterable; my_iterable.push_back(101); my_iterable.push_back(102); my_iterable.push_back(103); my_iterable.push_back(104); reference_iterator(my_iterable); return 0;}",
"e": 29188,
"s": 28223,
"text": null
},
{
"code": null,
"e": 29275,
"s": 29188,
"text": "Value before modification: 101 102 103 104 \nValue after modification : 102 103 104 105"
},
{
"code": null,
"e": 29714,
"s": 29277,
"text": "3. Constant Iterators :Constant iterators are declared as a reference to a constant and in this case, no copy of the current loop item will be made making the execution faster as compared to the above two cases. This is useful in cases where we don’t want any accidental changes in the iterator value or if we are iterating over large items in a container. If we will try to modify the existing value then the compiler will show errors."
},
{
"code": null,
"e": 29723,
"s": 29714,
"text": "Syntax :"
},
{
"code": null,
"e": 29799,
"s": 29723,
"text": "for (const datatype iterator : list)\n{\n // operation are performed here \n}"
},
{
"code": null,
"e": 29938,
"s": 29799,
"text": "The iterator used is a normal iterator of any data type like int, float, double, etc, which is used to iterate over any type of container."
},
{
"code": null,
"e": 29973,
"s": 29938,
"text": "list can be any type of container."
},
{
"code": null,
"e": 30038,
"s": 29973,
"text": "Here is the implementation of the normal range based iterators :"
},
{
"code": null,
"e": 30042,
"s": 30038,
"text": "C++"
},
{
"code": "// C++ program to implements// constant iterators #include <iostream>#include <vector>using namespace std; // Function to implements// constant iteratorsvoid reference_iterator(vector<int> my_iterable){ // Printing the iterable // using constant iterator for (const int& my_iterator : my_iterable) { cout << my_iterator << \" \"; // Uncomment below line to see the error // my_iterator += 1 ; }} // Driver Codeint main(){ // Initialising a standard // template container vector<int> my_iterable; my_iterable.push_back(101); my_iterable.push_back(102); my_iterable.push_back(103); my_iterable.push_back(104); reference_iterator(my_iterable); return 0;}",
"e": 30757,
"s": 30042,
"text": null
},
{
"code": null,
"e": 30773,
"s": 30757,
"text": "101 102 103 104"
},
{
"code": null,
"e": 30785,
"s": 30775,
"text": "kk9826225"
},
{
"code": null,
"e": 30798,
"s": 30785,
"text": "cpp-iterator"
},
{
"code": null,
"e": 30813,
"s": 30798,
"text": "cpp-references"
},
{
"code": null,
"e": 30839,
"s": 30813,
"text": "Loops & Control Structure"
},
{
"code": null,
"e": 30843,
"s": 30839,
"text": "C++"
},
{
"code": null,
"e": 30847,
"s": 30843,
"text": "CPP"
},
{
"code": null,
"e": 30945,
"s": 30847,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30973,
"s": 30945,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 30993,
"s": 30973,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 31017,
"s": 30993,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 31050,
"s": 31017,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 31075,
"s": 31050,
"text": "std::string class in C++"
},
{
"code": null,
"e": 31119,
"s": 31075,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 31164,
"s": 31119,
"text": "Queue in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 31188,
"s": 31164,
"text": "Inline Functions in C++"
},
{
"code": null,
"e": 31241,
"s": 31188,
"text": "Array of Strings in C++ (5 Different Ways to Create)"
}
] |
Speech Recognition in Python using Google Speech API - GeeksforGeeks
|
22 Oct, 2017
Speech Recognition is an important feature in several applications used such as home automation, artificial intelligence, etc. This article aims to provide an introduction on how to make use of the SpeechRecognition library of Python. This is useful as it can be used on microcontrollers such as Raspberri Pis with the help of an external microphone.
Required Installations
The following must be installed:
Python Speech Recognition module: sudo pip install SpeechRecognition PyAudio: Use the following command for linux userssudo apt-get install python-pyaudio python3-pyaudioIf the versions in the repositories are too old, install pyaudio using the following commandsudo apt-get install portaudio19-dev python-all-dev python3-all-dev &&
sudo pip install pyaudioUse pip3 instead of pip for python3.Windows users can install pyaudio by executing the following command in a terminalpip install pyaudio
Python Speech Recognition module: sudo pip install SpeechRecognition
sudo pip install SpeechRecognition
PyAudio: Use the following command for linux userssudo apt-get install python-pyaudio python3-pyaudioIf the versions in the repositories are too old, install pyaudio using the following commandsudo apt-get install portaudio19-dev python-all-dev python3-all-dev &&
sudo pip install pyaudioUse pip3 instead of pip for python3.Windows users can install pyaudio by executing the following command in a terminalpip install pyaudio
sudo apt-get install python-pyaudio python3-pyaudio
If the versions in the repositories are too old, install pyaudio using the following command
sudo apt-get install portaudio19-dev python-all-dev python3-all-dev &&
sudo pip install pyaudio
Use pip3 instead of pip for python3.Windows users can install pyaudio by executing the following command in a terminal
pip install pyaudio
Speech Input Using a Microphone and Translation of Speech to Text
Configure Microphone (For external microphones): It is advisable to specify the microphone during the program to avoid any glitches.Type lsusb in the terminal. A list of connected devices will show up. The microphone name would look like thisUSB Device 0x46d:0x825: Audio (hw:1, 0)Make a note of this as it will be used in the program.Set Chunk Size: This basically involved specifying how many bytes of data we want to read at once. Typically, this value is specified in powers of 2 such as 1024 or 2048Set Sampling Rate: Sampling rate defines how often values are recorded for processingSet Device ID to the selected microphone: In this step, we specify the device ID of the microphone that we wish to use in order to avoid ambiguity in case there are multiple microphones. This also helps debug, in the sense that, while running the program, we will know whether the specified microphone is being recognized. During the program, we specify a parameter device_id. The program will say that device_id could not be found if the microphone is not recognized.Allow Adjusting for Ambient Noise: Since the surrounding noise varies, we must allow the program a second or too to adjust the energy threshold of recording so it is adjusted according to the external noise level.Speech to text translation: This is done with the help of Google Speech Recognition. This requires an active internet connection to work. However, there are certain offline Recognition systems such as PocketSphinx, but have a very rigorous installation process that requires several dependencies. Google Speech Recognition is one of the easiest to use.The Above steps have been implemented below:#Python 2.x program for Speech Recognition import speech_recognition as sr #enter the name of usb microphone that you found#using lsusb#the following name is only used as an examplemic_name = "USB Device 0x46d:0x825: Audio (hw:1, 0)"#Sample rate is how often values are recordedsample_rate = 48000#Chunk is like a buffer. It stores 2048 samples (bytes of data)#here. #it is advisable to use powers of 2 such as 1024 or 2048chunk_size = 2048#Initialize the recognizerr = sr.Recognizer() #generate a list of all audio cards/microphonesmic_list = sr.Microphone.list_microphone_names() #the following loop aims to set the device ID of the mic that#we specifically want to use to avoid ambiguity.for i, microphone_name in enumerate(mic_list): if microphone_name == mic_name: device_id = i #use the microphone as source for input. Here, we also specify #which device ID to specifically look for incase the microphone #is not working, an error will pop up saying "device_id undefined"with sr.Microphone(device_index = device_id, sample_rate = sample_rate, chunk_size = chunk_size) as source: #wait for a second to let the recognizer adjust the #energy threshold based on the surrounding noise level r.adjust_for_ambient_noise(source) print "Say Something" #listens for the user's input audio = r.listen(source) try: text = r.recognize_google(audio) print "you said: " + text #error occurs when google could not understand what was said except sr.UnknownValueError: print("Google Speech Recognition could not understand audio") except sr.RequestError as e: print("Could not request results from Google Speech Recognition service; {0}".format(e))Transcribe an Audio file to textIf we have an audio file that we want to translate to text, we simply have to replace the source with the audio file instead of a microphone.Place the audio file and the program in the same folder for convenience. This works for WAV, AIFF, of FLAC files.An implementation has been shown below#Python 2.x program to transcribe an Audio fileimport speech_recognition as sr AUDIO_FILE = ("example.wav") # use the audio file as the audio source r = sr.Recognizer() with sr.AudioFile(AUDIO_FILE) as source: #reads the audio file. Here we use record instead of #listen audio = r.record(source) try: print("The audio file contains: " + r.recognize_google(audio)) except sr.UnknownValueError: print("Google Speech Recognition could not understand audio") except sr.RequestError as e: print("Could not request results from Google Speech Recognition service; {0}".format(e))
Configure Microphone (For external microphones): It is advisable to specify the microphone during the program to avoid any glitches.Type lsusb in the terminal. A list of connected devices will show up. The microphone name would look like thisUSB Device 0x46d:0x825: Audio (hw:1, 0)Make a note of this as it will be used in the program.
USB Device 0x46d:0x825: Audio (hw:1, 0)
Make a note of this as it will be used in the program.
Set Chunk Size: This basically involved specifying how many bytes of data we want to read at once. Typically, this value is specified in powers of 2 such as 1024 or 2048
Set Sampling Rate: Sampling rate defines how often values are recorded for processing
Set Device ID to the selected microphone: In this step, we specify the device ID of the microphone that we wish to use in order to avoid ambiguity in case there are multiple microphones. This also helps debug, in the sense that, while running the program, we will know whether the specified microphone is being recognized. During the program, we specify a parameter device_id. The program will say that device_id could not be found if the microphone is not recognized.
Allow Adjusting for Ambient Noise: Since the surrounding noise varies, we must allow the program a second or too to adjust the energy threshold of recording so it is adjusted according to the external noise level.
Speech to text translation: This is done with the help of Google Speech Recognition. This requires an active internet connection to work. However, there are certain offline Recognition systems such as PocketSphinx, but have a very rigorous installation process that requires several dependencies. Google Speech Recognition is one of the easiest to use.The Above steps have been implemented below:#Python 2.x program for Speech Recognition import speech_recognition as sr #enter the name of usb microphone that you found#using lsusb#the following name is only used as an examplemic_name = "USB Device 0x46d:0x825: Audio (hw:1, 0)"#Sample rate is how often values are recordedsample_rate = 48000#Chunk is like a buffer. It stores 2048 samples (bytes of data)#here. #it is advisable to use powers of 2 such as 1024 or 2048chunk_size = 2048#Initialize the recognizerr = sr.Recognizer() #generate a list of all audio cards/microphonesmic_list = sr.Microphone.list_microphone_names() #the following loop aims to set the device ID of the mic that#we specifically want to use to avoid ambiguity.for i, microphone_name in enumerate(mic_list): if microphone_name == mic_name: device_id = i #use the microphone as source for input. Here, we also specify #which device ID to specifically look for incase the microphone #is not working, an error will pop up saying "device_id undefined"with sr.Microphone(device_index = device_id, sample_rate = sample_rate, chunk_size = chunk_size) as source: #wait for a second to let the recognizer adjust the #energy threshold based on the surrounding noise level r.adjust_for_ambient_noise(source) print "Say Something" #listens for the user's input audio = r.listen(source) try: text = r.recognize_google(audio) print "you said: " + text #error occurs when google could not understand what was said except sr.UnknownValueError: print("Google Speech Recognition could not understand audio") except sr.RequestError as e: print("Could not request results from Google Speech Recognition service; {0}".format(e))Transcribe an Audio file to textIf we have an audio file that we want to translate to text, we simply have to replace the source with the audio file instead of a microphone.Place the audio file and the program in the same folder for convenience. This works for WAV, AIFF, of FLAC files.An implementation has been shown below#Python 2.x program to transcribe an Audio fileimport speech_recognition as sr AUDIO_FILE = ("example.wav") # use the audio file as the audio source r = sr.Recognizer() with sr.AudioFile(AUDIO_FILE) as source: #reads the audio file. Here we use record instead of #listen audio = r.record(source) try: print("The audio file contains: " + r.recognize_google(audio)) except sr.UnknownValueError: print("Google Speech Recognition could not understand audio") except sr.RequestError as e: print("Could not request results from Google Speech Recognition service; {0}".format(e))
The Above steps have been implemented below:
#Python 2.x program for Speech Recognition import speech_recognition as sr #enter the name of usb microphone that you found#using lsusb#the following name is only used as an examplemic_name = "USB Device 0x46d:0x825: Audio (hw:1, 0)"#Sample rate is how often values are recordedsample_rate = 48000#Chunk is like a buffer. It stores 2048 samples (bytes of data)#here. #it is advisable to use powers of 2 such as 1024 or 2048chunk_size = 2048#Initialize the recognizerr = sr.Recognizer() #generate a list of all audio cards/microphonesmic_list = sr.Microphone.list_microphone_names() #the following loop aims to set the device ID of the mic that#we specifically want to use to avoid ambiguity.for i, microphone_name in enumerate(mic_list): if microphone_name == mic_name: device_id = i #use the microphone as source for input. Here, we also specify #which device ID to specifically look for incase the microphone #is not working, an error will pop up saying "device_id undefined"with sr.Microphone(device_index = device_id, sample_rate = sample_rate, chunk_size = chunk_size) as source: #wait for a second to let the recognizer adjust the #energy threshold based on the surrounding noise level r.adjust_for_ambient_noise(source) print "Say Something" #listens for the user's input audio = r.listen(source) try: text = r.recognize_google(audio) print "you said: " + text #error occurs when google could not understand what was said except sr.UnknownValueError: print("Google Speech Recognition could not understand audio") except sr.RequestError as e: print("Could not request results from Google Speech Recognition service; {0}".format(e))
Transcribe an Audio file to text
If we have an audio file that we want to translate to text, we simply have to replace the source with the audio file instead of a microphone.Place the audio file and the program in the same folder for convenience. This works for WAV, AIFF, of FLAC files.An implementation has been shown below
#Python 2.x program to transcribe an Audio fileimport speech_recognition as sr AUDIO_FILE = ("example.wav") # use the audio file as the audio source r = sr.Recognizer() with sr.AudioFile(AUDIO_FILE) as source: #reads the audio file. Here we use record instead of #listen audio = r.record(source) try: print("The audio file contains: " + r.recognize_google(audio)) except sr.UnknownValueError: print("Google Speech Recognition could not understand audio") except sr.RequestError as e: print("Could not request results from Google Speech Recognition service; {0}".format(e))
Troubleshooting
The following problems are commonly encountered
Muted Microphone: This leads to input not being received. To check for this, you can use alsamixer.It can be installed usingsudo apt-get install libasound2 alsa-utils alsa-ossType amixer. The output will look somewhat like thisSimple mixer control 'Master', 0
Capabilities: pvolume pswitch pswitch-joined
Playback channels: Front Left - Front Right
Limits: Playback 0 - 65536
Mono:
Front Left: Playback 41855 [64%] [on]
Front Right: Playback 65536 [100%] [on]
Simple mixer control 'Capture', 0
Capabilities: cvolume cswitch cswitch-joined
Capture channels: Front Left - Front Right
Limits: Capture 0 - 65536
Front Left: Capture 0 [0%] [off] #switched off
Front Right: Capture 0 [0%] [off]
As you can see, the capture device is currently switched off. To switch it on, type alsamixerAs you can see in the first picture, it is displaying our playback devices. Press F4 to toggle to Capture devices.In the second picture, the highlighted portion shows that the capture device is muted. To unmute it, press space barAs you can see in the last picture, the highlighted part confirms that the capture device is not muted.Current microphone not selected as capture device:In this case, the microphone can be set by typing alsamixer and selecting sound cards. Here, you can select default microphone device.As shown in the picture, the highlighted portion is where you have to select sound card.The second picture shows the screen selection for sound cardNo Internet Connection: The speech to text conversion requires an active internet connection.
Muted Microphone: This leads to input not being received. To check for this, you can use alsamixer.It can be installed usingsudo apt-get install libasound2 alsa-utils alsa-ossType amixer. The output will look somewhat like thisSimple mixer control 'Master', 0
Capabilities: pvolume pswitch pswitch-joined
Playback channels: Front Left - Front Right
Limits: Playback 0 - 65536
Mono:
Front Left: Playback 41855 [64%] [on]
Front Right: Playback 65536 [100%] [on]
Simple mixer control 'Capture', 0
Capabilities: cvolume cswitch cswitch-joined
Capture channels: Front Left - Front Right
Limits: Capture 0 - 65536
Front Left: Capture 0 [0%] [off] #switched off
Front Right: Capture 0 [0%] [off]
As you can see, the capture device is currently switched off. To switch it on, type alsamixerAs you can see in the first picture, it is displaying our playback devices. Press F4 to toggle to Capture devices.In the second picture, the highlighted portion shows that the capture device is muted. To unmute it, press space barAs you can see in the last picture, the highlighted part confirms that the capture device is not muted.
sudo apt-get install libasound2 alsa-utils alsa-oss
Type amixer. The output will look somewhat like this
Simple mixer control 'Master', 0
Capabilities: pvolume pswitch pswitch-joined
Playback channels: Front Left - Front Right
Limits: Playback 0 - 65536
Mono:
Front Left: Playback 41855 [64%] [on]
Front Right: Playback 65536 [100%] [on]
Simple mixer control 'Capture', 0
Capabilities: cvolume cswitch cswitch-joined
Capture channels: Front Left - Front Right
Limits: Capture 0 - 65536
Front Left: Capture 0 [0%] [off] #switched off
Front Right: Capture 0 [0%] [off]
As you can see, the capture device is currently switched off. To switch it on, type alsamixerAs you can see in the first picture, it is displaying our playback devices. Press F4 to toggle to Capture devices.
In the second picture, the highlighted portion shows that the capture device is muted. To unmute it, press space bar
As you can see in the last picture, the highlighted part confirms that the capture device is not muted.
Current microphone not selected as capture device:In this case, the microphone can be set by typing alsamixer and selecting sound cards. Here, you can select default microphone device.As shown in the picture, the highlighted portion is where you have to select sound card.The second picture shows the screen selection for sound card
The second picture shows the screen selection for sound card
No Internet Connection: The speech to text conversion requires an active internet connection.
This article is contributed by Deepak Srivatsav. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
python-utility
GBlog
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DSA Sheet by Love Babbar
GET and POST requests using Python
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Types of Software Testing
Working with csv files in Python
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
|
[
{
"code": null,
"e": 26135,
"s": 26107,
"text": "\n22 Oct, 2017"
},
{
"code": null,
"e": 26486,
"s": 26135,
"text": "Speech Recognition is an important feature in several applications used such as home automation, artificial intelligence, etc. This article aims to provide an introduction on how to make use of the SpeechRecognition library of Python. This is useful as it can be used on microcontrollers such as Raspberri Pis with the help of an external microphone."
},
{
"code": null,
"e": 26509,
"s": 26486,
"text": "Required Installations"
},
{
"code": null,
"e": 26542,
"s": 26509,
"text": "The following must be installed:"
},
{
"code": null,
"e": 27038,
"s": 26542,
"text": "Python Speech Recognition module: sudo pip install SpeechRecognition PyAudio: Use the following command for linux userssudo apt-get install python-pyaudio python3-pyaudioIf the versions in the repositories are too old, install pyaudio using the following commandsudo apt-get install portaudio19-dev python-all-dev python3-all-dev && \nsudo pip install pyaudioUse pip3 instead of pip for python3.Windows users can install pyaudio by executing the following command in a terminalpip install pyaudio"
},
{
"code": null,
"e": 27108,
"s": 27038,
"text": "Python Speech Recognition module: sudo pip install SpeechRecognition "
},
{
"code": null,
"e": 27145,
"s": 27108,
"text": " sudo pip install SpeechRecognition "
},
{
"code": null,
"e": 27572,
"s": 27145,
"text": "PyAudio: Use the following command for linux userssudo apt-get install python-pyaudio python3-pyaudioIf the versions in the repositories are too old, install pyaudio using the following commandsudo apt-get install portaudio19-dev python-all-dev python3-all-dev && \nsudo pip install pyaudioUse pip3 instead of pip for python3.Windows users can install pyaudio by executing the following command in a terminalpip install pyaudio"
},
{
"code": null,
"e": 27624,
"s": 27572,
"text": "sudo apt-get install python-pyaudio python3-pyaudio"
},
{
"code": null,
"e": 27717,
"s": 27624,
"text": "If the versions in the repositories are too old, install pyaudio using the following command"
},
{
"code": null,
"e": 27814,
"s": 27717,
"text": "sudo apt-get install portaudio19-dev python-all-dev python3-all-dev && \nsudo pip install pyaudio"
},
{
"code": null,
"e": 27933,
"s": 27814,
"text": "Use pip3 instead of pip for python3.Windows users can install pyaudio by executing the following command in a terminal"
},
{
"code": null,
"e": 27953,
"s": 27933,
"text": "pip install pyaudio"
},
{
"code": null,
"e": 28019,
"s": 27953,
"text": "Speech Input Using a Microphone and Translation of Speech to Text"
},
{
"code": null,
"e": 32419,
"s": 28019,
"text": "Configure Microphone (For external microphones): It is advisable to specify the microphone during the program to avoid any glitches.Type lsusb in the terminal. A list of connected devices will show up. The microphone name would look like thisUSB Device 0x46d:0x825: Audio (hw:1, 0)Make a note of this as it will be used in the program.Set Chunk Size: This basically involved specifying how many bytes of data we want to read at once. Typically, this value is specified in powers of 2 such as 1024 or 2048Set Sampling Rate: Sampling rate defines how often values are recorded for processingSet Device ID to the selected microphone: In this step, we specify the device ID of the microphone that we wish to use in order to avoid ambiguity in case there are multiple microphones. This also helps debug, in the sense that, while running the program, we will know whether the specified microphone is being recognized. During the program, we specify a parameter device_id. The program will say that device_id could not be found if the microphone is not recognized.Allow Adjusting for Ambient Noise: Since the surrounding noise varies, we must allow the program a second or too to adjust the energy threshold of recording so it is adjusted according to the external noise level.Speech to text translation: This is done with the help of Google Speech Recognition. This requires an active internet connection to work. However, there are certain offline Recognition systems such as PocketSphinx, but have a very rigorous installation process that requires several dependencies. Google Speech Recognition is one of the easiest to use.The Above steps have been implemented below:#Python 2.x program for Speech Recognition import speech_recognition as sr #enter the name of usb microphone that you found#using lsusb#the following name is only used as an examplemic_name = \"USB Device 0x46d:0x825: Audio (hw:1, 0)\"#Sample rate is how often values are recordedsample_rate = 48000#Chunk is like a buffer. It stores 2048 samples (bytes of data)#here. #it is advisable to use powers of 2 such as 1024 or 2048chunk_size = 2048#Initialize the recognizerr = sr.Recognizer() #generate a list of all audio cards/microphonesmic_list = sr.Microphone.list_microphone_names() #the following loop aims to set the device ID of the mic that#we specifically want to use to avoid ambiguity.for i, microphone_name in enumerate(mic_list): if microphone_name == mic_name: device_id = i #use the microphone as source for input. Here, we also specify #which device ID to specifically look for incase the microphone #is not working, an error will pop up saying \"device_id undefined\"with sr.Microphone(device_index = device_id, sample_rate = sample_rate, chunk_size = chunk_size) as source: #wait for a second to let the recognizer adjust the #energy threshold based on the surrounding noise level r.adjust_for_ambient_noise(source) print \"Say Something\" #listens for the user's input audio = r.listen(source) try: text = r.recognize_google(audio) print \"you said: \" + text #error occurs when google could not understand what was said except sr.UnknownValueError: print(\"Google Speech Recognition could not understand audio\") except sr.RequestError as e: print(\"Could not request results from Google Speech Recognition service; {0}\".format(e))Transcribe an Audio file to textIf we have an audio file that we want to translate to text, we simply have to replace the source with the audio file instead of a microphone.Place the audio file and the program in the same folder for convenience. This works for WAV, AIFF, of FLAC files.An implementation has been shown below#Python 2.x program to transcribe an Audio fileimport speech_recognition as sr AUDIO_FILE = (\"example.wav\") # use the audio file as the audio source r = sr.Recognizer() with sr.AudioFile(AUDIO_FILE) as source: #reads the audio file. Here we use record instead of #listen audio = r.record(source) try: print(\"The audio file contains: \" + r.recognize_google(audio)) except sr.UnknownValueError: print(\"Google Speech Recognition could not understand audio\") except sr.RequestError as e: print(\"Could not request results from Google Speech Recognition service; {0}\".format(e))"
},
{
"code": null,
"e": 32755,
"s": 32419,
"text": "Configure Microphone (For external microphones): It is advisable to specify the microphone during the program to avoid any glitches.Type lsusb in the terminal. A list of connected devices will show up. The microphone name would look like thisUSB Device 0x46d:0x825: Audio (hw:1, 0)Make a note of this as it will be used in the program."
},
{
"code": null,
"e": 32795,
"s": 32755,
"text": "USB Device 0x46d:0x825: Audio (hw:1, 0)"
},
{
"code": null,
"e": 32850,
"s": 32795,
"text": "Make a note of this as it will be used in the program."
},
{
"code": null,
"e": 33020,
"s": 32850,
"text": "Set Chunk Size: This basically involved specifying how many bytes of data we want to read at once. Typically, this value is specified in powers of 2 such as 1024 or 2048"
},
{
"code": null,
"e": 33106,
"s": 33020,
"text": "Set Sampling Rate: Sampling rate defines how often values are recorded for processing"
},
{
"code": null,
"e": 33575,
"s": 33106,
"text": "Set Device ID to the selected microphone: In this step, we specify the device ID of the microphone that we wish to use in order to avoid ambiguity in case there are multiple microphones. This also helps debug, in the sense that, while running the program, we will know whether the specified microphone is being recognized. During the program, we specify a parameter device_id. The program will say that device_id could not be found if the microphone is not recognized."
},
{
"code": null,
"e": 33789,
"s": 33575,
"text": "Allow Adjusting for Ambient Noise: Since the surrounding noise varies, we must allow the program a second or too to adjust the energy threshold of recording so it is adjusted according to the external noise level."
},
{
"code": null,
"e": 36919,
"s": 33789,
"text": "Speech to text translation: This is done with the help of Google Speech Recognition. This requires an active internet connection to work. However, there are certain offline Recognition systems such as PocketSphinx, but have a very rigorous installation process that requires several dependencies. Google Speech Recognition is one of the easiest to use.The Above steps have been implemented below:#Python 2.x program for Speech Recognition import speech_recognition as sr #enter the name of usb microphone that you found#using lsusb#the following name is only used as an examplemic_name = \"USB Device 0x46d:0x825: Audio (hw:1, 0)\"#Sample rate is how often values are recordedsample_rate = 48000#Chunk is like a buffer. It stores 2048 samples (bytes of data)#here. #it is advisable to use powers of 2 such as 1024 or 2048chunk_size = 2048#Initialize the recognizerr = sr.Recognizer() #generate a list of all audio cards/microphonesmic_list = sr.Microphone.list_microphone_names() #the following loop aims to set the device ID of the mic that#we specifically want to use to avoid ambiguity.for i, microphone_name in enumerate(mic_list): if microphone_name == mic_name: device_id = i #use the microphone as source for input. Here, we also specify #which device ID to specifically look for incase the microphone #is not working, an error will pop up saying \"device_id undefined\"with sr.Microphone(device_index = device_id, sample_rate = sample_rate, chunk_size = chunk_size) as source: #wait for a second to let the recognizer adjust the #energy threshold based on the surrounding noise level r.adjust_for_ambient_noise(source) print \"Say Something\" #listens for the user's input audio = r.listen(source) try: text = r.recognize_google(audio) print \"you said: \" + text #error occurs when google could not understand what was said except sr.UnknownValueError: print(\"Google Speech Recognition could not understand audio\") except sr.RequestError as e: print(\"Could not request results from Google Speech Recognition service; {0}\".format(e))Transcribe an Audio file to textIf we have an audio file that we want to translate to text, we simply have to replace the source with the audio file instead of a microphone.Place the audio file and the program in the same folder for convenience. This works for WAV, AIFF, of FLAC files.An implementation has been shown below#Python 2.x program to transcribe an Audio fileimport speech_recognition as sr AUDIO_FILE = (\"example.wav\") # use the audio file as the audio source r = sr.Recognizer() with sr.AudioFile(AUDIO_FILE) as source: #reads the audio file. Here we use record instead of #listen audio = r.record(source) try: print(\"The audio file contains: \" + r.recognize_google(audio)) except sr.UnknownValueError: print(\"Google Speech Recognition could not understand audio\") except sr.RequestError as e: print(\"Could not request results from Google Speech Recognition service; {0}\".format(e))"
},
{
"code": null,
"e": 36964,
"s": 36919,
"text": "The Above steps have been implemented below:"
},
{
"code": "#Python 2.x program for Speech Recognition import speech_recognition as sr #enter the name of usb microphone that you found#using lsusb#the following name is only used as an examplemic_name = \"USB Device 0x46d:0x825: Audio (hw:1, 0)\"#Sample rate is how often values are recordedsample_rate = 48000#Chunk is like a buffer. It stores 2048 samples (bytes of data)#here. #it is advisable to use powers of 2 such as 1024 or 2048chunk_size = 2048#Initialize the recognizerr = sr.Recognizer() #generate a list of all audio cards/microphonesmic_list = sr.Microphone.list_microphone_names() #the following loop aims to set the device ID of the mic that#we specifically want to use to avoid ambiguity.for i, microphone_name in enumerate(mic_list): if microphone_name == mic_name: device_id = i #use the microphone as source for input. Here, we also specify #which device ID to specifically look for incase the microphone #is not working, an error will pop up saying \"device_id undefined\"with sr.Microphone(device_index = device_id, sample_rate = sample_rate, chunk_size = chunk_size) as source: #wait for a second to let the recognizer adjust the #energy threshold based on the surrounding noise level r.adjust_for_ambient_noise(source) print \"Say Something\" #listens for the user's input audio = r.listen(source) try: text = r.recognize_google(audio) print \"you said: \" + text #error occurs when google could not understand what was said except sr.UnknownValueError: print(\"Google Speech Recognition could not understand audio\") except sr.RequestError as e: print(\"Could not request results from Google Speech Recognition service; {0}\".format(e))",
"e": 38761,
"s": 36964,
"text": null
},
{
"code": null,
"e": 38794,
"s": 38761,
"text": "Transcribe an Audio file to text"
},
{
"code": null,
"e": 39087,
"s": 38794,
"text": "If we have an audio file that we want to translate to text, we simply have to replace the source with the audio file instead of a microphone.Place the audio file and the program in the same folder for convenience. This works for WAV, AIFF, of FLAC files.An implementation has been shown below"
},
{
"code": "#Python 2.x program to transcribe an Audio fileimport speech_recognition as sr AUDIO_FILE = (\"example.wav\") # use the audio file as the audio source r = sr.Recognizer() with sr.AudioFile(AUDIO_FILE) as source: #reads the audio file. Here we use record instead of #listen audio = r.record(source) try: print(\"The audio file contains: \" + r.recognize_google(audio)) except sr.UnknownValueError: print(\"Google Speech Recognition could not understand audio\") except sr.RequestError as e: print(\"Could not request results from Google Speech Recognition service; {0}\".format(e))",
"e": 39701,
"s": 39087,
"text": null
},
{
"code": null,
"e": 39717,
"s": 39701,
"text": "Troubleshooting"
},
{
"code": null,
"e": 39765,
"s": 39717,
"text": "The following problems are commonly encountered"
},
{
"code": null,
"e": 41328,
"s": 39765,
"text": "Muted Microphone: This leads to input not being received. To check for this, you can use alsamixer.It can be installed usingsudo apt-get install libasound2 alsa-utils alsa-ossType amixer. The output will look somewhat like thisSimple mixer control 'Master', 0\n Capabilities: pvolume pswitch pswitch-joined\n Playback channels: Front Left - Front Right\n Limits: Playback 0 - 65536\n Mono:\n Front Left: Playback 41855 [64%] [on]\n Front Right: Playback 65536 [100%] [on]\nSimple mixer control 'Capture', 0\n Capabilities: cvolume cswitch cswitch-joined\n Capture channels: Front Left - Front Right\n Limits: Capture 0 - 65536\n Front Left: Capture 0 [0%] [off] #switched off\n Front Right: Capture 0 [0%] [off]\nAs you can see, the capture device is currently switched off. To switch it on, type alsamixerAs you can see in the first picture, it is displaying our playback devices. Press F4 to toggle to Capture devices.In the second picture, the highlighted portion shows that the capture device is muted. To unmute it, press space barAs you can see in the last picture, the highlighted part confirms that the capture device is not muted.Current microphone not selected as capture device:In this case, the microphone can be set by typing alsamixer and selecting sound cards. Here, you can select default microphone device.As shown in the picture, the highlighted portion is where you have to select sound card.The second picture shows the screen selection for sound cardNo Internet Connection: The speech to text conversion requires an active internet connection."
},
{
"code": null,
"e": 42466,
"s": 41328,
"text": "Muted Microphone: This leads to input not being received. To check for this, you can use alsamixer.It can be installed usingsudo apt-get install libasound2 alsa-utils alsa-ossType amixer. The output will look somewhat like thisSimple mixer control 'Master', 0\n Capabilities: pvolume pswitch pswitch-joined\n Playback channels: Front Left - Front Right\n Limits: Playback 0 - 65536\n Mono:\n Front Left: Playback 41855 [64%] [on]\n Front Right: Playback 65536 [100%] [on]\nSimple mixer control 'Capture', 0\n Capabilities: cvolume cswitch cswitch-joined\n Capture channels: Front Left - Front Right\n Limits: Capture 0 - 65536\n Front Left: Capture 0 [0%] [off] #switched off\n Front Right: Capture 0 [0%] [off]\nAs you can see, the capture device is currently switched off. To switch it on, type alsamixerAs you can see in the first picture, it is displaying our playback devices. Press F4 to toggle to Capture devices.In the second picture, the highlighted portion shows that the capture device is muted. To unmute it, press space barAs you can see in the last picture, the highlighted part confirms that the capture device is not muted."
},
{
"code": null,
"e": 42518,
"s": 42466,
"text": "sudo apt-get install libasound2 alsa-utils alsa-oss"
},
{
"code": null,
"e": 42571,
"s": 42518,
"text": "Type amixer. The output will look somewhat like this"
},
{
"code": null,
"e": 43056,
"s": 42571,
"text": "Simple mixer control 'Master', 0\n Capabilities: pvolume pswitch pswitch-joined\n Playback channels: Front Left - Front Right\n Limits: Playback 0 - 65536\n Mono:\n Front Left: Playback 41855 [64%] [on]\n Front Right: Playback 65536 [100%] [on]\nSimple mixer control 'Capture', 0\n Capabilities: cvolume cswitch cswitch-joined\n Capture channels: Front Left - Front Right\n Limits: Capture 0 - 65536\n Front Left: Capture 0 [0%] [off] #switched off\n Front Right: Capture 0 [0%] [off]\n"
},
{
"code": null,
"e": 43264,
"s": 43056,
"text": "As you can see, the capture device is currently switched off. To switch it on, type alsamixerAs you can see in the first picture, it is displaying our playback devices. Press F4 to toggle to Capture devices."
},
{
"code": null,
"e": 43381,
"s": 43264,
"text": "In the second picture, the highlighted portion shows that the capture device is muted. To unmute it, press space bar"
},
{
"code": null,
"e": 43485,
"s": 43381,
"text": "As you can see in the last picture, the highlighted part confirms that the capture device is not muted."
},
{
"code": null,
"e": 43818,
"s": 43485,
"text": "Current microphone not selected as capture device:In this case, the microphone can be set by typing alsamixer and selecting sound cards. Here, you can select default microphone device.As shown in the picture, the highlighted portion is where you have to select sound card.The second picture shows the screen selection for sound card"
},
{
"code": null,
"e": 43879,
"s": 43818,
"text": "The second picture shows the screen selection for sound card"
},
{
"code": null,
"e": 43973,
"s": 43879,
"text": "No Internet Connection: The speech to text conversion requires an active internet connection."
},
{
"code": null,
"e": 44277,
"s": 43973,
"text": "This article is contributed by Deepak Srivatsav. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 44402,
"s": 44277,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 44417,
"s": 44402,
"text": "python-utility"
},
{
"code": null,
"e": 44423,
"s": 44417,
"text": "GBlog"
},
{
"code": null,
"e": 44430,
"s": 44423,
"text": "Python"
},
{
"code": null,
"e": 44528,
"s": 44430,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 44553,
"s": 44528,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 44588,
"s": 44553,
"text": "GET and POST requests using Python"
},
{
"code": null,
"e": 44650,
"s": 44588,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 44676,
"s": 44650,
"text": "Types of Software Testing"
},
{
"code": null,
"e": 44709,
"s": 44676,
"text": "Working with csv files in Python"
},
{
"code": null,
"e": 44737,
"s": 44709,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 44787,
"s": 44737,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 44809,
"s": 44787,
"text": "Python map() function"
}
] |
Find the maximum number of elements divisible by 3 - GeeksforGeeks
|
14 May, 2021
Given an array of size N. The task to find the maximum possible number of elements divisible by 3 that are in the array after performing the operation an arbitrary (possibly, zero) number of times. In each operation, one can add any two elements of the array. Examples:
Input : a[] = {1, 2, 3} Output : 2 After applying the operation once (on elements 1, 2), the array becomes {3, 3}. It contains 2 numbers which are divisible by 3 which are maximum possible.Input : a[] = {1, 1, 1, 1, 1, 2, 2} Output : 3
Approach : Let cnti be the number of elements of a with the remainder i modulo 3. Then the initial answer can be represented as cnt0 and we have to compose numbers with remainders 1 and 2 somehow optimally. It can be shown that the best way to do it is the following:
Firstly, while there is at least one remainder of 1 and at least one remainder of 2 then compose them into one 0. After this, at least one of the numbers cnt1, cnt2 will be zero, then we have to compose remaining numbers into numbers divisible by 3.
If cnt1=0 then the maximum remaining number of elements we can obtain is [cnt2/3] (because 2+2+2=6), and in the other case (cnt2=0) the maximum number of elements is [cnt1/3] (because 1+1+1=3).
Below is the implementation of the above approach :
C++
Java
Python3
C#
Javascript
// C++ program to find the maximum// number of elements divisible by 3#include <bits/stdc++.h>using namespace std; // Function to find the maximum// number of elements divisible by 3int MaxNumbers(int a[], int n){ // To store frequency of each number int fre[3] = { 0 }; for (int i = 0; i < n; i++) { // Store modulo value a[i] %= 3; // Store frequency fre[a[i]]++; } // Add numbers with zero modulo to answer int ans = fre[0]; // Find minimum of elements with modulo // frequency one and zero int k = min(fre[1], fre[2]); // Add k to the answer ans += k; // Remove them from frequency fre[1] -= k; fre[2] -= k; // Add numbers possible with // remaining frequency ans += fre[1] / 3 + fre[2] / 3; // Return the required answer return ans;} // Driver codeint main(){ int a[] = { 1, 4, 10, 7, 11, 2, 8, 5, 9 }; int n = sizeof(a) / sizeof(a[0]); // Function call cout << MaxNumbers(a, n); return 0;}
// Java program to find the maximum// number of elements divisible by 3import java.io.*; class GFG{ // Function to find the maximum // number of elements divisible by 3 static int MaxNumbers(int a[], int n) { // To store frequency of each number int []fre = { 0,0,0 }; for (int i = 0; i < n; i++) { // Store modulo value a[i] %= 3; // Store frequency fre[a[i]]++; } // Add numbers with zero modulo to answer int ans = fre[0]; // Find minimum of elements with modulo // frequency one and zero int k = Math.min(fre[1], fre[2]); // Add k to the answer ans += k; // Remove them from frequency fre[1] -= k; fre[2] -= k; // Add numbers possible with // remaining frequency ans += fre[1] / 3 + fre[2] / 3; // Return the required answer return ans; } // Driver code public static void main (String[] args) { int a[] = { 1, 4, 10, 7, 11, 2, 8, 5, 9 }; int n = a.length; // Function call System.out.println(MaxNumbers(a, n)); }} // This code is contributed by @@ajit..
# Python3 program to find the maximum# number of elements divisible by 3 # Function to find the maximum# number of elements divisible by 3def MaxNumbers(a, n): # To store frequency of each number fre = [0 for i in range(3)] for i in range(n): # Store modulo value a[i] %= 3 # Store frequency fre[a[i]] += 1 # Add numbers with zero modulo to answer ans = fre[0] # Find minimum of elements with modulo # frequency one and zero k = min(fre[1], fre[2]) # Add k to the answer ans += k # Remove them from frequency fre[1] -= k fre[2] -= k # Add numbers possible with # remaining frequency ans += fre[1] // 3 + fre[2] // 3 # Return the required answer return ans # Driver codea = [1, 4, 10, 7, 11, 2, 8, 5, 9] n = len(a) # Function callprint(MaxNumbers(a, n)) # This code is contributed by Mohit Kumar
// C# program to find the maximum// number of elements divisible by 3using System; class GFG{ // Function to find the maximum // number of elements divisible by 3 static int MaxNumbers(int []a, int n) { // To store frequency of each number int []fre = { 0,0,0 }; for (int i = 0; i < n; i++) { // Store modulo value a[i] %= 3; // Store frequency fre[a[i]]++; } // Add numbers with zero modulo to answer int ans = fre[0]; // Find minimum of elements with modulo // frequency one and zero int k = Math.Min(fre[1], fre[2]); // Add k to the answer ans += k; // Remove them from frequency fre[1] -= k; fre[2] -= k; // Add numbers possible with // remaining frequency ans += fre[1] / 3 + fre[2] / 3; // Return the required answer return ans; } // Driver code static public void Main () { int []a = { 1, 4, 10, 7, 11, 2, 8, 5, 9 }; int n = a.Length; // Function call Console.WriteLine(MaxNumbers(a, n)); }} // This code is contributed by AnkitRai01
<script> // Javascript program to find the maximum// number of elements divisible by 3 // Function to find the maximum// number of elements divisible by 3function MaxNumbers(a, n){ // To store frequency of each number let fre = new Array(3).fill(0); for (let i = 0; i < n; i++) { // Store modulo value a[i] %= 3; // Store frequency fre[a[i]]++; } // Add numbers with zero modulo to answer let ans = fre[0]; // Find minimum of elements with modulo // frequency one and zero let k = Math.min(fre[1], fre[2]); // Add k to the answer ans += k; // Remove them from frequency fre[1] -= k; fre[2] -= k; // Add numbers possible with // remaining frequency ans += parseInt(fre[1] / 3) + parseInt(fre[2] / 3); // Return the required answer return ans;} // Driver code let a = [ 1, 4, 10, 7, 11, 2, 8, 5, 9 ]; let n = a.length; // Function call document.write(MaxNumbers(a, n)); </script>
5
Time Complexity : O(N)
mohit kumar 29
ankthon
jit_t
rishavmahato348
surinderdawra388
frequency-counting
Arrays
Mathematical
Arrays
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Stack Data Structure (Introduction and Program)
Introduction to Arrays
Multidimensional Arrays in Java
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7
|
[
{
"code": null,
"e": 26527,
"s": 26499,
"text": "\n14 May, 2021"
},
{
"code": null,
"e": 26798,
"s": 26527,
"text": "Given an array of size N. The task to find the maximum possible number of elements divisible by 3 that are in the array after performing the operation an arbitrary (possibly, zero) number of times. In each operation, one can add any two elements of the array. Examples: "
},
{
"code": null,
"e": 27036,
"s": 26798,
"text": "Input : a[] = {1, 2, 3} Output : 2 After applying the operation once (on elements 1, 2), the array becomes {3, 3}. It contains 2 numbers which are divisible by 3 which are maximum possible.Input : a[] = {1, 1, 1, 1, 1, 2, 2} Output : 3 "
},
{
"code": null,
"e": 27306,
"s": 27036,
"text": "Approach : Let cnti be the number of elements of a with the remainder i modulo 3. Then the initial answer can be represented as cnt0 and we have to compose numbers with remainders 1 and 2 somehow optimally. It can be shown that the best way to do it is the following: "
},
{
"code": null,
"e": 27556,
"s": 27306,
"text": "Firstly, while there is at least one remainder of 1 and at least one remainder of 2 then compose them into one 0. After this, at least one of the numbers cnt1, cnt2 will be zero, then we have to compose remaining numbers into numbers divisible by 3."
},
{
"code": null,
"e": 27750,
"s": 27556,
"text": "If cnt1=0 then the maximum remaining number of elements we can obtain is [cnt2/3] (because 2+2+2=6), and in the other case (cnt2=0) the maximum number of elements is [cnt1/3] (because 1+1+1=3)."
},
{
"code": null,
"e": 27804,
"s": 27750,
"text": "Below is the implementation of the above approach : "
},
{
"code": null,
"e": 27808,
"s": 27804,
"text": "C++"
},
{
"code": null,
"e": 27813,
"s": 27808,
"text": "Java"
},
{
"code": null,
"e": 27821,
"s": 27813,
"text": "Python3"
},
{
"code": null,
"e": 27824,
"s": 27821,
"text": "C#"
},
{
"code": null,
"e": 27835,
"s": 27824,
"text": "Javascript"
},
{
"code": "// C++ program to find the maximum// number of elements divisible by 3#include <bits/stdc++.h>using namespace std; // Function to find the maximum// number of elements divisible by 3int MaxNumbers(int a[], int n){ // To store frequency of each number int fre[3] = { 0 }; for (int i = 0; i < n; i++) { // Store modulo value a[i] %= 3; // Store frequency fre[a[i]]++; } // Add numbers with zero modulo to answer int ans = fre[0]; // Find minimum of elements with modulo // frequency one and zero int k = min(fre[1], fre[2]); // Add k to the answer ans += k; // Remove them from frequency fre[1] -= k; fre[2] -= k; // Add numbers possible with // remaining frequency ans += fre[1] / 3 + fre[2] / 3; // Return the required answer return ans;} // Driver codeint main(){ int a[] = { 1, 4, 10, 7, 11, 2, 8, 5, 9 }; int n = sizeof(a) / sizeof(a[0]); // Function call cout << MaxNumbers(a, n); return 0;}",
"e": 28843,
"s": 27835,
"text": null
},
{
"code": "// Java program to find the maximum// number of elements divisible by 3import java.io.*; class GFG{ // Function to find the maximum // number of elements divisible by 3 static int MaxNumbers(int a[], int n) { // To store frequency of each number int []fre = { 0,0,0 }; for (int i = 0; i < n; i++) { // Store modulo value a[i] %= 3; // Store frequency fre[a[i]]++; } // Add numbers with zero modulo to answer int ans = fre[0]; // Find minimum of elements with modulo // frequency one and zero int k = Math.min(fre[1], fre[2]); // Add k to the answer ans += k; // Remove them from frequency fre[1] -= k; fre[2] -= k; // Add numbers possible with // remaining frequency ans += fre[1] / 3 + fre[2] / 3; // Return the required answer return ans; } // Driver code public static void main (String[] args) { int a[] = { 1, 4, 10, 7, 11, 2, 8, 5, 9 }; int n = a.length; // Function call System.out.println(MaxNumbers(a, n)); }} // This code is contributed by @@ajit..",
"e": 30101,
"s": 28843,
"text": null
},
{
"code": "# Python3 program to find the maximum# number of elements divisible by 3 # Function to find the maximum# number of elements divisible by 3def MaxNumbers(a, n): # To store frequency of each number fre = [0 for i in range(3)] for i in range(n): # Store modulo value a[i] %= 3 # Store frequency fre[a[i]] += 1 # Add numbers with zero modulo to answer ans = fre[0] # Find minimum of elements with modulo # frequency one and zero k = min(fre[1], fre[2]) # Add k to the answer ans += k # Remove them from frequency fre[1] -= k fre[2] -= k # Add numbers possible with # remaining frequency ans += fre[1] // 3 + fre[2] // 3 # Return the required answer return ans # Driver codea = [1, 4, 10, 7, 11, 2, 8, 5, 9] n = len(a) # Function callprint(MaxNumbers(a, n)) # This code is contributed by Mohit Kumar",
"e": 31000,
"s": 30101,
"text": null
},
{
"code": "// C# program to find the maximum// number of elements divisible by 3using System; class GFG{ // Function to find the maximum // number of elements divisible by 3 static int MaxNumbers(int []a, int n) { // To store frequency of each number int []fre = { 0,0,0 }; for (int i = 0; i < n; i++) { // Store modulo value a[i] %= 3; // Store frequency fre[a[i]]++; } // Add numbers with zero modulo to answer int ans = fre[0]; // Find minimum of elements with modulo // frequency one and zero int k = Math.Min(fre[1], fre[2]); // Add k to the answer ans += k; // Remove them from frequency fre[1] -= k; fre[2] -= k; // Add numbers possible with // remaining frequency ans += fre[1] / 3 + fre[2] / 3; // Return the required answer return ans; } // Driver code static public void Main () { int []a = { 1, 4, 10, 7, 11, 2, 8, 5, 9 }; int n = a.Length; // Function call Console.WriteLine(MaxNumbers(a, n)); }} // This code is contributed by AnkitRai01",
"e": 32249,
"s": 31000,
"text": null
},
{
"code": "<script> // Javascript program to find the maximum// number of elements divisible by 3 // Function to find the maximum// number of elements divisible by 3function MaxNumbers(a, n){ // To store frequency of each number let fre = new Array(3).fill(0); for (let i = 0; i < n; i++) { // Store modulo value a[i] %= 3; // Store frequency fre[a[i]]++; } // Add numbers with zero modulo to answer let ans = fre[0]; // Find minimum of elements with modulo // frequency one and zero let k = Math.min(fre[1], fre[2]); // Add k to the answer ans += k; // Remove them from frequency fre[1] -= k; fre[2] -= k; // Add numbers possible with // remaining frequency ans += parseInt(fre[1] / 3) + parseInt(fre[2] / 3); // Return the required answer return ans;} // Driver code let a = [ 1, 4, 10, 7, 11, 2, 8, 5, 9 ]; let n = a.length; // Function call document.write(MaxNumbers(a, n)); </script>",
"e": 33235,
"s": 32249,
"text": null
},
{
"code": null,
"e": 33237,
"s": 33235,
"text": "5"
},
{
"code": null,
"e": 33263,
"s": 33239,
"text": "Time Complexity : O(N) "
},
{
"code": null,
"e": 33278,
"s": 33263,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 33286,
"s": 33278,
"text": "ankthon"
},
{
"code": null,
"e": 33292,
"s": 33286,
"text": "jit_t"
},
{
"code": null,
"e": 33308,
"s": 33292,
"text": "rishavmahato348"
},
{
"code": null,
"e": 33325,
"s": 33308,
"text": "surinderdawra388"
},
{
"code": null,
"e": 33344,
"s": 33325,
"text": "frequency-counting"
},
{
"code": null,
"e": 33351,
"s": 33344,
"text": "Arrays"
},
{
"code": null,
"e": 33364,
"s": 33351,
"text": "Mathematical"
},
{
"code": null,
"e": 33371,
"s": 33364,
"text": "Arrays"
},
{
"code": null,
"e": 33384,
"s": 33371,
"text": "Mathematical"
},
{
"code": null,
"e": 33482,
"s": 33384,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33550,
"s": 33482,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 33594,
"s": 33550,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 33642,
"s": 33594,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 33665,
"s": 33642,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 33697,
"s": 33665,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 33727,
"s": 33697,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 33787,
"s": 33727,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 33802,
"s": 33787,
"text": "C++ Data Types"
},
{
"code": null,
"e": 33845,
"s": 33802,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
Minimum count of elements that sums to a given number - GeeksforGeeks
|
10 Mar, 2022
Given infinite number of elements of form and ( n >= 0 ). The task is to find the minimum count of elements chosen such that there sum is equal to K. Examples:
Input : K = 48 Output : 6 elements chosen are: (1 + 1 + 1 + 10 + 10 + 25)Input : 69 Output : 9 elements chosen are: (1 + 1 + 1 + 1 + 10 + 10 + 10 + 10 + 25)
Approach: There are infinite number of the following elements : 1, 10, 25, 100, 1000, 2500, 10000, 100000, 250000 ... and so on.Greedy Approach won’t work here. For K = 66, by Greedy Approach minimum count will be 9 and chosen elements are 25 + 25 + 10 + 1 + 1 + 1 + 1 + 1 + 1 = 66. But its optimum answer is 6 when these elements are chosen: 25 + 10 + 10 + 10 + 10 + 1 = 66. So, Dynamic Programming will work here. But simple DP cannot be applied because K can go upto 10^9 . Dynamic Programming approach:
Precompute the minimum no. of elements chosen that constitutes sum upto 99 and store it in memo array.
Also, sums upto 99 can only be formed by the combinations of 1, 10 and 25.
Starting from end of K, iterate over each last 2 digits to find minimum no. of elements chosen that will sum to last two digits.
Sum them all to find the minimum count.
Illustration of the above approach: Let’s take K = 250166Let min_count = 0, last 2 digits = 66 add minimum number of elements to min_count that sums to 66 (it is calculated from memo array that we have precomputed). min_count = min_count + 6, Now, min_count = 6, last 2 digits = 01add minimum number of elements to min_count sums to 1. min_count = min_count + 1, Now, min_count = 7, last 2 digits = 25add minimum number of elements to min_count sums to 25. min_count = min_count + 1, Now, min_count = 8.So, minimum number of elements chosen that sums to 250166 is 8. Optimal chosen Elements are (250000, 100, 25, 10, 10, 10, 10, 1)
Below is the implementation of the above approach.
C++
Java
Python3
C#
Javascript
// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; int minCount(int K){ // we will only store min counts // of sum upto 100 int memo[100]; // initialize with INT_MAX for (int i = 0; i < 100; i++) { memo[i] = INT_MAX; } // memo[0] = 0 as 0 is // made from 0 elements memo[0] = 0; // fill memo array with min counts // of elements that will constitute // sum upto 100 for (int i = 1; i < 100; i++) { memo[i] = min(memo[i - 1] + 1, memo[i]); } for (int i = 10; i < 100; i++) { memo[i] = min(memo[i - 10] + 1, memo[i]); } for (int i = 25; i < 100; i++) { memo[i] = min(memo[i - 25] + 1, memo[i]); } // min_count will store min // count of elements chosen long min_count = 0; // starting from end iterate over // each 2 digits and add min count // of elements to min_count while (K > 0) { min_count += memo[K % 100]; K /= 100; } return min_count;} // Driver codeint main(){ int K = 69; cout << minCount(K) << endl; return 0;}
// Java implementation of the above approach class GFG{ static int minCount(int K) { // we will only store min counts // of sum upto 100 int memo[] = new int[100]; // initialize with INT_MAX for (int i = 0; i < 100; i++) { memo[i] = Integer.MAX_VALUE; } // memo[0] = 0 as 0 is // made from 0 elements memo[0] = 0; // fill memo array with min counts // of elements that will constitute // sum upto 100 for (int i = 1; i < 100; i++) { memo[i] = Math.min(memo[i - 1] + 1, memo[i]); } for (int i = 10; i < 100; i++) { memo[i] = Math.min(memo[i - 10] + 1, memo[i]); } for (int i = 25; i < 100; i++) { memo[i] = Math.min(memo[i - 25] + 1, memo[i]); } // min_count will store min // count of elements chosen int min_count = 0; // starting from end iterate over // each 2 digits and add min count // of elements to min_count while (K > 0) { min_count += memo[K % 100]; K /= 100; } return min_count; } // Driver code public static void main (String[] args) { int K = 69; System.out.println(minCount(K)); }} // This code is contributed by AnkitRai01
# Python3 implementation of the above approach def minCount(K): # we will only store min counts # of sum upto 100 memo=[10**9 for i in range(100)] # memo[0] = 0 as 0 is # made from 0 elements memo[0] = 0 # fill memo array with min counts # of elements that will constitute # sum upto 100 for i in range(1,100): memo[i] = min(memo[i - 1] + 1, memo[i]) for i in range(10,100): memo[i] = min(memo[i - 10] + 1, memo[i]) for i in range(25,100): memo[i] = min(memo[i - 25] + 1, memo[i]) # min_count will store min # count of elements chosen min_count = 0 # starting from end iterate over # each 2 digits and add min count # of elements to min_count while (K > 0): min_count += memo[K % 100] K //= 100 return min_count # Driver code K = 69 print(minCount(K)) # This code is contributed by mohit kumar 29
// C# implementation of the above approachusing System; class GFG{ static int minCount(int K) { // we will only store min counts // of sum upto 100 int []memo = new int[100]; // initialize with INT_MAX for (int i = 0; i < 100; i++) { memo[i] = int.MaxValue; } // memo[0] = 0 as 0 is // made from 0 elements memo[0] = 0; // fill memo array with min counts // of elements that will constitute // sum upto 100 for (int i = 1; i < 100; i++) { memo[i] = Math.Min(memo[i - 1] + 1, memo[i]); } for (int i = 10; i < 100; i++) { memo[i] = Math.Min(memo[i - 10] + 1, memo[i]); } for (int i = 25; i < 100; i++) { memo[i] = Math.Min(memo[i - 25] + 1, memo[i]); } // min_count will store min // count of elements chosen int min_count = 0; // starting from end iterate over // each 2 digits and add min count // of elements to min_count while (K > 0) { min_count += memo[K % 100]; K /= 100; } return min_count; } // Driver code static public void Main () { int K = 69; Console.WriteLine(minCount(K)); }} // This code is contributed by ajit
<script> // Javascript implementation of the above approach function minCount(K) { // we will only store min counts // of sum upto 100 let memo = new Array(100); // initialize with INT_MAX for (let i = 0; i < 100; i++) { memo[i] = Number.MAX_VALUE; } // memo[0] = 0 as 0 is // made from 0 elements memo[0] = 0; // fill memo array with min counts // of elements that will constitute // sum upto 100 for (let i = 1; i < 100; i++) { memo[i] = Math.min(memo[i - 1] + 1, memo[i]); } for (let i = 10; i < 100; i++) { memo[i] = Math.min(memo[i - 10] + 1, memo[i]); } for (let i = 25; i < 100; i++) { memo[i] = Math.min(memo[i - 25] + 1, memo[i]); } // min_count will store min // count of elements chosen let min_count = 0; // starting from end iterate over // each 2 digits and add min count // of elements to min_count while (K > 0) { min_count += memo[K % 100]; K = parseInt(K / 100, 10); } return min_count; } let K = 69; document.write(minCount(K)); </script>
9
Time Complexity: O(1)
Auxiliary Space: O(1)
mohit kumar 29
ankthon
jit_t
divyeshrabadiya07
abhishek0719kadiyan
subham348
Arrays
Dynamic Programming
Arrays
Dynamic Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Arrays
Multidimensional Arrays in Java
Linear Search
Linked List vs Array
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
0-1 Knapsack Problem | DP-10
Longest Common Subsequence | DP-4
Bellman–Ford Algorithm | DP-23
Floyd Warshall Algorithm | DP-16
Longest Increasing Subsequence | DP-3
|
[
{
"code": null,
"e": 26145,
"s": 26117,
"text": "\n10 Mar, 2022"
},
{
"code": null,
"e": 26306,
"s": 26145,
"text": "Given infinite number of elements of form and ( n >= 0 ). The task is to find the minimum count of elements chosen such that there sum is equal to K. Examples: "
},
{
"code": null,
"e": 26465,
"s": 26306,
"text": "Input : K = 48 Output : 6 elements chosen are: (1 + 1 + 1 + 10 + 10 + 25)Input : 69 Output : 9 elements chosen are: (1 + 1 + 1 + 1 + 10 + 10 + 10 + 10 + 25) "
},
{
"code": null,
"e": 26976,
"s": 26467,
"text": "Approach: There are infinite number of the following elements : 1, 10, 25, 100, 1000, 2500, 10000, 100000, 250000 ... and so on.Greedy Approach won’t work here. For K = 66, by Greedy Approach minimum count will be 9 and chosen elements are 25 + 25 + 10 + 1 + 1 + 1 + 1 + 1 + 1 = 66. But its optimum answer is 6 when these elements are chosen: 25 + 10 + 10 + 10 + 10 + 1 = 66. So, Dynamic Programming will work here. But simple DP cannot be applied because K can go upto 10^9 . Dynamic Programming approach: "
},
{
"code": null,
"e": 27079,
"s": 26976,
"text": "Precompute the minimum no. of elements chosen that constitutes sum upto 99 and store it in memo array."
},
{
"code": null,
"e": 27154,
"s": 27079,
"text": "Also, sums upto 99 can only be formed by the combinations of 1, 10 and 25."
},
{
"code": null,
"e": 27283,
"s": 27154,
"text": "Starting from end of K, iterate over each last 2 digits to find minimum no. of elements chosen that will sum to last two digits."
},
{
"code": null,
"e": 27323,
"s": 27283,
"text": "Sum them all to find the minimum count."
},
{
"code": null,
"e": 27959,
"s": 27325,
"text": "Illustration of the above approach: Let’s take K = 250166Let min_count = 0, last 2 digits = 66 add minimum number of elements to min_count that sums to 66 (it is calculated from memo array that we have precomputed). min_count = min_count + 6, Now, min_count = 6, last 2 digits = 01add minimum number of elements to min_count sums to 1. min_count = min_count + 1, Now, min_count = 7, last 2 digits = 25add minimum number of elements to min_count sums to 25. min_count = min_count + 1, Now, min_count = 8.So, minimum number of elements chosen that sums to 250166 is 8. Optimal chosen Elements are (250000, 100, 25, 10, 10, 10, 10, 1) "
},
{
"code": null,
"e": 28012,
"s": 27959,
"text": "Below is the implementation of the above approach. "
},
{
"code": null,
"e": 28016,
"s": 28012,
"text": "C++"
},
{
"code": null,
"e": 28021,
"s": 28016,
"text": "Java"
},
{
"code": null,
"e": 28029,
"s": 28021,
"text": "Python3"
},
{
"code": null,
"e": 28032,
"s": 28029,
"text": "C#"
},
{
"code": null,
"e": 28043,
"s": 28032,
"text": "Javascript"
},
{
"code": "// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; int minCount(int K){ // we will only store min counts // of sum upto 100 int memo[100]; // initialize with INT_MAX for (int i = 0; i < 100; i++) { memo[i] = INT_MAX; } // memo[0] = 0 as 0 is // made from 0 elements memo[0] = 0; // fill memo array with min counts // of elements that will constitute // sum upto 100 for (int i = 1; i < 100; i++) { memo[i] = min(memo[i - 1] + 1, memo[i]); } for (int i = 10; i < 100; i++) { memo[i] = min(memo[i - 10] + 1, memo[i]); } for (int i = 25; i < 100; i++) { memo[i] = min(memo[i - 25] + 1, memo[i]); } // min_count will store min // count of elements chosen long min_count = 0; // starting from end iterate over // each 2 digits and add min count // of elements to min_count while (K > 0) { min_count += memo[K % 100]; K /= 100; } return min_count;} // Driver codeint main(){ int K = 69; cout << minCount(K) << endl; return 0;}",
"e": 29145,
"s": 28043,
"text": null
},
{
"code": "// Java implementation of the above approach class GFG{ static int minCount(int K) { // we will only store min counts // of sum upto 100 int memo[] = new int[100]; // initialize with INT_MAX for (int i = 0; i < 100; i++) { memo[i] = Integer.MAX_VALUE; } // memo[0] = 0 as 0 is // made from 0 elements memo[0] = 0; // fill memo array with min counts // of elements that will constitute // sum upto 100 for (int i = 1; i < 100; i++) { memo[i] = Math.min(memo[i - 1] + 1, memo[i]); } for (int i = 10; i < 100; i++) { memo[i] = Math.min(memo[i - 10] + 1, memo[i]); } for (int i = 25; i < 100; i++) { memo[i] = Math.min(memo[i - 25] + 1, memo[i]); } // min_count will store min // count of elements chosen int min_count = 0; // starting from end iterate over // each 2 digits and add min count // of elements to min_count while (K > 0) { min_count += memo[K % 100]; K /= 100; } return min_count; } // Driver code public static void main (String[] args) { int K = 69; System.out.println(minCount(K)); }} // This code is contributed by AnkitRai01",
"e": 30595,
"s": 29145,
"text": null
},
{
"code": "# Python3 implementation of the above approach def minCount(K): # we will only store min counts # of sum upto 100 memo=[10**9 for i in range(100)] # memo[0] = 0 as 0 is # made from 0 elements memo[0] = 0 # fill memo array with min counts # of elements that will constitute # sum upto 100 for i in range(1,100): memo[i] = min(memo[i - 1] + 1, memo[i]) for i in range(10,100): memo[i] = min(memo[i - 10] + 1, memo[i]) for i in range(25,100): memo[i] = min(memo[i - 25] + 1, memo[i]) # min_count will store min # count of elements chosen min_count = 0 # starting from end iterate over # each 2 digits and add min count # of elements to min_count while (K > 0): min_count += memo[K % 100] K //= 100 return min_count # Driver code K = 69 print(minCount(K)) # This code is contributed by mohit kumar 29",
"e": 31500,
"s": 30595,
"text": null
},
{
"code": "// C# implementation of the above approachusing System; class GFG{ static int minCount(int K) { // we will only store min counts // of sum upto 100 int []memo = new int[100]; // initialize with INT_MAX for (int i = 0; i < 100; i++) { memo[i] = int.MaxValue; } // memo[0] = 0 as 0 is // made from 0 elements memo[0] = 0; // fill memo array with min counts // of elements that will constitute // sum upto 100 for (int i = 1; i < 100; i++) { memo[i] = Math.Min(memo[i - 1] + 1, memo[i]); } for (int i = 10; i < 100; i++) { memo[i] = Math.Min(memo[i - 10] + 1, memo[i]); } for (int i = 25; i < 100; i++) { memo[i] = Math.Min(memo[i - 25] + 1, memo[i]); } // min_count will store min // count of elements chosen int min_count = 0; // starting from end iterate over // each 2 digits and add min count // of elements to min_count while (K > 0) { min_count += memo[K % 100]; K /= 100; } return min_count; } // Driver code static public void Main () { int K = 69; Console.WriteLine(minCount(K)); }} // This code is contributed by ajit",
"e": 32919,
"s": 31500,
"text": null
},
{
"code": "<script> // Javascript implementation of the above approach function minCount(K) { // we will only store min counts // of sum upto 100 let memo = new Array(100); // initialize with INT_MAX for (let i = 0; i < 100; i++) { memo[i] = Number.MAX_VALUE; } // memo[0] = 0 as 0 is // made from 0 elements memo[0] = 0; // fill memo array with min counts // of elements that will constitute // sum upto 100 for (let i = 1; i < 100; i++) { memo[i] = Math.min(memo[i - 1] + 1, memo[i]); } for (let i = 10; i < 100; i++) { memo[i] = Math.min(memo[i - 10] + 1, memo[i]); } for (let i = 25; i < 100; i++) { memo[i] = Math.min(memo[i - 25] + 1, memo[i]); } // min_count will store min // count of elements chosen let min_count = 0; // starting from end iterate over // each 2 digits and add min count // of elements to min_count while (K > 0) { min_count += memo[K % 100]; K = parseInt(K / 100, 10); } return min_count; } let K = 69; document.write(minCount(K)); </script>",
"e": 34260,
"s": 32919,
"text": null
},
{
"code": null,
"e": 34262,
"s": 34260,
"text": "9"
},
{
"code": null,
"e": 34286,
"s": 34264,
"text": "Time Complexity: O(1)"
},
{
"code": null,
"e": 34308,
"s": 34286,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 34323,
"s": 34308,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 34331,
"s": 34323,
"text": "ankthon"
},
{
"code": null,
"e": 34337,
"s": 34331,
"text": "jit_t"
},
{
"code": null,
"e": 34355,
"s": 34337,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 34375,
"s": 34355,
"text": "abhishek0719kadiyan"
},
{
"code": null,
"e": 34385,
"s": 34375,
"text": "subham348"
},
{
"code": null,
"e": 34392,
"s": 34385,
"text": "Arrays"
},
{
"code": null,
"e": 34412,
"s": 34392,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 34419,
"s": 34412,
"text": "Arrays"
},
{
"code": null,
"e": 34439,
"s": 34419,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 34537,
"s": 34439,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34560,
"s": 34537,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 34592,
"s": 34560,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 34606,
"s": 34592,
"text": "Linear Search"
},
{
"code": null,
"e": 34627,
"s": 34606,
"text": "Linked List vs Array"
},
{
"code": null,
"e": 34712,
"s": 34627,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 34741,
"s": 34712,
"text": "0-1 Knapsack Problem | DP-10"
},
{
"code": null,
"e": 34775,
"s": 34741,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 34806,
"s": 34775,
"text": "Bellman–Ford Algorithm | DP-23"
},
{
"code": null,
"e": 34839,
"s": 34806,
"text": "Floyd Warshall Algorithm | DP-16"
}
] |
PLSQL | CHR Function - GeeksforGeeks
|
19 Sep, 2019
The string in PL/SQL is actually a sequence of characters with an optional size specification.The characters could be numeric, letters, blank, special characters or a combination of all.The CHR Function in PLSQL is the opposite of the ASCII function and is used to return the character based on the NUMBER code.
Syntax:
CHR( number_code )
Parameters Used:
number_code – It is used to retrieve the character for the specified number code.
Supported Versions of Oracle/PLSQL:
Oracle 12cOracle 11gOracle 10gOracle 9iOracle 8i
Oracle 12c
Oracle 11g
Oracle 10g
Oracle 9i
Oracle 8i
Example:
DECLARE
Test_Char varchar2(4) := '69';
Test_Char1 varchar2(4) := '72';
BEGIN
dbms_output.put_line(CHR(Test_Char));
dbms_output.put_line(CHR(Test_Char1));
END;
Output:
E
H
SQL-PL/SQL
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL Interview Questions
CTE in SQL
SQL Trigger | Student Database
How to Update Multiple Columns in Single Update Statement in SQL?
SQL | Views
Difference between DDL and DML in DBMS
Difference between DELETE, DROP and TRUNCATE
MySQL | Group_CONCAT() Function
Difference between DELETE and TRUNCATE
SQL | Subquery
|
[
{
"code": null,
"e": 25175,
"s": 25147,
"text": "\n19 Sep, 2019"
},
{
"code": null,
"e": 25487,
"s": 25175,
"text": "The string in PL/SQL is actually a sequence of characters with an optional size specification.The characters could be numeric, letters, blank, special characters or a combination of all.The CHR Function in PLSQL is the opposite of the ASCII function and is used to return the character based on the NUMBER code."
},
{
"code": null,
"e": 25495,
"s": 25487,
"text": "Syntax:"
},
{
"code": null,
"e": 25514,
"s": 25495,
"text": "CHR( number_code )"
},
{
"code": null,
"e": 25531,
"s": 25514,
"text": "Parameters Used:"
},
{
"code": null,
"e": 25613,
"s": 25531,
"text": "number_code – It is used to retrieve the character for the specified number code."
},
{
"code": null,
"e": 25649,
"s": 25613,
"text": "Supported Versions of Oracle/PLSQL:"
},
{
"code": null,
"e": 25698,
"s": 25649,
"text": "Oracle 12cOracle 11gOracle 10gOracle 9iOracle 8i"
},
{
"code": null,
"e": 25709,
"s": 25698,
"text": "Oracle 12c"
},
{
"code": null,
"e": 25720,
"s": 25709,
"text": "Oracle 11g"
},
{
"code": null,
"e": 25731,
"s": 25720,
"text": "Oracle 10g"
},
{
"code": null,
"e": 25741,
"s": 25731,
"text": "Oracle 9i"
},
{
"code": null,
"e": 25751,
"s": 25741,
"text": "Oracle 8i"
},
{
"code": null,
"e": 25760,
"s": 25751,
"text": "Example:"
},
{
"code": null,
"e": 25948,
"s": 25760,
"text": "DECLARE \n Test_Char varchar2(4) := '69';\n Test_Char1 varchar2(4) := '72';\n \n BEGIN \n dbms_output.put_line(CHR(Test_Char)); \n dbms_output.put_line(CHR(Test_Char1)); \n \nEND; "
},
{
"code": null,
"e": 25956,
"s": 25948,
"text": "Output:"
},
{
"code": null,
"e": 25960,
"s": 25956,
"text": "E\nH"
},
{
"code": null,
"e": 25971,
"s": 25960,
"text": "SQL-PL/SQL"
},
{
"code": null,
"e": 25975,
"s": 25971,
"text": "SQL"
},
{
"code": null,
"e": 25979,
"s": 25975,
"text": "SQL"
},
{
"code": null,
"e": 26077,
"s": 25979,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26101,
"s": 26077,
"text": "SQL Interview Questions"
},
{
"code": null,
"e": 26112,
"s": 26101,
"text": "CTE in SQL"
},
{
"code": null,
"e": 26143,
"s": 26112,
"text": "SQL Trigger | Student Database"
},
{
"code": null,
"e": 26209,
"s": 26143,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 26221,
"s": 26209,
"text": "SQL | Views"
},
{
"code": null,
"e": 26260,
"s": 26221,
"text": "Difference between DDL and DML in DBMS"
},
{
"code": null,
"e": 26305,
"s": 26260,
"text": "Difference between DELETE, DROP and TRUNCATE"
},
{
"code": null,
"e": 26337,
"s": 26305,
"text": "MySQL | Group_CONCAT() Function"
},
{
"code": null,
"e": 26376,
"s": 26337,
"text": "Difference between DELETE and TRUNCATE"
}
] |
JQuery | parseJSON() method - GeeksforGeeks
|
27 Apr, 2020
This parseJSON() Method in jQuery takes a well-formed JSON string and returns the resulting JavaScript value.
Syntax:
jQuery.parseJSON( json )
Parameters: The parseXML() method accepts only one parameter that is mentioned above and described below:
json: This parameter is the well-formed JSON string to be parsed.
String
Number
Object
Array
Boolean
Example 1:
<!DOCTYPE html><html><head><meta charset="utf-8"><title>JQuery | parseJSON() method</title> <script src="https://code.jquery.com/jquery-3.4.1.js"></script><style> #a { color: blue; } #b { color: red; }</style></head><body style="text-align:center;"> <h1 style="color: green"> GeeksForGeeks </h1> <h3>JQuery | parseJSON() method</h3> <b id="a"></b> <script> var txt = '{"name":"John", "age":30, "city":"New York"}' var obj = jQuery.parseJSON(txt); document.getElementById("a").innerHTML = "Object Name : "+obj.name + "<br> Object Age : " + obj.age; </script></body></html>
Output:
Example 2: .
<!DOCTYPE html><html><head><meta charset="utf-8"><title>JQuery | parseJSON() method</title> <script src="https://code.jquery.com/jquery-3.4.1.js"></script> </head><body style="text-align:center;"> <h1 style="color: green"> GeeksForGeeks </h1> <h3>JQuery | parseJSON() method</h3> <button onclick="gfg()">Click</button> <script> function gfg(){ var txt = '{"name":"Shubham Singh", "age":21, "Cars":"ABC" }' var obj = jQuery.parseJSON(txt); alert( obj.name === "ABC" ); } </script></body></html>
Output:Before Click:After Click:
jQuery-Methods
JQuery
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
JQuery | Set the value of an input text field
Form validation using jQuery
How to change selected value of a drop-down list using jQuery?
How to change the background color after clicking the button in JavaScript ?
How to fetch data from JSON file and display in HTML table using jQuery ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 41968,
"s": 41940,
"text": "\n27 Apr, 2020"
},
{
"code": null,
"e": 42078,
"s": 41968,
"text": "This parseJSON() Method in jQuery takes a well-formed JSON string and returns the resulting JavaScript value."
},
{
"code": null,
"e": 42086,
"s": 42078,
"text": "Syntax:"
},
{
"code": null,
"e": 42112,
"s": 42086,
"text": "jQuery.parseJSON( json )\n"
},
{
"code": null,
"e": 42218,
"s": 42112,
"text": "Parameters: The parseXML() method accepts only one parameter that is mentioned above and described below:"
},
{
"code": null,
"e": 42284,
"s": 42218,
"text": "json: This parameter is the well-formed JSON string to be parsed."
},
{
"code": null,
"e": 42291,
"s": 42284,
"text": "String"
},
{
"code": null,
"e": 42298,
"s": 42291,
"text": "Number"
},
{
"code": null,
"e": 42305,
"s": 42298,
"text": "Object"
},
{
"code": null,
"e": 42311,
"s": 42305,
"text": "Array"
},
{
"code": null,
"e": 42319,
"s": 42311,
"text": "Boolean"
},
{
"code": null,
"e": 42330,
"s": 42319,
"text": "Example 1:"
},
{
"code": "<!DOCTYPE html><html><head><meta charset=\"utf-8\"><title>JQuery | parseJSON() method</title> <script src=\"https://code.jquery.com/jquery-3.4.1.js\"></script><style> #a { color: blue; } #b { color: red; }</style></head><body style=\"text-align:center;\"> <h1 style=\"color: green\"> GeeksForGeeks </h1> <h3>JQuery | parseJSON() method</h3> <b id=\"a\"></b> <script> var txt = '{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}' var obj = jQuery.parseJSON(txt); document.getElementById(\"a\").innerHTML = \"Object Name : \"+obj.name + \"<br> Object Age : \" + obj.age; </script></body></html> ",
"e": 43048,
"s": 42330,
"text": null
},
{
"code": null,
"e": 43056,
"s": 43048,
"text": "Output:"
},
{
"code": null,
"e": 43069,
"s": 43056,
"text": "Example 2: ."
},
{
"code": "<!DOCTYPE html><html><head><meta charset=\"utf-8\"><title>JQuery | parseJSON() method</title> <script src=\"https://code.jquery.com/jquery-3.4.1.js\"></script> </head><body style=\"text-align:center;\"> <h1 style=\"color: green\"> GeeksForGeeks </h1> <h3>JQuery | parseJSON() method</h3> <button onclick=\"gfg()\">Click</button> <script> function gfg(){ var txt = '{\"name\":\"Shubham Singh\", \"age\":21, \"Cars\":\"ABC\" }' var obj = jQuery.parseJSON(txt); alert( obj.name === \"ABC\" ); } </script></body></html> ",
"e": 43682,
"s": 43069,
"text": null
},
{
"code": null,
"e": 43715,
"s": 43682,
"text": "Output:Before Click:After Click:"
},
{
"code": null,
"e": 43730,
"s": 43715,
"text": "jQuery-Methods"
},
{
"code": null,
"e": 43737,
"s": 43730,
"text": "JQuery"
},
{
"code": null,
"e": 43754,
"s": 43737,
"text": "Web Technologies"
},
{
"code": null,
"e": 43852,
"s": 43754,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 43898,
"s": 43852,
"text": "JQuery | Set the value of an input text field"
},
{
"code": null,
"e": 43927,
"s": 43898,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 43990,
"s": 43927,
"text": "How to change selected value of a drop-down list using jQuery?"
},
{
"code": null,
"e": 44067,
"s": 43990,
"text": "How to change the background color after clicking the button in JavaScript ?"
},
{
"code": null,
"e": 44141,
"s": 44067,
"text": "How to fetch data from JSON file and display in HTML table using jQuery ?"
},
{
"code": null,
"e": 44181,
"s": 44141,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 44214,
"s": 44181,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 44259,
"s": 44214,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 44302,
"s": 44259,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Internal Working of HashMap in Java
|
22 Jun, 2022
In this article, we will see how the hashmap get and put method works internally. What operations are performed? How the hashing is done. How the value is fetched by key. How the key-value pair is stored.In the previous article, HashMap contains an array of Node and Node can represent a class having the following objects :
int hashK keyV valueNode next
int hash
K key
V value
Node next
Now we will see how this works. First, we will see the hashing process.
Hashing
Hashing is a process of converting an object into integer form by using the method hashCode(). It’s necessary to write the hashCode() method properly for better performance of HashMap. Here I am taking the key of my class so that I can override the hashCode() method to show different scenarios. My Key class is
//custom Key class to override hashCode()
// and equals() method
class Key
{
String key;
Key(String key)
{
this.key = key;
}
@Override
public int hashCode()
{
return (int)key.charAt(0);
}
@Override
public boolean equals(Object obj)
{
return key.equals((String)obj);
}
}
Here override hashCode() method returns the first character’s ASCII value as hash code. So whenever the first character of the key is same, the hash code will be the same. You should not approach these criteria in your program. It is just for demo purposes. As HashMap also allows a null key, so hash code of null will always be 0.
hashCode() method
hashCode() method is used to get the hash code of an object. hashCode() method of the object class returns the memory reference of an object in integer form. Definition of hashCode() method is public native hashCode(). It indicates the implementation of hashCode() is native because there is not any direct method in java to fetch the reference of the object. It is possible to provide your implementation of hashCode(). In HashMap, hashCode() is used to calculate the bucket and therefore calculate the index.
equals() method
This method is used to check whether 2 objects are equal or not. This method is provided by the Object class. You can override this in your class to provide your implementation. HashMap uses equals() to compare the key to whether they are equal or not. If the equals() method return true, they are equal otherwise not equal.
Buckets
A bucket is one element of the HashMap array. It is used to store nodes. Two or more nodes can have the same bucket. In that case, a link list structure is used to connect the nodes. Buckets are different in capacity. A relation between bucket and capacity is as follows:
capacity = number of buckets * load factor
A single bucket can have more than one node, it depends on the hashCode() method. The better your hashCode() method is, the better your buckets will be utilized.
Index Calculation in Hashmap
The Hash code of the key may be large enough to create an array. hash code generated may be in the range of integer and if we create arrays for such a range, then it will easily cause outOfMemoryException. So we generate an index to minimize the size of the array. The following operation is performed to calculate the index.
index = hashCode(key) & (n-1).
where n is the number of buckets or the size of the array. In our example, I will consider n as the default size which is 16.
Why the above method is used to calculate the index
Using a bitwise AND operator is similar to doing bit masking wherein only the lower bits of the hash integer is considered which in turn provides a very efficient method of calculating the modulus based on the length of the hashmap.
Initially Empty hashMap: Here, the hashmap’s size is taken as 16.
HashMap map = new HashMap();
HashMap :
Inserting Key-Value Pair: Putting one key-value pair in the above HashMap
map.put(new Key("vishal"), 20);
Steps: Calculate hash code of Key {“vishal”}. It will be generated as 118.Calculate index by using index method it will be 6.Create a node object as :
Calculate hash code of Key {“vishal”}. It will be generated as 118.Calculate index by using index method it will be 6.Create a node object as :
Calculate hash code of Key {“vishal”}. It will be generated as 118.
Calculate index by using index method it will be 6.
Create a node object as :
{
int hash = 118
// {"vishal"} is not a string but
// an object of class Key
Key key = {"vishal"}
Integer value = 20
Node next = null
}
Place this object at index 6, if no other object is presented there.
Place this object at index 6, if no other object is presented there.
Inserting another Key-Value Pair: Now, putting the other pair that is,
map.put(new Key("sachin"), 30);
Steps:Calculate hashCode of Key {“sachin”}. It will be generated as 115.Calculate index by using index method it will be 3.Create a node object as :
Calculate hashCode of Key {“sachin”}. It will be generated as 115.Calculate index by using index method it will be 3.Create a node object as :
Calculate hashCode of Key {“sachin”}. It will be generated as 115.
Calculate index by using index method it will be 3.
Create a node object as :
{
int hash = 115
Key key = {"sachin"}
Integer value = 30
Node next = null
}
In Case of collision: Now, putting another pair that is,
map.put(new Key("vaibhav"), 40);
Steps: Calculate hash code of Key {“vaibhav”}. It will be generated as 118.Calculate index by using index method it will be 6.Create a node object as :
Calculate hash code of Key {“vaibhav”}. It will be generated as 118.Calculate index by using index method it will be 6.Create a node object as :
Calculate hash code of Key {“vaibhav”}. It will be generated as 118.
Calculate index by using index method it will be 6.
Create a node object as :
{
int hash = 118
Key key = {"vaibhav"}
Integer value = 40
Node next = null
}
Place this object at index 6 if no other object is presented there.In this case, a node object is found at index 6 – this is a case of collision.In that case, check via the hashCode() and equals() method if both the keys are the same.If keys are the same, replace the value with the current value.Otherwise, connect this node object to the previous node object via linked list and both are stored at index 6. Now HashMap becomes :
Place this object at index 6 if no other object is presented there.
In this case, a node object is found at index 6 – this is a case of collision.
In that case, check via the hashCode() and equals() method if both the keys are the same.
If keys are the same, replace the value with the current value.
Otherwise, connect this node object to the previous node object via linked list and both are stored at index 6. Now HashMap becomes :
Using the get method()
Now let’s try some get methods to get a value. get(K key) method is used to get a value by its key. If you don’t know the key then it is not possible to fetch a value.
Fetch the data for key sachin:
map.get(new Key("sachin"));
Steps: Calculate hash code of Key {“sachin”}. It will be generated as 115.Calculate index by using index method it will be 3.Go to index 3 of the array and compare the first element’s key with the given key. If both are equals then return the value, otherwise, check for the next element if it exists.In our case, it is found as the first element and the returned value is 30.
Calculate hash code of Key {“sachin”}. It will be generated as 115.Calculate index by using index method it will be 3.Go to index 3 of the array and compare the first element’s key with the given key. If both are equals then return the value, otherwise, check for the next element if it exists.In our case, it is found as the first element and the returned value is 30.
Calculate hash code of Key {“sachin”}. It will be generated as 115.
Calculate index by using index method it will be 3.
Go to index 3 of the array and compare the first element’s key with the given key. If both are equals then return the value, otherwise, check for the next element if it exists.
In our case, it is found as the first element and the returned value is 30.
Fetch the data for key vaibhav:
map.get(new Key("vaibhav"));
Steps: Calculate hash code of Key {“vaibhav”}. It will be generated as 118.Calculate index by using index method it will be 6.Go to index 6 of the array and compare the first element’s key with the given key. If both are equals then return the value, otherwise, check for the next element if it exists.In our case, it is not found as the first element and the next node object is not null.If the next node is null then return null.If the next of node is not null traverse to the second element and repeat process 3 until the key is not found or next is not null.Time complexity is almost constant for the put and the get method until rehashing is not done.In case of collision, i.e. index of two or more nodes are the same, nodes are joined by a link list i.e. the second node is referenced by the first node and the third by the second, and so on.If the key given already exist in HashMap, the value is replaced with the new value.hash code of the null key is 0.When getting an object with its key, the linked list is traversed until the key matches or null is found on the next field.
Calculate hash code of Key {“vaibhav”}. It will be generated as 118.Calculate index by using index method it will be 6.Go to index 6 of the array and compare the first element’s key with the given key. If both are equals then return the value, otherwise, check for the next element if it exists.In our case, it is not found as the first element and the next node object is not null.If the next node is null then return null.If the next of node is not null traverse to the second element and repeat process 3 until the key is not found or next is not null.Time complexity is almost constant for the put and the get method until rehashing is not done.In case of collision, i.e. index of two or more nodes are the same, nodes are joined by a link list i.e. the second node is referenced by the first node and the third by the second, and so on.If the key given already exist in HashMap, the value is replaced with the new value.hash code of the null key is 0.When getting an object with its key, the linked list is traversed until the key matches or null is found on the next field.
Calculate hash code of Key {“vaibhav”}. It will be generated as 118.
Calculate index by using index method it will be 6.
Go to index 6 of the array and compare the first element’s key with the given key. If both are equals then return the value, otherwise, check for the next element if it exists.
In our case, it is not found as the first element and the next node object is not null.
If the next node is null then return null.
If the next of node is not null traverse to the second element and repeat process 3 until the key is not found or next is not null.
Time complexity is almost constant for the put and the get method until rehashing is not done.
In case of collision, i.e. index of two or more nodes are the same, nodes are joined by a link list i.e. the second node is referenced by the first node and the third by the second, and so on.
If the key given already exist in HashMap, the value is replaced with the new value.
hash code of the null key is 0.
When getting an object with its key, the linked list is traversed until the key matches or null is found on the next field.
ShubhamDeshmukh
danish arora
shivakumaras2427
harshmaster07705
akd3257
Java-HashMap
Java-Map-Programs
Hash
Java
Hash
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
What is Hashing | A Complete Tutorial
Count pairs with given sum
Sort string of characters
Longest Consecutive Subsequence
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": 54,
"s": 26,
"text": "\n22 Jun, 2022"
},
{
"code": null,
"e": 381,
"s": 54,
"text": "In this article, we will see how the hashmap get and put method works internally. What operations are performed? How the hashing is done. How the value is fetched by key. How the key-value pair is stored.In the previous article, HashMap contains an array of Node and Node can represent a class having the following objects : "
},
{
"code": null,
"e": 411,
"s": 381,
"text": "int hashK keyV valueNode next"
},
{
"code": null,
"e": 420,
"s": 411,
"text": "int hash"
},
{
"code": null,
"e": 426,
"s": 420,
"text": "K key"
},
{
"code": null,
"e": 434,
"s": 426,
"text": "V value"
},
{
"code": null,
"e": 444,
"s": 434,
"text": "Node next"
},
{
"code": null,
"e": 518,
"s": 444,
"text": "Now we will see how this works. First, we will see the hashing process. "
},
{
"code": null,
"e": 526,
"s": 518,
"text": "Hashing"
},
{
"code": null,
"e": 840,
"s": 526,
"text": "Hashing is a process of converting an object into integer form by using the method hashCode(). It’s necessary to write the hashCode() method properly for better performance of HashMap. Here I am taking the key of my class so that I can override the hashCode() method to show different scenarios. My Key class is "
},
{
"code": null,
"e": 1152,
"s": 840,
"text": "//custom Key class to override hashCode()\n// and equals() method\nclass Key\n{\n String key;\n Key(String key)\n {\n this.key = key;\n }\n \n @Override\n public int hashCode() \n {\n return (int)key.charAt(0);\n }\n\n @Override\n public boolean equals(Object obj)\n {\n return key.equals((String)obj);\n }\n}"
},
{
"code": null,
"e": 1485,
"s": 1152,
"text": "Here override hashCode() method returns the first character’s ASCII value as hash code. So whenever the first character of the key is same, the hash code will be the same. You should not approach these criteria in your program. It is just for demo purposes. As HashMap also allows a null key, so hash code of null will always be 0. "
},
{
"code": null,
"e": 1503,
"s": 1485,
"text": "hashCode() method"
},
{
"code": null,
"e": 2016,
"s": 1503,
"text": "hashCode() method is used to get the hash code of an object. hashCode() method of the object class returns the memory reference of an object in integer form. Definition of hashCode() method is public native hashCode(). It indicates the implementation of hashCode() is native because there is not any direct method in java to fetch the reference of the object. It is possible to provide your implementation of hashCode(). In HashMap, hashCode() is used to calculate the bucket and therefore calculate the index. "
},
{
"code": null,
"e": 2032,
"s": 2016,
"text": "equals() method"
},
{
"code": null,
"e": 2359,
"s": 2032,
"text": "This method is used to check whether 2 objects are equal or not. This method is provided by the Object class. You can override this in your class to provide your implementation. HashMap uses equals() to compare the key to whether they are equal or not. If the equals() method return true, they are equal otherwise not equal. "
},
{
"code": null,
"e": 2367,
"s": 2359,
"text": "Buckets"
},
{
"code": null,
"e": 2641,
"s": 2367,
"text": "A bucket is one element of the HashMap array. It is used to store nodes. Two or more nodes can have the same bucket. In that case, a link list structure is used to connect the nodes. Buckets are different in capacity. A relation between bucket and capacity is as follows: "
},
{
"code": null,
"e": 2684,
"s": 2641,
"text": "capacity = number of buckets * load factor"
},
{
"code": null,
"e": 2848,
"s": 2684,
"text": "A single bucket can have more than one node, it depends on the hashCode() method. The better your hashCode() method is, the better your buckets will be utilized. "
},
{
"code": null,
"e": 2877,
"s": 2848,
"text": "Index Calculation in Hashmap"
},
{
"code": null,
"e": 3205,
"s": 2877,
"text": "The Hash code of the key may be large enough to create an array. hash code generated may be in the range of integer and if we create arrays for such a range, then it will easily cause outOfMemoryException. So we generate an index to minimize the size of the array. The following operation is performed to calculate the index. "
},
{
"code": null,
"e": 3236,
"s": 3205,
"text": "index = hashCode(key) & (n-1)."
},
{
"code": null,
"e": 3363,
"s": 3236,
"text": "where n is the number of buckets or the size of the array. In our example, I will consider n as the default size which is 16. "
},
{
"code": null,
"e": 3415,
"s": 3363,
"text": "Why the above method is used to calculate the index"
},
{
"code": null,
"e": 3649,
"s": 3415,
"text": "Using a bitwise AND operator is similar to doing bit masking wherein only the lower bits of the hash integer is considered which in turn provides a very efficient method of calculating the modulus based on the length of the hashmap. "
},
{
"code": null,
"e": 3717,
"s": 3649,
"text": "Initially Empty hashMap: Here, the hashmap’s size is taken as 16. "
},
{
"code": null,
"e": 3746,
"s": 3717,
"text": "HashMap map = new HashMap();"
},
{
"code": null,
"e": 3758,
"s": 3746,
"text": "HashMap : "
},
{
"code": null,
"e": 3834,
"s": 3758,
"text": "Inserting Key-Value Pair: Putting one key-value pair in the above HashMap "
},
{
"code": null,
"e": 3866,
"s": 3834,
"text": "map.put(new Key(\"vishal\"), 20);"
},
{
"code": null,
"e": 4019,
"s": 3866,
"text": "Steps: Calculate hash code of Key {“vishal”}. It will be generated as 118.Calculate index by using index method it will be 6.Create a node object as : "
},
{
"code": null,
"e": 4165,
"s": 4019,
"text": "Calculate hash code of Key {“vishal”}. It will be generated as 118.Calculate index by using index method it will be 6.Create a node object as : "
},
{
"code": null,
"e": 4233,
"s": 4165,
"text": "Calculate hash code of Key {“vishal”}. It will be generated as 118."
},
{
"code": null,
"e": 4285,
"s": 4233,
"text": "Calculate index by using index method it will be 6."
},
{
"code": null,
"e": 4313,
"s": 4285,
"text": "Create a node object as : "
},
{
"code": null,
"e": 4464,
"s": 4313,
"text": "{\n int hash = 118\n\n // {\"vishal\"} is not a string but \n // an object of class Key\n Key key = {\"vishal\"}\n\n Integer value = 20\n Node next = null\n}"
},
{
"code": null,
"e": 4534,
"s": 4464,
"text": " Place this object at index 6, if no other object is presented there."
},
{
"code": null,
"e": 4605,
"s": 4536,
"text": "Place this object at index 6, if no other object is presented there."
},
{
"code": null,
"e": 4678,
"s": 4605,
"text": "Inserting another Key-Value Pair: Now, putting the other pair that is, "
},
{
"code": null,
"e": 4710,
"s": 4678,
"text": "map.put(new Key(\"sachin\"), 30);"
},
{
"code": null,
"e": 4861,
"s": 4710,
"text": "Steps:Calculate hashCode of Key {“sachin”}. It will be generated as 115.Calculate index by using index method it will be 3.Create a node object as : "
},
{
"code": null,
"e": 5006,
"s": 4861,
"text": "Calculate hashCode of Key {“sachin”}. It will be generated as 115.Calculate index by using index method it will be 3.Create a node object as : "
},
{
"code": null,
"e": 5073,
"s": 5006,
"text": "Calculate hashCode of Key {“sachin”}. It will be generated as 115."
},
{
"code": null,
"e": 5125,
"s": 5073,
"text": "Calculate index by using index method it will be 3."
},
{
"code": null,
"e": 5153,
"s": 5125,
"text": "Create a node object as : "
},
{
"code": null,
"e": 5237,
"s": 5153,
"text": "{\n int hash = 115\n Key key = {\"sachin\"}\n Integer value = 30\n Node next = null\n}"
},
{
"code": null,
"e": 5298,
"s": 5239,
"text": "In Case of collision: Now, putting another pair that is, "
},
{
"code": null,
"e": 5331,
"s": 5298,
"text": "map.put(new Key(\"vaibhav\"), 40);"
},
{
"code": null,
"e": 5483,
"s": 5331,
"text": "Steps: Calculate hash code of Key {“vaibhav”}. It will be generated as 118.Calculate index by using index method it will be 6.Create a node object as :"
},
{
"code": null,
"e": 5628,
"s": 5483,
"text": "Calculate hash code of Key {“vaibhav”}. It will be generated as 118.Calculate index by using index method it will be 6.Create a node object as :"
},
{
"code": null,
"e": 5697,
"s": 5628,
"text": "Calculate hash code of Key {“vaibhav”}. It will be generated as 118."
},
{
"code": null,
"e": 5749,
"s": 5697,
"text": "Calculate index by using index method it will be 6."
},
{
"code": null,
"e": 5775,
"s": 5749,
"text": "Create a node object as :"
},
{
"code": null,
"e": 5861,
"s": 5775,
"text": " {\n int hash = 118\n Key key = {\"vaibhav\"}\n Integer value = 40\n Node next = null\n}"
},
{
"code": null,
"e": 6292,
"s": 5861,
"text": "Place this object at index 6 if no other object is presented there.In this case, a node object is found at index 6 – this is a case of collision.In that case, check via the hashCode() and equals() method if both the keys are the same.If keys are the same, replace the value with the current value.Otherwise, connect this node object to the previous node object via linked list and both are stored at index 6. Now HashMap becomes :"
},
{
"code": null,
"e": 6360,
"s": 6292,
"text": "Place this object at index 6 if no other object is presented there."
},
{
"code": null,
"e": 6439,
"s": 6360,
"text": "In this case, a node object is found at index 6 – this is a case of collision."
},
{
"code": null,
"e": 6529,
"s": 6439,
"text": "In that case, check via the hashCode() and equals() method if both the keys are the same."
},
{
"code": null,
"e": 6593,
"s": 6529,
"text": "If keys are the same, replace the value with the current value."
},
{
"code": null,
"e": 6727,
"s": 6593,
"text": "Otherwise, connect this node object to the previous node object via linked list and both are stored at index 6. Now HashMap becomes :"
},
{
"code": null,
"e": 6752,
"s": 6729,
"text": "Using the get method()"
},
{
"code": null,
"e": 6922,
"s": 6752,
"text": "Now let’s try some get methods to get a value. get(K key) method is used to get a value by its key. If you don’t know the key then it is not possible to fetch a value. "
},
{
"code": null,
"e": 6953,
"s": 6922,
"text": "Fetch the data for key sachin:"
},
{
"code": null,
"e": 6981,
"s": 6953,
"text": "map.get(new Key(\"sachin\"));"
},
{
"code": null,
"e": 7358,
"s": 6981,
"text": "Steps: Calculate hash code of Key {“sachin”}. It will be generated as 115.Calculate index by using index method it will be 3.Go to index 3 of the array and compare the first element’s key with the given key. If both are equals then return the value, otherwise, check for the next element if it exists.In our case, it is found as the first element and the returned value is 30."
},
{
"code": null,
"e": 7728,
"s": 7358,
"text": "Calculate hash code of Key {“sachin”}. It will be generated as 115.Calculate index by using index method it will be 3.Go to index 3 of the array and compare the first element’s key with the given key. If both are equals then return the value, otherwise, check for the next element if it exists.In our case, it is found as the first element and the returned value is 30."
},
{
"code": null,
"e": 7796,
"s": 7728,
"text": "Calculate hash code of Key {“sachin”}. It will be generated as 115."
},
{
"code": null,
"e": 7848,
"s": 7796,
"text": "Calculate index by using index method it will be 3."
},
{
"code": null,
"e": 8025,
"s": 7848,
"text": "Go to index 3 of the array and compare the first element’s key with the given key. If both are equals then return the value, otherwise, check for the next element if it exists."
},
{
"code": null,
"e": 8101,
"s": 8025,
"text": "In our case, it is found as the first element and the returned value is 30."
},
{
"code": null,
"e": 8135,
"s": 8101,
"text": "Fetch the data for key vaibhav: "
},
{
"code": null,
"e": 8164,
"s": 8135,
"text": "map.get(new Key(\"vaibhav\"));"
},
{
"code": null,
"e": 9251,
"s": 8164,
"text": "Steps: Calculate hash code of Key {“vaibhav”}. It will be generated as 118.Calculate index by using index method it will be 6.Go to index 6 of the array and compare the first element’s key with the given key. If both are equals then return the value, otherwise, check for the next element if it exists.In our case, it is not found as the first element and the next node object is not null.If the next node is null then return null.If the next of node is not null traverse to the second element and repeat process 3 until the key is not found or next is not null.Time complexity is almost constant for the put and the get method until rehashing is not done.In case of collision, i.e. index of two or more nodes are the same, nodes are joined by a link list i.e. the second node is referenced by the first node and the third by the second, and so on.If the key given already exist in HashMap, the value is replaced with the new value.hash code of the null key is 0.When getting an object with its key, the linked list is traversed until the key matches or null is found on the next field."
},
{
"code": null,
"e": 10331,
"s": 9251,
"text": "Calculate hash code of Key {“vaibhav”}. It will be generated as 118.Calculate index by using index method it will be 6.Go to index 6 of the array and compare the first element’s key with the given key. If both are equals then return the value, otherwise, check for the next element if it exists.In our case, it is not found as the first element and the next node object is not null.If the next node is null then return null.If the next of node is not null traverse to the second element and repeat process 3 until the key is not found or next is not null.Time complexity is almost constant for the put and the get method until rehashing is not done.In case of collision, i.e. index of two or more nodes are the same, nodes are joined by a link list i.e. the second node is referenced by the first node and the third by the second, and so on.If the key given already exist in HashMap, the value is replaced with the new value.hash code of the null key is 0.When getting an object with its key, the linked list is traversed until the key matches or null is found on the next field."
},
{
"code": null,
"e": 10400,
"s": 10331,
"text": "Calculate hash code of Key {“vaibhav”}. It will be generated as 118."
},
{
"code": null,
"e": 10452,
"s": 10400,
"text": "Calculate index by using index method it will be 6."
},
{
"code": null,
"e": 10629,
"s": 10452,
"text": "Go to index 6 of the array and compare the first element’s key with the given key. If both are equals then return the value, otherwise, check for the next element if it exists."
},
{
"code": null,
"e": 10717,
"s": 10629,
"text": "In our case, it is not found as the first element and the next node object is not null."
},
{
"code": null,
"e": 10760,
"s": 10717,
"text": "If the next node is null then return null."
},
{
"code": null,
"e": 10892,
"s": 10760,
"text": "If the next of node is not null traverse to the second element and repeat process 3 until the key is not found or next is not null."
},
{
"code": null,
"e": 10987,
"s": 10892,
"text": "Time complexity is almost constant for the put and the get method until rehashing is not done."
},
{
"code": null,
"e": 11180,
"s": 10987,
"text": "In case of collision, i.e. index of two or more nodes are the same, nodes are joined by a link list i.e. the second node is referenced by the first node and the third by the second, and so on."
},
{
"code": null,
"e": 11265,
"s": 11180,
"text": "If the key given already exist in HashMap, the value is replaced with the new value."
},
{
"code": null,
"e": 11297,
"s": 11265,
"text": "hash code of the null key is 0."
},
{
"code": null,
"e": 11421,
"s": 11297,
"text": "When getting an object with its key, the linked list is traversed until the key matches or null is found on the next field."
},
{
"code": null,
"e": 11437,
"s": 11421,
"text": "ShubhamDeshmukh"
},
{
"code": null,
"e": 11450,
"s": 11437,
"text": "danish arora"
},
{
"code": null,
"e": 11467,
"s": 11450,
"text": "shivakumaras2427"
},
{
"code": null,
"e": 11484,
"s": 11467,
"text": "harshmaster07705"
},
{
"code": null,
"e": 11492,
"s": 11484,
"text": "akd3257"
},
{
"code": null,
"e": 11505,
"s": 11492,
"text": "Java-HashMap"
},
{
"code": null,
"e": 11523,
"s": 11505,
"text": "Java-Map-Programs"
},
{
"code": null,
"e": 11528,
"s": 11523,
"text": "Hash"
},
{
"code": null,
"e": 11533,
"s": 11528,
"text": "Java"
},
{
"code": null,
"e": 11538,
"s": 11533,
"text": "Hash"
},
{
"code": null,
"e": 11543,
"s": 11538,
"text": "Java"
},
{
"code": null,
"e": 11641,
"s": 11543,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 11726,
"s": 11641,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 11764,
"s": 11726,
"text": "What is Hashing | A Complete Tutorial"
},
{
"code": null,
"e": 11791,
"s": 11764,
"text": "Count pairs with given sum"
},
{
"code": null,
"e": 11817,
"s": 11791,
"text": "Sort string of characters"
},
{
"code": null,
"e": 11849,
"s": 11817,
"text": "Longest Consecutive Subsequence"
},
{
"code": null,
"e": 11864,
"s": 11849,
"text": "Arrays in Java"
},
{
"code": null,
"e": 11900,
"s": 11864,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 11944,
"s": 11900,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 11969,
"s": 11944,
"text": "Reverse a string in Java"
}
] |
plotly.express.scatter_ternary() function in Python
|
17 Jul, 2020
Plotly library of Python can be very useful for data visualization and understanding the data simply and easily. Plotly graph objects are a high-level interface to plotly which are easy to use.
This method is used to create a ternary plot. A ternary plot is used to depics the ratio of three variables on an equilateral triangle.
Syntax: plotly.express.scatter_ternary(data_frame=None, a=None, b=None, c=None, color=None, symbol=None, size=None, text=None, hover_name=None, hover_data=None, size_max=None, title=None, template=None, width=None, height=None)
Parameters:
data_frame: DataFrame or array-like or dict needs to be passed for column names.
a, b, c: These parameters are either a name of a column in data_frame, or a pandas Series or array_like object. These are used to position marks along the a, b, and c axis in ternary coordinates respectively.
color: This parameters assign color to marks.
symbol: This parameter is used to assign symbols to marks. It is either a name of a column in data_frame, or a pandas Series or array_like object.
size: This parameter is used to assign mark sizes. It is either a name of a column in data_frame, or a pandas Series or array_like object.
hover_name: Values from this column or array_like appear in bold in the hover tooltip.
hover_data: This parameter is used to appear in the hover tooltip or tuples with a bool or formatting string as first element, and list-like data to appear in hover as second element Values from these columns appear as extra data in the hover tooltip.
title: The title of the figure.
width: Set the width of the figure.
height: Set the height of the figure.
Example 1:
Python3
import plotly.express as px df = px.data.iris() plot = px.scatter_ternary(df, a = 'sepal_width', b = 'sepal_length', c = 'petal_width')plot.show()
Output:
Example 2: Using the size and color arguments
Python3
import plotly.express as px df = px.data.iris() plot = px.scatter_ternary(df, a = 'sepal_width', b = 'sepal_length', c='petal_width', color = 'species', size = 'petal_length')plot.show()
Output:
Example 3: Using the symbol parameter
Python3
import plotly.express as px df = px.data.iris() plot = px.scatter_ternary(df, a = 'sepal_width', b = 'sepal_length', c = 'petal_width', color = 'species', size = 'petal_length', symbol = 'species_id')plot.show()
Output:
Python Plotly express-class
Python-Plotly
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 Jul, 2020"
},
{
"code": null,
"e": 222,
"s": 28,
"text": "Plotly library of Python can be very useful for data visualization and understanding the data simply and easily. Plotly graph objects are a high-level interface to plotly which are easy to use."
},
{
"code": null,
"e": 358,
"s": 222,
"text": "This method is used to create a ternary plot. A ternary plot is used to depics the ratio of three variables on an equilateral triangle."
},
{
"code": null,
"e": 586,
"s": 358,
"text": "Syntax: plotly.express.scatter_ternary(data_frame=None, a=None, b=None, c=None, color=None, symbol=None, size=None, text=None, hover_name=None, hover_data=None, size_max=None, title=None, template=None, width=None, height=None)"
},
{
"code": null,
"e": 598,
"s": 586,
"text": "Parameters:"
},
{
"code": null,
"e": 679,
"s": 598,
"text": "data_frame: DataFrame or array-like or dict needs to be passed for column names."
},
{
"code": null,
"e": 889,
"s": 679,
"text": "a, b, c: These parameters are either a name of a column in data_frame, or a pandas Series or array_like object. These are used to position marks along the a, b, and c axis in ternary coordinates respectively."
},
{
"code": null,
"e": 935,
"s": 889,
"text": "color: This parameters assign color to marks."
},
{
"code": null,
"e": 1082,
"s": 935,
"text": "symbol: This parameter is used to assign symbols to marks. It is either a name of a column in data_frame, or a pandas Series or array_like object."
},
{
"code": null,
"e": 1221,
"s": 1082,
"text": "size: This parameter is used to assign mark sizes. It is either a name of a column in data_frame, or a pandas Series or array_like object."
},
{
"code": null,
"e": 1309,
"s": 1221,
"text": "hover_name: Values from this column or array_like appear in bold in the hover tooltip."
},
{
"code": null,
"e": 1561,
"s": 1309,
"text": "hover_data: This parameter is used to appear in the hover tooltip or tuples with a bool or formatting string as first element, and list-like data to appear in hover as second element Values from these columns appear as extra data in the hover tooltip."
},
{
"code": null,
"e": 1593,
"s": 1561,
"text": "title: The title of the figure."
},
{
"code": null,
"e": 1629,
"s": 1593,
"text": "width: Set the width of the figure."
},
{
"code": null,
"e": 1667,
"s": 1629,
"text": "height: Set the height of the figure."
},
{
"code": null,
"e": 1678,
"s": 1667,
"text": "Example 1:"
},
{
"code": null,
"e": 1686,
"s": 1678,
"text": "Python3"
},
{
"code": "import plotly.express as px df = px.data.iris() plot = px.scatter_ternary(df, a = 'sepal_width', b = 'sepal_length', c = 'petal_width')plot.show()",
"e": 1886,
"s": 1686,
"text": null
},
{
"code": null,
"e": 1894,
"s": 1886,
"text": "Output:"
},
{
"code": null,
"e": 1940,
"s": 1894,
"text": "Example 2: Using the size and color arguments"
},
{
"code": null,
"e": 1948,
"s": 1940,
"text": "Python3"
},
{
"code": "import plotly.express as px df = px.data.iris() plot = px.scatter_ternary(df, a = 'sepal_width', b = 'sepal_length', c='petal_width', color = 'species', size = 'petal_length')plot.show()",
"e": 2238,
"s": 1948,
"text": null
},
{
"code": null,
"e": 2246,
"s": 2238,
"text": "Output:"
},
{
"code": null,
"e": 2284,
"s": 2246,
"text": "Example 3: Using the symbol parameter"
},
{
"code": null,
"e": 2292,
"s": 2284,
"text": "Python3"
},
{
"code": "import plotly.express as px df = px.data.iris() plot = px.scatter_ternary(df, a = 'sepal_width', b = 'sepal_length', c = 'petal_width', color = 'species', size = 'petal_length', symbol = 'species_id')plot.show()",
"e": 2633,
"s": 2292,
"text": null
},
{
"code": null,
"e": 2641,
"s": 2633,
"text": "Output:"
},
{
"code": null,
"e": 2669,
"s": 2641,
"text": "Python Plotly express-class"
},
{
"code": null,
"e": 2683,
"s": 2669,
"text": "Python-Plotly"
},
{
"code": null,
"e": 2690,
"s": 2683,
"text": "Python"
}
] |
PyQtGraph – Getting Histogram Object for Image View
|
25 May, 2022
In this article, we will see how we can get the histogram object of the image view object in PyQTGaph. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.). Widget used for display and analysis of image data. Implements many features like displaying 2D and 3D image data. For 3D data, a z-axis slider is displayed allowing the user to select which frame is displayed. Displays histogram of image data with movable region defining the dark/light levels, editable gradient provides a color lookup table, frame slider may also be moved using left/right arrow keys as well as pgup, pgdn, home, and end. A histogram is a graphical display of data using bars of different heights. In a histogram, each bar group numbers into ranges. Taller bars show that more data falls in that range.We can create an image view with the help of the command given below.
# creating a pyqtgraph image view object
imv = pg.ImageView()
In order to do this we use getHistogramWidget method with the image view objectSyntax : imv.getHistogramWidget()Argument : It takes no argumentReturn : It returns HistogramLUTWidget object
Below is the implementation.
Python3
# importing Qt widgetsfrom PyQt5.QtWidgets import * # importing systemimport sys # importing numpy as npimport numpy as np # importing pyqtgraph as pgimport pyqtgraph as pgfrom PyQt5.QtGui import *from PyQt5.QtCore import * from collections import namedtuple class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("PyQtGraph") # setting geometry self.setGeometry(100, 100, 600, 500) # icon icon = QIcon("skin.png") # setting icon to the window self.setWindowIcon(icon) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a widget object widget = QWidget() # creating a label label = QLabel("Geeksforgeeks Image View") # setting minimum width label.setMinimumWidth(130) # making label do word wrap label.setWordWrap(True) # setting configuration options pg.setConfigOptions(antialias=True) # creating image view object imv = pg.ImageView() # Create random 3D data set with noisy signals img = pg.gaussianFilter(np.random.normal( size=(200, 200)), (5, 5)) * 20 + 100 # setting new axis to image img = img[np.newaxis, :, :] # decay data decay = np.exp(-np.linspace(0, 0.3, 100))[:, np.newaxis, np.newaxis] # random data data = np.random.normal(size=(100, 200, 200)) data += img * decay data += 2 # adding time-varying signal sig = np.zeros(data.shape[0]) sig[30:] += np.exp(-np.linspace(1, 10, 70)) sig[40:] += np.exp(-np.linspace(1, 10, 60)) sig[70:] += np.exp(-np.linspace(1, 10, 30)) sig = sig[:, np.newaxis, np.newaxis] * 3 data[:, 50:60, 30:40] += sig # Displaying the data and assign each frame a time value from 1.0 to 3.0 imv.setImage(data, xvals=np.linspace(1., 3., data.shape[0])) # Set a custom color map colors = [ (0, 0, 0), (45, 5, 61), (84, 42, 55), (150, 87, 60), (208, 171, 141), (255, 255, 255) ] # color map cmap = pg.ColorMap(pos=np.linspace(0.0, 1.0, 6), color=colors) # setting color map to the image view imv.setColorMap(cmap) # Creating a grid layout layout = QGridLayout() # minimum width value of the label label.setFixedWidth(130) # setting this layout to the widget widget.setLayout(layout) # adding label in the layout layout.addWidget(label, 1, 0) # plot window goes on right side, spanning 3 rows layout.addWidget(imv, 0, 1, 3, 1) # setting this widget as central widget of the main window self.setCentralWidget(widget) # getting histogram object from image view value = imv.getHistogramWidget() # setting text to the label label.setText("Histogram Widget : " + str(value)) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :
sweetyty
Python-gui
Python-PyQtGraph
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n25 May, 2022"
},
{
"code": null,
"e": 1072,
"s": 28,
"text": "In this article, we will see how we can get the histogram object of the image view object in PyQTGaph. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.). Widget used for display and analysis of image data. Implements many features like displaying 2D and 3D image data. For 3D data, a z-axis slider is displayed allowing the user to select which frame is displayed. Displays histogram of image data with movable region defining the dark/light levels, editable gradient provides a color lookup table, frame slider may also be moved using left/right arrow keys as well as pgup, pgdn, home, and end. A histogram is a graphical display of data using bars of different heights. In a histogram, each bar group numbers into ranges. Taller bars show that more data falls in that range.We can create an image view with the help of the command given below."
},
{
"code": null,
"e": 1134,
"s": 1072,
"text": "# creating a pyqtgraph image view object\nimv = pg.ImageView()"
},
{
"code": null,
"e": 1324,
"s": 1134,
"text": "In order to do this we use getHistogramWidget method with the image view objectSyntax : imv.getHistogramWidget()Argument : It takes no argumentReturn : It returns HistogramLUTWidget object "
},
{
"code": null,
"e": 1353,
"s": 1324,
"text": "Below is the implementation."
},
{
"code": null,
"e": 1361,
"s": 1353,
"text": "Python3"
},
{
"code": "# importing Qt widgetsfrom PyQt5.QtWidgets import * # importing systemimport sys # importing numpy as npimport numpy as np # importing pyqtgraph as pgimport pyqtgraph as pgfrom PyQt5.QtGui import *from PyQt5.QtCore import * from collections import namedtuple class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"PyQtGraph\") # setting geometry self.setGeometry(100, 100, 600, 500) # icon icon = QIcon(\"skin.png\") # setting icon to the window self.setWindowIcon(icon) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a widget object widget = QWidget() # creating a label label = QLabel(\"Geeksforgeeks Image View\") # setting minimum width label.setMinimumWidth(130) # making label do word wrap label.setWordWrap(True) # setting configuration options pg.setConfigOptions(antialias=True) # creating image view object imv = pg.ImageView() # Create random 3D data set with noisy signals img = pg.gaussianFilter(np.random.normal( size=(200, 200)), (5, 5)) * 20 + 100 # setting new axis to image img = img[np.newaxis, :, :] # decay data decay = np.exp(-np.linspace(0, 0.3, 100))[:, np.newaxis, np.newaxis] # random data data = np.random.normal(size=(100, 200, 200)) data += img * decay data += 2 # adding time-varying signal sig = np.zeros(data.shape[0]) sig[30:] += np.exp(-np.linspace(1, 10, 70)) sig[40:] += np.exp(-np.linspace(1, 10, 60)) sig[70:] += np.exp(-np.linspace(1, 10, 30)) sig = sig[:, np.newaxis, np.newaxis] * 3 data[:, 50:60, 30:40] += sig # Displaying the data and assign each frame a time value from 1.0 to 3.0 imv.setImage(data, xvals=np.linspace(1., 3., data.shape[0])) # Set a custom color map colors = [ (0, 0, 0), (45, 5, 61), (84, 42, 55), (150, 87, 60), (208, 171, 141), (255, 255, 255) ] # color map cmap = pg.ColorMap(pos=np.linspace(0.0, 1.0, 6), color=colors) # setting color map to the image view imv.setColorMap(cmap) # Creating a grid layout layout = QGridLayout() # minimum width value of the label label.setFixedWidth(130) # setting this layout to the widget widget.setLayout(layout) # adding label in the layout layout.addWidget(label, 1, 0) # plot window goes on right side, spanning 3 rows layout.addWidget(imv, 0, 1, 3, 1) # setting this widget as central widget of the main window self.setCentralWidget(widget) # getting histogram object from image view value = imv.getHistogramWidget() # setting text to the label label.setText(\"Histogram Widget : \" + str(value)) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())",
"e": 4617,
"s": 1361,
"text": null
},
{
"code": null,
"e": 4628,
"s": 4617,
"text": "Output : "
},
{
"code": null,
"e": 4639,
"s": 4630,
"text": "sweetyty"
},
{
"code": null,
"e": 4650,
"s": 4639,
"text": "Python-gui"
},
{
"code": null,
"e": 4667,
"s": 4650,
"text": "Python-PyQtGraph"
},
{
"code": null,
"e": 4674,
"s": 4667,
"text": "Python"
}
] |
set::lower_bound() function in C++ STL
|
05 Jun, 2022
The set::lower_bound() is a built-in function in C++ STL which returns an iterator pointing to the element in the container which is equivalent to k passed in the parameter. In case k is not present in the set container, the function returns an iterator pointing to the immediate next element which is just greater than k. If the key passed in the parameter exceeds the maximum value in the container, then the iterator returned points to the element beyond last element in the set container.
Time Complexity of set::lower_bound() is O(logn), where n is the size of the set.Syntax:
set_name.lower_bound(key)
Parameters: This function accepts a single mandatory parameter key which specifies the element whose lower_bound is to be returned.Return Value: The function returns an iterator pointing to the element in the container which is equivalent to k passed in the parameter. In case k is not present in the set container, the function returns an iterator pointing to the immediate next element which is just greater than k. If the key passed in the parameter exceeds the maximum value in the container, then the iterator returned is equivalent to s.end() (A special iterator points beyond the last element). Below program illustrate the above function:
CPP
// CPP program to demonstrate the// set::lower_bound() function#include <bits/stdc++.h>using namespace std;int main(){ set<int> s; // Function to insert elements // in the set container s.insert(1); s.insert(4); s.insert(2); s.insert(5); s.insert(6); cout << "The set elements are: "; for (auto it = s.begin(); it != s.end(); it++) cout << *it << " "; // when 2 is present auto it = s.lower_bound(2); if (it != s.end()) { cout << "\nThe lower bound of key 2 is "; cout << (*it) << endl; } else cout << "The element entered is larger than the " "greatest element in the set" << endl; // when 3 is not present // points to next greater after 3 it = s.lower_bound(3); if (it != s.end()) { cout << "The lower bound of key 3 is "; cout << (*it) << endl; } else cout << "The element entered is larger than the " "greatest element in the set" << endl; // when 8 exceeds the max element in set it = s.lower_bound(8); if (it != s.end()) { cout << "The lower bound of key 8 is "; cout << (*it) << endl; } else cout << "The element is larger than the greatest " "element in the set" << endl; return 0;}
The set elements are: 1 2 4 5 6
The lower bound of key 2 is 2
The lower bound of key 3 is 4
The element is larger than the greatest element in the set
shubham_1210
yash_1604
asadityasingh60
mahtodeepanshu
CPP-Functions
cpp-set
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Priority Queue in C++ Standard Template Library (STL)
vector erase() and clear() in C++
Substring in C++
Sorting a vector in C++
2D Vector In C++ With User Defined Size
C++ Data Types
Virtual Function in C++
Templates in C++ with Examples
Multidimensional Arrays in C / C++
Operator Overloading in C++
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n05 Jun, 2022"
},
{
"code": null,
"e": 546,
"s": 52,
"text": "The set::lower_bound() is a built-in function in C++ STL which returns an iterator pointing to the element in the container which is equivalent to k passed in the parameter. In case k is not present in the set container, the function returns an iterator pointing to the immediate next element which is just greater than k. If the key passed in the parameter exceeds the maximum value in the container, then the iterator returned points to the element beyond last element in the set container. "
},
{
"code": null,
"e": 636,
"s": 546,
"text": "Time Complexity of set::lower_bound() is O(logn), where n is the size of the set.Syntax: "
},
{
"code": null,
"e": 662,
"s": 636,
"text": "set_name.lower_bound(key)"
},
{
"code": null,
"e": 1310,
"s": 662,
"text": "Parameters: This function accepts a single mandatory parameter key which specifies the element whose lower_bound is to be returned.Return Value: The function returns an iterator pointing to the element in the container which is equivalent to k passed in the parameter. In case k is not present in the set container, the function returns an iterator pointing to the immediate next element which is just greater than k. If the key passed in the parameter exceeds the maximum value in the container, then the iterator returned is equivalent to s.end() (A special iterator points beyond the last element). Below program illustrate the above function: "
},
{
"code": null,
"e": 1314,
"s": 1310,
"text": "CPP"
},
{
"code": "// CPP program to demonstrate the// set::lower_bound() function#include <bits/stdc++.h>using namespace std;int main(){ set<int> s; // Function to insert elements // in the set container s.insert(1); s.insert(4); s.insert(2); s.insert(5); s.insert(6); cout << \"The set elements are: \"; for (auto it = s.begin(); it != s.end(); it++) cout << *it << \" \"; // when 2 is present auto it = s.lower_bound(2); if (it != s.end()) { cout << \"\\nThe lower bound of key 2 is \"; cout << (*it) << endl; } else cout << \"The element entered is larger than the \" \"greatest element in the set\" << endl; // when 3 is not present // points to next greater after 3 it = s.lower_bound(3); if (it != s.end()) { cout << \"The lower bound of key 3 is \"; cout << (*it) << endl; } else cout << \"The element entered is larger than the \" \"greatest element in the set\" << endl; // when 8 exceeds the max element in set it = s.lower_bound(8); if (it != s.end()) { cout << \"The lower bound of key 8 is \"; cout << (*it) << endl; } else cout << \"The element is larger than the greatest \" \"element in the set\" << endl; return 0;}",
"e": 2644,
"s": 1314,
"text": null
},
{
"code": null,
"e": 2796,
"s": 2644,
"text": "The set elements are: 1 2 4 5 6 \nThe lower bound of key 2 is 2\nThe lower bound of key 3 is 4\nThe element is larger than the greatest element in the set"
},
{
"code": null,
"e": 2811,
"s": 2798,
"text": "shubham_1210"
},
{
"code": null,
"e": 2821,
"s": 2811,
"text": "yash_1604"
},
{
"code": null,
"e": 2837,
"s": 2821,
"text": "asadityasingh60"
},
{
"code": null,
"e": 2852,
"s": 2837,
"text": "mahtodeepanshu"
},
{
"code": null,
"e": 2866,
"s": 2852,
"text": "CPP-Functions"
},
{
"code": null,
"e": 2874,
"s": 2866,
"text": "cpp-set"
},
{
"code": null,
"e": 2878,
"s": 2874,
"text": "STL"
},
{
"code": null,
"e": 2882,
"s": 2878,
"text": "C++"
},
{
"code": null,
"e": 2886,
"s": 2882,
"text": "STL"
},
{
"code": null,
"e": 2890,
"s": 2886,
"text": "CPP"
},
{
"code": null,
"e": 2988,
"s": 2890,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3042,
"s": 2988,
"text": "Priority Queue in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 3076,
"s": 3042,
"text": "vector erase() and clear() in C++"
},
{
"code": null,
"e": 3093,
"s": 3076,
"text": "Substring in C++"
},
{
"code": null,
"e": 3117,
"s": 3093,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 3157,
"s": 3117,
"text": "2D Vector In C++ With User Defined Size"
},
{
"code": null,
"e": 3172,
"s": 3157,
"text": "C++ Data Types"
},
{
"code": null,
"e": 3196,
"s": 3172,
"text": "Virtual Function in C++"
},
{
"code": null,
"e": 3227,
"s": 3196,
"text": "Templates in C++ with Examples"
},
{
"code": null,
"e": 3262,
"s": 3227,
"text": "Multidimensional Arrays in C / C++"
}
] |
Secant method to solve non-linear equation
|
Secant method is also used to solve non-linear equations. This method is similar to the Newton-Raphson method, but here we do not need to find the differentiation of the function f(x). Only using f(x), we can find f’(x) numerically by using Newton’s Divide difference formula. From the Newton-Raphson formula,
we know that,
Now, using divide difference formula, we get,
By replacing the f’(x) of Newton-Raphson formula by the new f’(x), we can find the secant formula to solve non-linear equations.
Note: For this method, we need any two initial guess to start finding the root of non-linear equations.
Input:
The function f(x) = (x*x) - (4*x) - 10
Output:
The root is: -1.74166
secant(x1, x2)
Input: Two initial guess for root.
Output: The approximate root of a non-linear equation f(x).
Begin
f1 := f(x1)
f2 := f(x2)
x3 := ((f2*x1) – (f1*x2)) / (f2 – f1)
while relative error of x3 and x2 are > precision, do
x1 := x2
f1 := f2
x2 := x3
f2 := f(x2)
x3 := ((f2*x1) – (f1*x2)) / (f2 – f1)
done
root := x3
return root
End
#include<iostream>
#include<cmath>
using namespace std;
double absolute(double value) { //to find magnitude of value
if(value < 0)
return (-value);
return value;
}
double f(double x) { //the given function x^2-4x-10
return ((x*x)-(4*x)-10);
}
double secant(double x1, double x2) {
double x3, root;
double f1, f2;
f1 = f(x1);
f2 = f(x2);
x3 = (f2*x1-f1*x2)/(f2-f1);
while(absolute((x3-x2)/x3) > 0.00001) { //test accuracy of x3
x1 = x2; //shift x values
f1 = f2;
x2 = x3;
f2 = f(x2); //find new x2
x3 = (f2*x1-f1*x2)/(f2-f1); //calculate x3
}
root = x3;
return root; //root of the equation
}
main() {
double a, b, res;
a = 0.5;
b = 0.75;
res = secant(a, b);
cout << "The root is: " << res;
}
The root is: -1.74166
|
[
{
"code": null,
"e": 1497,
"s": 1187,
"text": "Secant method is also used to solve non-linear equations. This method is similar to the Newton-Raphson method, but here we do not need to find the differentiation of the function f(x). Only using f(x), we can find f’(x) numerically by using Newton’s Divide difference formula. From the Newton-Raphson formula,"
},
{
"code": null,
"e": 1511,
"s": 1497,
"text": "we know that,"
},
{
"code": null,
"e": 1557,
"s": 1511,
"text": "Now, using divide difference formula, we get,"
},
{
"code": null,
"e": 1686,
"s": 1557,
"text": "By replacing the f’(x) of Newton-Raphson formula by the new f’(x), we can find the secant formula to solve non-linear equations."
},
{
"code": null,
"e": 1790,
"s": 1686,
"text": "Note: For this method, we need any two initial guess to start finding the root of non-linear equations."
},
{
"code": null,
"e": 1866,
"s": 1790,
"text": "Input:\nThe function f(x) = (x*x) - (4*x) - 10\nOutput:\nThe root is: -1.74166"
},
{
"code": null,
"e": 1881,
"s": 1866,
"text": "secant(x1, x2)"
},
{
"code": null,
"e": 1916,
"s": 1881,
"text": "Input: Two initial guess for root."
},
{
"code": null,
"e": 1976,
"s": 1916,
"text": "Output: The approximate root of a non-linear equation f(x)."
},
{
"code": null,
"e": 2258,
"s": 1976,
"text": "Begin\n f1 := f(x1)\n f2 := f(x2)\n x3 := ((f2*x1) – (f1*x2)) / (f2 – f1)\n while relative error of x3 and x2 are > precision, do\n x1 := x2\n f1 := f2\n x2 := x3\n f2 := f(x2)\n x3 := ((f2*x1) – (f1*x2)) / (f2 – f1)\n done\n root := x3\n return root\nEnd"
},
{
"code": null,
"e": 3123,
"s": 2258,
"text": "#include<iostream>\n#include<cmath>\nusing namespace std;\n\ndouble absolute(double value) { //to find magnitude of value\n if(value < 0)\n return (-value);\n return value;\n}\n\ndouble f(double x) { //the given function x^2-4x-10\n return ((x*x)-(4*x)-10);\n}\n\ndouble secant(double x1, double x2) {\n double x3, root;\n double f1, f2;\n f1 = f(x1);\n f2 = f(x2);\n x3 = (f2*x1-f1*x2)/(f2-f1);\n\n while(absolute((x3-x2)/x3) > 0.00001) { //test accuracy of x3\n x1 = x2; //shift x values\n f1 = f2;\n x2 = x3;\n f2 = f(x2); //find new x2\n x3 = (f2*x1-f1*x2)/(f2-f1); //calculate x3\n }\n\n root = x3;\n return root; //root of the equation\n}\n\nmain() {\n double a, b, res;\n a = 0.5;\n b = 0.75;\n res = secant(a, b);\n cout << \"The root is: \" << res;\n}"
},
{
"code": null,
"e": 3145,
"s": 3123,
"text": "The root is: -1.74166"
}
] |
Random vs Secure Random numbers in Java
|
09 Nov, 2020
Prerequisite: Generating Random numbers in Javajava.security.SecureRandom class: This class provides a cryptographically strong random number generator (RNG). A cryptographically strong random number minimally complies with the statistical random number generator tests specified in FIPS 140-2, Security Requirements for Cryptographic Modules, section 4.9.1. Additionally, SecureRandom must produce non-deterministic output. Therefore any seed material passed to a SecureRandom object must be unpredictable, and all SecureRandom output sequences must be cryptographically strong.java.util.Random class: The classes defined in Random are not cryptographically strong, and the numbers chosen are not completely random because a definite mathematical algorithm (based on Donald E. Knuth’s subtractive random number generator algorithm) is used to select them. Therefore, it is not safe to use this class for tasks that require a high level of security, like creating a random password etc.
Random vs SecureRandom
Size: A Random class has only 48 bits whereas SecureRandom can have up to 128 bits. So the chances of repeating in SecureRandom are smaller.Seed Generation: Random uses the system clock as the seed/or to generate the seed. So they can be reproduced easily if the attacker knows the time at which the seed was generated. But SecureRandom takes Random Data from your OS (they can be interval between keystrokes etc – most OS collect these data and store them in files – /dev/random and /dev/urandom in case of linux/solaris) and use that as the seed.Breaking the code: In case of random, just 2^48 attempts are required, with today’s advanced cpu’s it is possible to break it in practical time. But for securerandom 2^128 attempts will be required, which will take years and years to break even with today’s advanced machines.Generating Function: The standard Oracle JDK 7 implementation uses what’s called a Linear Congruential Generator to produce random values in java.util.Random. Whereas Secure Random implements SHA1PRNG algorithm, which uses SHA1 to generate pseudo-random numbers. The algorithm computes the SHA-1 hash over a true random number(uses an entropy source) and then concatenates it with a 64-bit counter which increments by 1 on each operation.Security: Consequently, the java.util. The random class must not be used either for security-critical applications or for protecting sensitive data.
Size: A Random class has only 48 bits whereas SecureRandom can have up to 128 bits. So the chances of repeating in SecureRandom are smaller.
Seed Generation: Random uses the system clock as the seed/or to generate the seed. So they can be reproduced easily if the attacker knows the time at which the seed was generated. But SecureRandom takes Random Data from your OS (they can be interval between keystrokes etc – most OS collect these data and store them in files – /dev/random and /dev/urandom in case of linux/solaris) and use that as the seed.
Breaking the code: In case of random, just 2^48 attempts are required, with today’s advanced cpu’s it is possible to break it in practical time. But for securerandom 2^128 attempts will be required, which will take years and years to break even with today’s advanced machines.
Generating Function: The standard Oracle JDK 7 implementation uses what’s called a Linear Congruential Generator to produce random values in java.util.Random. Whereas Secure Random implements SHA1PRNG algorithm, which uses SHA1 to generate pseudo-random numbers. The algorithm computes the SHA-1 hash over a true random number(uses an entropy source) and then concatenates it with a 64-bit counter which increments by 1 on each operation.
Security: Consequently, the java.util. The random class must not be used either for security-critical applications or for protecting sensitive data.
Generating Random number using java.util.Random;
Java
// A Java program to demonstrate// random number generation// using java.util.Random;import java.util.Random; public class generateRandom { public static void main(String args[]) { // create instance of Random class Random rand = new Random(); // Generate random integers in range 0 to 999 int rand_int1 = rand.nextInt(1000); int rand_int2 = rand.nextInt(1000); // Print random integers System.out.println("Random Integers: " + rand_int1); System.out.println("Random Integers: " + rand_int2); }}
Output:
Random Integers: 956
Random Integers: 678
Generating Random number using java.security.SecureRandom;
Java
// A Java program to demonstrate secure// random number generation// using java.security.SecureRandomimport java.security.SecureRandom; public class generateRandom { public static void main(String args[]) { // create instance of SecureRandom class SecureRandom rand = new SecureRandom(); // Generate random integers in range 0 to 999 int rand_int1 = rand.nextInt(1000); int rand_int2 = rand.nextInt(1000); // Print random integers System.out.println("Random Integers: " + rand_int1); System.out.println("Random Integers: " + rand_int2); }}
Output:
Random Integers: 817
Random Integers: 500
This article is contributed by Saket Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
AbhijitPatil3
user_tmyc
Java-Library
Difference Between
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Differences between JDK, JRE and JVM
Stack vs Heap Memory Allocation
Difference between Process and Thread
Arrays.sort() in Java with examples
Object Oriented Programming (OOPs) Concept in Java
Reverse a string in Java
For-each loop in Java
How to iterate any Map in Java
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n09 Nov, 2020"
},
{
"code": null,
"e": 1041,
"s": 53,
"text": "Prerequisite: Generating Random numbers in Javajava.security.SecureRandom class: This class provides a cryptographically strong random number generator (RNG). A cryptographically strong random number minimally complies with the statistical random number generator tests specified in FIPS 140-2, Security Requirements for Cryptographic Modules, section 4.9.1. Additionally, SecureRandom must produce non-deterministic output. Therefore any seed material passed to a SecureRandom object must be unpredictable, and all SecureRandom output sequences must be cryptographically strong.java.util.Random class: The classes defined in Random are not cryptographically strong, and the numbers chosen are not completely random because a definite mathematical algorithm (based on Donald E. Knuth’s subtractive random number generator algorithm) is used to select them. Therefore, it is not safe to use this class for tasks that require a high level of security, like creating a random password etc. "
},
{
"code": null,
"e": 1064,
"s": 1041,
"text": "Random vs SecureRandom"
},
{
"code": null,
"e": 2476,
"s": 1064,
"text": "Size: A Random class has only 48 bits whereas SecureRandom can have up to 128 bits. So the chances of repeating in SecureRandom are smaller.Seed Generation: Random uses the system clock as the seed/or to generate the seed. So they can be reproduced easily if the attacker knows the time at which the seed was generated. But SecureRandom takes Random Data from your OS (they can be interval between keystrokes etc – most OS collect these data and store them in files – /dev/random and /dev/urandom in case of linux/solaris) and use that as the seed.Breaking the code: In case of random, just 2^48 attempts are required, with today’s advanced cpu’s it is possible to break it in practical time. But for securerandom 2^128 attempts will be required, which will take years and years to break even with today’s advanced machines.Generating Function: The standard Oracle JDK 7 implementation uses what’s called a Linear Congruential Generator to produce random values in java.util.Random. Whereas Secure Random implements SHA1PRNG algorithm, which uses SHA1 to generate pseudo-random numbers. The algorithm computes the SHA-1 hash over a true random number(uses an entropy source) and then concatenates it with a 64-bit counter which increments by 1 on each operation.Security: Consequently, the java.util. The random class must not be used either for security-critical applications or for protecting sensitive data. "
},
{
"code": null,
"e": 2617,
"s": 2476,
"text": "Size: A Random class has only 48 bits whereas SecureRandom can have up to 128 bits. So the chances of repeating in SecureRandom are smaller."
},
{
"code": null,
"e": 3026,
"s": 2617,
"text": "Seed Generation: Random uses the system clock as the seed/or to generate the seed. So they can be reproduced easily if the attacker knows the time at which the seed was generated. But SecureRandom takes Random Data from your OS (they can be interval between keystrokes etc – most OS collect these data and store them in files – /dev/random and /dev/urandom in case of linux/solaris) and use that as the seed."
},
{
"code": null,
"e": 3303,
"s": 3026,
"text": "Breaking the code: In case of random, just 2^48 attempts are required, with today’s advanced cpu’s it is possible to break it in practical time. But for securerandom 2^128 attempts will be required, which will take years and years to break even with today’s advanced machines."
},
{
"code": null,
"e": 3742,
"s": 3303,
"text": "Generating Function: The standard Oracle JDK 7 implementation uses what’s called a Linear Congruential Generator to produce random values in java.util.Random. Whereas Secure Random implements SHA1PRNG algorithm, which uses SHA1 to generate pseudo-random numbers. The algorithm computes the SHA-1 hash over a true random number(uses an entropy source) and then concatenates it with a 64-bit counter which increments by 1 on each operation."
},
{
"code": null,
"e": 3892,
"s": 3742,
"text": "Security: Consequently, the java.util. The random class must not be used either for security-critical applications or for protecting sensitive data. "
},
{
"code": null,
"e": 3942,
"s": 3892,
"text": "Generating Random number using java.util.Random; "
},
{
"code": null,
"e": 3947,
"s": 3942,
"text": "Java"
},
{
"code": "// A Java program to demonstrate// random number generation// using java.util.Random;import java.util.Random; public class generateRandom { public static void main(String args[]) { // create instance of Random class Random rand = new Random(); // Generate random integers in range 0 to 999 int rand_int1 = rand.nextInt(1000); int rand_int2 = rand.nextInt(1000); // Print random integers System.out.println(\"Random Integers: \" + rand_int1); System.out.println(\"Random Integers: \" + rand_int2); }}",
"e": 4511,
"s": 3947,
"text": null
},
{
"code": null,
"e": 4520,
"s": 4511,
"text": "Output: "
},
{
"code": null,
"e": 4563,
"s": 4520,
"text": "Random Integers: 956\nRandom Integers: 678\n"
},
{
"code": null,
"e": 4622,
"s": 4563,
"text": "Generating Random number using java.security.SecureRandom;"
},
{
"code": null,
"e": 4627,
"s": 4622,
"text": "Java"
},
{
"code": "// A Java program to demonstrate secure// random number generation// using java.security.SecureRandomimport java.security.SecureRandom; public class generateRandom { public static void main(String args[]) { // create instance of SecureRandom class SecureRandom rand = new SecureRandom(); // Generate random integers in range 0 to 999 int rand_int1 = rand.nextInt(1000); int rand_int2 = rand.nextInt(1000); // Print random integers System.out.println(\"Random Integers: \" + rand_int1); System.out.println(\"Random Integers: \" + rand_int2); }}",
"e": 5235,
"s": 4627,
"text": null
},
{
"code": null,
"e": 5244,
"s": 5235,
"text": "Output: "
},
{
"code": null,
"e": 5287,
"s": 5244,
"text": "Random Integers: 817\nRandom Integers: 500\n"
},
{
"code": null,
"e": 5710,
"s": 5287,
"text": "This article is contributed by Saket Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 5724,
"s": 5710,
"text": "AbhijitPatil3"
},
{
"code": null,
"e": 5734,
"s": 5724,
"text": "user_tmyc"
},
{
"code": null,
"e": 5747,
"s": 5734,
"text": "Java-Library"
},
{
"code": null,
"e": 5766,
"s": 5747,
"text": "Difference Between"
},
{
"code": null,
"e": 5771,
"s": 5766,
"text": "Java"
},
{
"code": null,
"e": 5776,
"s": 5771,
"text": "Java"
},
{
"code": null,
"e": 5874,
"s": 5776,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5935,
"s": 5874,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 6003,
"s": 5935,
"text": "Difference Between Method Overloading and Method Overriding in Java"
},
{
"code": null,
"e": 6040,
"s": 6003,
"text": "Differences between JDK, JRE and JVM"
},
{
"code": null,
"e": 6072,
"s": 6040,
"text": "Stack vs Heap Memory Allocation"
},
{
"code": null,
"e": 6110,
"s": 6072,
"text": "Difference between Process and Thread"
},
{
"code": null,
"e": 6146,
"s": 6110,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 6197,
"s": 6146,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 6222,
"s": 6197,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 6244,
"s": 6222,
"text": "For-each loop in Java"
}
] |
Window to Viewport Transformation in Computer Graphics with Implementation
|
04 Jun, 2021
Window to Viewport Transformation is the process of transforming 2D world-coordinate objects to device coordinates. Objects inside the world or clipping window are mapped to the viewport which is the area on the screen where world coordinates are mapped to be displayed.
General Terms:
World coordinate – It is the Cartesian coordinate w.r.t which we define the diagram, like Xwmin, Xwmax, Ywmin, Ywmax
Device Coordinate –It is the screen coordinate where the objects are to be displayed, like Xvmin, Xvmax, Yvmin, Yvmax
Window –It is the area on world coordinate selected for display.
ViewPort –It is the area on the device coordinate where graphics is to be displayed.
Mathematical Calculation of Window to Viewport: It may be possible that the size of the Viewport is much smaller or greater than the Window. In these cases, we have to increase or decrease the size of the Window according to the Viewport and for this, we need some mathematical calculations.
(xw, yw): A point on Window
(xv, yv): Corresponding point on Viewport
we have to calculate the point (xv, yv)
Now the relative position of the object in Window and Viewport are same.
For x coordinate,
For y coordinate,
so, after calculating for x and y coordinate, we get
where sx is the scaling factor of x coordinate and sy is the scaling factor of y coordinate
Example:Lets assume,
for window, Xwmin = 20, Xwmax = 80, Ywmin = 40, Ywmax = 80.
for viewport, Xvmin = 30, Xvmax = 60, Yvmin = 40, Yvmax = 60.
Now a point ( Xw, Yw ) be ( 30, 80 ) on the window. We have to calculate that point on the viewport i.e ( Xv, Yv ).
First of all, calculate the scaling factor of x coordinate Sx and the scaling factor of y coordinate Sy using the above-mentioned formula.
Sx = ( 60 - 30 ) / ( 80 - 20 ) = 30 / 60
Sy = ( 60 - 40 ) / ( 80 - 40 ) = 20 / 40
So, now calculate the point on the viewport ( Xv, Yv ).
Xv = 30 + ( 30 - 20 ) * ( 30 / 60 ) = 35
Yv = 40 + ( 80 - 40 ) * ( 20 / 40 ) = 60
So, the point on window ( Xw, Yw ) = ( 30, 80 ) will be ( Xv, Yv ) = ( 35, 60 ) on viewport.
Here is the implementation of the above approach:
C++
C
Java
Python3
C#
Javascript
// C++ program to implement// Window to ViewPort Transformation #include <iostream>using namespace std; // Function for window to viewport transformationvoid WindowtoViewport(int x_w, int y_w, int x_wmax, int y_wmax, int x_wmin, int y_wmin, int x_vmax, int y_vmax, int x_vmin, int y_vmin){ // point on viewport int x_v, y_v; // scaling factors for x coordinate and y coordinate float sx, sy; // calculating Sx and Sy sx = (float)(x_vmax - x_vmin) / (x_wmax - x_wmin); sy = (float)(y_vmax - y_vmin) / (y_wmax - y_wmin); // calculating the point on viewport x_v = x_vmin + (float)((x_w - x_wmin) * sx); y_v = y_vmin + (float)((y_w - y_wmin) * sy); cout<< "The point on viewport: ("<<x_v <<","<< y_v<<")" ;} // Driver Codeint main(){ // boundary values for window int x_wmax = 80, y_wmax = 80, x_wmin = 20, y_wmin = 40; // boundary values for viewport int x_vmax = 60, y_vmax = 60, x_vmin = 30, y_vmin = 40; // point on window int x_w = 30, y_w = 80; WindowtoViewport(30, 80, 80, 80, 20, 40, 60, 60, 30, 40);} // This code is contributed by khusboogoyal499.
// C program to implement// Window to ViewPort Transformation #include <stdio.h> // Function for window to viewport transformationvoid WindowtoViewport(int x_w, int y_w, int x_wmax, int y_wmax, int x_wmin, int y_wmin, int x_vmax, int y_vmax, int x_vmin, int y_vmin){ // point on viewport int x_v, y_v; // scaling factors for x coordinate and y coordinate float sx, sy; // calculating Sx and Sy sx = (float)(x_vmax - x_vmin) / (x_wmax - x_wmin); sy = (float)(y_vmax - y_vmin) / (y_wmax - y_wmin); // calculating the point on viewport x_v = x_vmin + (float)((x_w - x_wmin) * sx); y_v = y_vmin + (float)((y_w - y_wmin) * sy); printf("The point on viewport: (%d, %d )\n ", x_v, y_v);} // Driver Codevoid main(){ // boundary values for window int x_wmax = 80, y_wmax = 80, x_wmin = 20, y_wmin = 40; // boundary values for viewport int x_vmax = 60, y_vmax = 60, x_vmin = 30, y_vmin = 40; // point on window int x_w = 30, y_w = 80; WindowtoViewport(30, 80, 80, 80, 20, 40, 60, 60, 30, 40);} //this code is added by khushboogoyal499
// Java program to implement// Window to ViewPort Transformationclass GFG{ // Function for window to viewport transformationstatic void WindowtoViewport(int x_w, int y_w, int x_wmax, int y_wmax, int x_wmin, int y_wmin, int x_vmax, int y_vmax, int x_vmin, int y_vmin){ // point on viewport int x_v, y_v; // scaling factors for x coordinate and y coordinate float sx, sy; // calculating Sx and Sy sx = (float)(x_vmax - x_vmin) / (x_wmax - x_wmin); sy = (float)(y_vmax - y_vmin) / (y_wmax - y_wmin); // calculating the point on viewport x_v = (int) (x_vmin + (float)((x_w - x_wmin) * sx)); y_v = (int) (y_vmin + (float)((y_w - y_wmin) * sy)); System.out.printf("The point on viewport: (%d, %d )\n ", x_v, y_v);} // Driver Codepublic static void main(String[] args){ // boundary values for window int x_wmax = 80, y_wmax = 80, x_wmin = 20, y_wmin = 40; // boundary values for viewport int x_vmax = 60, y_vmax = 60, x_vmin = 30, y_vmin = 40; // point on window int x_w = 30, y_w = 80; WindowtoViewport(30, 80, 80, 80, 20, 40, 60, 60, 30, 40);}} // This code is contributed by Rajput-Ji
# Python3 program to implement# Window to ViewPort Transformation # Function for window to viewport transformationdef WindowtoViewport(x_w, y_w, x_wmax, y_wmax, x_wmin, y_wmin, x_vmax, y_vmax, x_vmin, y_vmin): # point on viewport # calculating Sx and Sy sx = (x_vmax - x_vmin) / (x_wmax - x_wmin) sy = (y_vmax - y_vmin) / (y_wmax - y_wmin) # calculating the point on viewport x_v = x_vmin + ((x_w - x_wmin) * sx) y_v = y_vmin + ((y_w - y_wmin) * sy) print("The point on viewport:(", int(x_v), ",", int(y_v), ")") # Driver Codeif __name__ == '__main__': # boundary values for window x_wmax = 80 y_wmax = 80 x_wmin = 20 y_wmin = 40 # boundary values for viewport x_vmax = 60 y_vmax = 60 x_vmin = 30 y_vmin = 40 # point on window x_w = 30 y_w = 80 WindowtoViewport(30, 80, 80, 80, 20, 40, 60, 60, 30, 40) # This code is contributed by Surendra_Gangwar
// C# program to implement// Window to ViewPort Transformationusing System; class GFG{ // Function for window to viewport transformationstatic void WindowtoViewport(int x_w, int y_w, int x_wmax, int y_wmax, int x_wmin, int y_wmin, int x_vmax, int y_vmax, int x_vmin, int y_vmin){ // point on viewport int x_v, y_v; // scaling factors for x coordinate // and y coordinate float sx, sy; // calculating Sx and Sy sx = (float)(x_vmax - x_vmin) / (x_wmax - x_wmin); sy = (float)(y_vmax - y_vmin) / (y_wmax - y_wmin); // calculating the point on viewport x_v = (int) (x_vmin + (float)((x_w - x_wmin) * sx)); y_v = (int) (y_vmin + (float)((y_w - y_wmin) * sy)); Console.Write("The point on viewport: " + "({0}, {1} )\n ", x_v, y_v);} // Driver Codepublic static void Main(String[] args){ // boundary values for window int x_wmax = 80, y_wmax = 80, x_wmin = 20, y_wmin = 40; // boundary values for viewport int x_vmax = 60, y_vmax = 60, x_vmin = 30, y_vmin = 40; // point on window int x_w = 30, y_w = 80; WindowtoViewport(30, 80, 80, 80, 20, 40, 60, 60, 30, 40);}} // This code is contributed by PrinciRaj1992
<script>// Javascript program to implement// Window to ViewPort Transformation // Function for window to viewport transformationfunction WindowtoViewport(x_w, y_w, x_wmax,y_wmax, x_wmin, y_wmin,x_vmax, y_vmax, x_vmin,y_vmin){ // point on viewport let x_v, y_v; // scaling factors for x coordinate and y coordinate let sx, sy; // calculating Sx and Sy sx = (x_vmax - x_vmin) / (x_wmax - x_wmin); sy = (y_vmax - y_vmin) / (y_wmax - y_wmin); // calculating the point on viewport x_v = x_vmin + ((x_w - x_wmin) * sx); y_v = y_vmin + ((y_w - y_wmin) * sy); document.write("The point on viewport: (" + x_v + ", " + y_v + " )<br>");} // Driver Code // boundary values for window let x_wmax = 80, y_wmax = 80, x_wmin = 20, y_wmin = 40; // boundary values for viewport let x_vmax = 60, y_vmax = 60, x_vmin = 30, y_vmin = 40; // point on window let x_w = 30, y_w = 80; WindowtoViewport(30, 80, 80, 80, 20, 40, 60, 60, 30, 40); </script>
The point on viewport: (35, 60 )
soumya7
Akanksha_Rai
Rajput-Ji
princiraj1992
SURENDRA_GANGWAR
subham348
anikaseth98
khushboogoyal499
computer-graphics
Geometric
Mathematical
Mathematical
Geometric
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program for distance between two points on earth
Optimum location of point to minimize total distance
Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping)
Check whether a given point lies inside a triangle or not
Program for Point of Intersection of Two Lines
Program for Fibonacci numbers
Set in C++ Standard Template Library (STL)
Write a program to print all permutations of a given string
C++ Data Types
Merge two sorted arrays
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n04 Jun, 2021"
},
{
"code": null,
"e": 324,
"s": 52,
"text": "Window to Viewport Transformation is the process of transforming 2D world-coordinate objects to device coordinates. Objects inside the world or clipping window are mapped to the viewport which is the area on the screen where world coordinates are mapped to be displayed. "
},
{
"code": null,
"e": 340,
"s": 324,
"text": "General Terms: "
},
{
"code": null,
"e": 457,
"s": 340,
"text": "World coordinate – It is the Cartesian coordinate w.r.t which we define the diagram, like Xwmin, Xwmax, Ywmin, Ywmax"
},
{
"code": null,
"e": 575,
"s": 457,
"text": "Device Coordinate –It is the screen coordinate where the objects are to be displayed, like Xvmin, Xvmax, Yvmin, Yvmax"
},
{
"code": null,
"e": 640,
"s": 575,
"text": "Window –It is the area on world coordinate selected for display."
},
{
"code": null,
"e": 725,
"s": 640,
"text": "ViewPort –It is the area on the device coordinate where graphics is to be displayed."
},
{
"code": null,
"e": 1017,
"s": 725,
"text": "Mathematical Calculation of Window to Viewport: It may be possible that the size of the Viewport is much smaller or greater than the Window. In these cases, we have to increase or decrease the size of the Window according to the Viewport and for this, we need some mathematical calculations."
},
{
"code": null,
"e": 1088,
"s": 1017,
"text": "(xw, yw): A point on Window\n(xv, yv): Corresponding point on Viewport"
},
{
"code": null,
"e": 1129,
"s": 1088,
"text": "we have to calculate the point (xv, yv) "
},
{
"code": null,
"e": 1204,
"s": 1131,
"text": "Now the relative position of the object in Window and Viewport are same."
},
{
"code": null,
"e": 1246,
"s": 1204,
"text": "For x coordinate, "
},
{
"code": null,
"e": 1269,
"s": 1250,
"text": " For y coordinate,"
},
{
"code": null,
"e": 1325,
"s": 1271,
"text": "so, after calculating for x and y coordinate, we get "
},
{
"code": null,
"e": 1418,
"s": 1325,
"text": "where sx is the scaling factor of x coordinate and sy is the scaling factor of y coordinate "
},
{
"code": null,
"e": 1440,
"s": 1418,
"text": "Example:Lets assume, "
},
{
"code": null,
"e": 1500,
"s": 1440,
"text": "for window, Xwmin = 20, Xwmax = 80, Ywmin = 40, Ywmax = 80."
},
{
"code": null,
"e": 1562,
"s": 1500,
"text": "for viewport, Xvmin = 30, Xvmax = 60, Yvmin = 40, Yvmax = 60."
},
{
"code": null,
"e": 1678,
"s": 1562,
"text": "Now a point ( Xw, Yw ) be ( 30, 80 ) on the window. We have to calculate that point on the viewport i.e ( Xv, Yv )."
},
{
"code": null,
"e": 1817,
"s": 1678,
"text": "First of all, calculate the scaling factor of x coordinate Sx and the scaling factor of y coordinate Sy using the above-mentioned formula."
},
{
"code": null,
"e": 1899,
"s": 1817,
"text": "Sx = ( 60 - 30 ) / ( 80 - 20 ) = 30 / 60\nSy = ( 60 - 40 ) / ( 80 - 40 ) = 20 / 40"
},
{
"code": null,
"e": 1955,
"s": 1899,
"text": "So, now calculate the point on the viewport ( Xv, Yv )."
},
{
"code": null,
"e": 2037,
"s": 1955,
"text": "Xv = 30 + ( 30 - 20 ) * ( 30 / 60 ) = 35\nYv = 40 + ( 80 - 40 ) * ( 20 / 40 ) = 60"
},
{
"code": null,
"e": 2130,
"s": 2037,
"text": "So, the point on window ( Xw, Yw ) = ( 30, 80 ) will be ( Xv, Yv ) = ( 35, 60 ) on viewport."
},
{
"code": null,
"e": 2180,
"s": 2130,
"text": "Here is the implementation of the above approach:"
},
{
"code": null,
"e": 2184,
"s": 2180,
"text": "C++"
},
{
"code": null,
"e": 2186,
"s": 2184,
"text": "C"
},
{
"code": null,
"e": 2191,
"s": 2186,
"text": "Java"
},
{
"code": null,
"e": 2199,
"s": 2191,
"text": "Python3"
},
{
"code": null,
"e": 2202,
"s": 2199,
"text": "C#"
},
{
"code": null,
"e": 2213,
"s": 2202,
"text": "Javascript"
},
{
"code": "// C++ program to implement// Window to ViewPort Transformation #include <iostream>using namespace std; // Function for window to viewport transformationvoid WindowtoViewport(int x_w, int y_w, int x_wmax, int y_wmax, int x_wmin, int y_wmin, int x_vmax, int y_vmax, int x_vmin, int y_vmin){ // point on viewport int x_v, y_v; // scaling factors for x coordinate and y coordinate float sx, sy; // calculating Sx and Sy sx = (float)(x_vmax - x_vmin) / (x_wmax - x_wmin); sy = (float)(y_vmax - y_vmin) / (y_wmax - y_wmin); // calculating the point on viewport x_v = x_vmin + (float)((x_w - x_wmin) * sx); y_v = y_vmin + (float)((y_w - y_wmin) * sy); cout<< \"The point on viewport: (\"<<x_v <<\",\"<< y_v<<\")\" ;} // Driver Codeint main(){ // boundary values for window int x_wmax = 80, y_wmax = 80, x_wmin = 20, y_wmin = 40; // boundary values for viewport int x_vmax = 60, y_vmax = 60, x_vmin = 30, y_vmin = 40; // point on window int x_w = 30, y_w = 80; WindowtoViewport(30, 80, 80, 80, 20, 40, 60, 60, 30, 40);} // This code is contributed by khusboogoyal499.",
"e": 3393,
"s": 2213,
"text": null
},
{
"code": "// C program to implement// Window to ViewPort Transformation #include <stdio.h> // Function for window to viewport transformationvoid WindowtoViewport(int x_w, int y_w, int x_wmax, int y_wmax, int x_wmin, int y_wmin, int x_vmax, int y_vmax, int x_vmin, int y_vmin){ // point on viewport int x_v, y_v; // scaling factors for x coordinate and y coordinate float sx, sy; // calculating Sx and Sy sx = (float)(x_vmax - x_vmin) / (x_wmax - x_wmin); sy = (float)(y_vmax - y_vmin) / (y_wmax - y_wmin); // calculating the point on viewport x_v = x_vmin + (float)((x_w - x_wmin) * sx); y_v = y_vmin + (float)((y_w - y_wmin) * sy); printf(\"The point on viewport: (%d, %d )\\n \", x_v, y_v);} // Driver Codevoid main(){ // boundary values for window int x_wmax = 80, y_wmax = 80, x_wmin = 20, y_wmin = 40; // boundary values for viewport int x_vmax = 60, y_vmax = 60, x_vmin = 30, y_vmin = 40; // point on window int x_w = 30, y_w = 80; WindowtoViewport(30, 80, 80, 80, 20, 40, 60, 60, 30, 40);} //this code is added by khushboogoyal499",
"e": 4542,
"s": 3393,
"text": null
},
{
"code": "// Java program to implement// Window to ViewPort Transformationclass GFG{ // Function for window to viewport transformationstatic void WindowtoViewport(int x_w, int y_w, int x_wmax, int y_wmax, int x_wmin, int y_wmin, int x_vmax, int y_vmax, int x_vmin, int y_vmin){ // point on viewport int x_v, y_v; // scaling factors for x coordinate and y coordinate float sx, sy; // calculating Sx and Sy sx = (float)(x_vmax - x_vmin) / (x_wmax - x_wmin); sy = (float)(y_vmax - y_vmin) / (y_wmax - y_wmin); // calculating the point on viewport x_v = (int) (x_vmin + (float)((x_w - x_wmin) * sx)); y_v = (int) (y_vmin + (float)((y_w - y_wmin) * sy)); System.out.printf(\"The point on viewport: (%d, %d )\\n \", x_v, y_v);} // Driver Codepublic static void main(String[] args){ // boundary values for window int x_wmax = 80, y_wmax = 80, x_wmin = 20, y_wmin = 40; // boundary values for viewport int x_vmax = 60, y_vmax = 60, x_vmin = 30, y_vmin = 40; // point on window int x_w = 30, y_w = 80; WindowtoViewport(30, 80, 80, 80, 20, 40, 60, 60, 30, 40);}} // This code is contributed by Rajput-Ji",
"e": 5742,
"s": 4542,
"text": null
},
{
"code": "# Python3 program to implement# Window to ViewPort Transformation # Function for window to viewport transformationdef WindowtoViewport(x_w, y_w, x_wmax, y_wmax, x_wmin, y_wmin, x_vmax, y_vmax, x_vmin, y_vmin): # point on viewport # calculating Sx and Sy sx = (x_vmax - x_vmin) / (x_wmax - x_wmin) sy = (y_vmax - y_vmin) / (y_wmax - y_wmin) # calculating the point on viewport x_v = x_vmin + ((x_w - x_wmin) * sx) y_v = y_vmin + ((y_w - y_wmin) * sy) print(\"The point on viewport:(\", int(x_v), \",\", int(y_v), \")\") # Driver Codeif __name__ == '__main__': # boundary values for window x_wmax = 80 y_wmax = 80 x_wmin = 20 y_wmin = 40 # boundary values for viewport x_vmax = 60 y_vmax = 60 x_vmin = 30 y_vmin = 40 # point on window x_w = 30 y_w = 80 WindowtoViewport(30, 80, 80, 80, 20, 40, 60, 60, 30, 40) # This code is contributed by Surendra_Gangwar",
"e": 6794,
"s": 5742,
"text": null
},
{
"code": "// C# program to implement// Window to ViewPort Transformationusing System; class GFG{ // Function for window to viewport transformationstatic void WindowtoViewport(int x_w, int y_w, int x_wmax, int y_wmax, int x_wmin, int y_wmin, int x_vmax, int y_vmax, int x_vmin, int y_vmin){ // point on viewport int x_v, y_v; // scaling factors for x coordinate // and y coordinate float sx, sy; // calculating Sx and Sy sx = (float)(x_vmax - x_vmin) / (x_wmax - x_wmin); sy = (float)(y_vmax - y_vmin) / (y_wmax - y_wmin); // calculating the point on viewport x_v = (int) (x_vmin + (float)((x_w - x_wmin) * sx)); y_v = (int) (y_vmin + (float)((y_w - y_wmin) * sy)); Console.Write(\"The point on viewport: \" + \"({0}, {1} )\\n \", x_v, y_v);} // Driver Codepublic static void Main(String[] args){ // boundary values for window int x_wmax = 80, y_wmax = 80, x_wmin = 20, y_wmin = 40; // boundary values for viewport int x_vmax = 60, y_vmax = 60, x_vmin = 30, y_vmin = 40; // point on window int x_w = 30, y_w = 80; WindowtoViewport(30, 80, 80, 80, 20, 40, 60, 60, 30, 40);}} // This code is contributed by PrinciRaj1992",
"e": 8168,
"s": 6794,
"text": null
},
{
"code": "<script>// Javascript program to implement// Window to ViewPort Transformation // Function for window to viewport transformationfunction WindowtoViewport(x_w, y_w, x_wmax,y_wmax, x_wmin, y_wmin,x_vmax, y_vmax, x_vmin,y_vmin){ // point on viewport let x_v, y_v; // scaling factors for x coordinate and y coordinate let sx, sy; // calculating Sx and Sy sx = (x_vmax - x_vmin) / (x_wmax - x_wmin); sy = (y_vmax - y_vmin) / (y_wmax - y_wmin); // calculating the point on viewport x_v = x_vmin + ((x_w - x_wmin) * sx); y_v = y_vmin + ((y_w - y_wmin) * sy); document.write(\"The point on viewport: (\" + x_v + \", \" + y_v + \" )<br>\");} // Driver Code // boundary values for window let x_wmax = 80, y_wmax = 80, x_wmin = 20, y_wmin = 40; // boundary values for viewport let x_vmax = 60, y_vmax = 60, x_vmin = 30, y_vmin = 40; // point on window let x_w = 30, y_w = 80; WindowtoViewport(30, 80, 80, 80, 20, 40, 60, 60, 30, 40); </script>",
"e": 9206,
"s": 8168,
"text": null
},
{
"code": null,
"e": 9239,
"s": 9206,
"text": "The point on viewport: (35, 60 )"
},
{
"code": null,
"e": 9249,
"s": 9241,
"text": "soumya7"
},
{
"code": null,
"e": 9262,
"s": 9249,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 9272,
"s": 9262,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 9286,
"s": 9272,
"text": "princiraj1992"
},
{
"code": null,
"e": 9303,
"s": 9286,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 9313,
"s": 9303,
"text": "subham348"
},
{
"code": null,
"e": 9325,
"s": 9313,
"text": "anikaseth98"
},
{
"code": null,
"e": 9342,
"s": 9325,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 9360,
"s": 9342,
"text": "computer-graphics"
},
{
"code": null,
"e": 9370,
"s": 9360,
"text": "Geometric"
},
{
"code": null,
"e": 9383,
"s": 9370,
"text": "Mathematical"
},
{
"code": null,
"e": 9396,
"s": 9383,
"text": "Mathematical"
},
{
"code": null,
"e": 9406,
"s": 9396,
"text": "Geometric"
},
{
"code": null,
"e": 9504,
"s": 9406,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9553,
"s": 9504,
"text": "Program for distance between two points on earth"
},
{
"code": null,
"e": 9606,
"s": 9553,
"text": "Optimum location of point to minimize total distance"
},
{
"code": null,
"e": 9659,
"s": 9606,
"text": "Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping)"
},
{
"code": null,
"e": 9717,
"s": 9659,
"text": "Check whether a given point lies inside a triangle or not"
},
{
"code": null,
"e": 9764,
"s": 9717,
"text": "Program for Point of Intersection of Two Lines"
},
{
"code": null,
"e": 9794,
"s": 9764,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 9837,
"s": 9794,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 9897,
"s": 9837,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 9912,
"s": 9897,
"text": "C++ Data Types"
}
] |
Multiples of 3 and 5 without using % operator in C++
|
We can find the multiples using % operator without any hurdles. But, the problem states that we can't use % operator.
Here, we make use of the + operator. We can get the multiples by adding 3 or 5 to the previous multiple. Let's see an example.
Input
15
Output
1
2
3 - Multiple of 3
4
5 - Multiple of 5
6 - Multiple of 3
7
8
9 - Multiple 3
10 - Multiple of 5
11
12 - Multiple of 3
13
14
15 - Multiple of both 3 and 5
Initialise the number n.
Initialise the number n.
Initialise two number to keep track of next multiple of 3 and 5.
Initialise two number to keep track of next multiple of 3 and 5.
Initially those two numbers will be 3 and 5.
Write a loop that iterates from 1 to n. Both inclusive.Check whether the current number is multiple of 3 or not using the track variably.Similarly check for the multiple of 5.If they are multiple of 3 or 5, add respective number to them to get the next multiple.Print the corresponding text to the console.
Write a loop that iterates from 1 to n. Both inclusive.
Check whether the current number is multiple of 3 or not using the track variably.
Check whether the current number is multiple of 3 or not using the track variably.
Similarly check for the multiple of 5.
Similarly check for the multiple of 5.
If they are multiple of 3 or 5, add respective number to them to get the next multiple.
If they are multiple of 3 or 5, add respective number to them to get the next multiple.
Print the corresponding text to the console.
Print the corresponding text to the console.
Following is the implementation of the above algorithm in C++
#include <bits/stdc++.h>
using namespace std;
void findMultiplesOf3And5(int n) {
int threeMultiple = 3;
int fiveMultiple = 5;
for (int i = 1; i <= n; i++) {
bool _3 = false, _5 = false;
if (i == threeMultiple) {
threeMultiple += 3;
_3 = true;
}
if (i == fiveMultiple) {
fiveMultiple += 5;
_5 = true;
}
if (_3 && _5) {
cout << "Multiple of both 3 and 5" << endl;
}else if (_3) {
cout << "Multiple of 3" << endl;
}else if (_5) {
cout << "Multiple of 5" << endl;
}else {
cout << i << endl;
}
}
}
int main() {
findMultiplesOf3And5(100);
return 0;
}
If you run the above code, then you will get the following result.
1
2
Multiple of 3
4
Multiple of 5
Multiple of 3
7
8
Multiple of 3
Multiple of 5
11
Multiple of 3
13
14
Multiple of both 3 and 5
16
17
Multiple of 3
19
Multiple of 5
Multiple of 3
22
23
Multiple of 3
Multiple of 5
26
Multiple of 3
28
29
Multiple of both 3 and 5
31
32
Multiple of 3
34
Multiple of 5
Multiple of 3
37
38
Multiple of 3
Multiple of 5
41
Multiple of 3
43
44
Multiple of both 3 and 5
46
47
Multiple of 3
49
Multiple of 5
Multiple of 3
52
53
Multiple of 3
Multiple of 5
56
Multiple of 3
58
59
Multiple of both 3 and 5
61
62
Multiple of 3
64
Multiple of 5
Multiple of 3
67
68
Multiple of 3
Multiple of 5
71
Multiple of 3
73
74
Multiple of both 3 and 5
76
77
Multiple of 3
79
Multiple of 5
Multiple of 3
82
83
Multiple of 3
Multiple of 5
86
Multiple of 3
88
89
Multiple of both 3 and 5
91
92
Multiple of 3
94
Multiple of 5
Multiple of 3
97
98
Multiple of 3
Multiple of 5
|
[
{
"code": null,
"e": 1305,
"s": 1187,
"text": "We can find the multiples using % operator without any hurdles. But, the problem states that we can't use % operator."
},
{
"code": null,
"e": 1432,
"s": 1305,
"text": "Here, we make use of the + operator. We can get the multiples by adding 3 or 5 to the previous multiple. Let's see an example."
},
{
"code": null,
"e": 1438,
"s": 1432,
"text": "Input"
},
{
"code": null,
"e": 1441,
"s": 1438,
"text": "15"
},
{
"code": null,
"e": 1448,
"s": 1441,
"text": "Output"
},
{
"code": null,
"e": 1604,
"s": 1448,
"text": "1\n2\n3 - Multiple of 3\n4\n5 - Multiple of 5\n6 - Multiple of 3\n7\n8\n9 - Multiple 3\n10 - Multiple of 5\n11\n12 - Multiple of 3\n13\n14\n15 - Multiple of both 3 and 5"
},
{
"code": null,
"e": 1629,
"s": 1604,
"text": "Initialise the number n."
},
{
"code": null,
"e": 1654,
"s": 1629,
"text": "Initialise the number n."
},
{
"code": null,
"e": 1719,
"s": 1654,
"text": "Initialise two number to keep track of next multiple of 3 and 5."
},
{
"code": null,
"e": 1784,
"s": 1719,
"text": "Initialise two number to keep track of next multiple of 3 and 5."
},
{
"code": null,
"e": 1829,
"s": 1784,
"text": "Initially those two numbers will be 3 and 5."
},
{
"code": null,
"e": 2136,
"s": 1829,
"text": "Write a loop that iterates from 1 to n. Both inclusive.Check whether the current number is multiple of 3 or not using the track variably.Similarly check for the multiple of 5.If they are multiple of 3 or 5, add respective number to them to get the next multiple.Print the corresponding text to the console."
},
{
"code": null,
"e": 2192,
"s": 2136,
"text": "Write a loop that iterates from 1 to n. Both inclusive."
},
{
"code": null,
"e": 2275,
"s": 2192,
"text": "Check whether the current number is multiple of 3 or not using the track variably."
},
{
"code": null,
"e": 2358,
"s": 2275,
"text": "Check whether the current number is multiple of 3 or not using the track variably."
},
{
"code": null,
"e": 2397,
"s": 2358,
"text": "Similarly check for the multiple of 5."
},
{
"code": null,
"e": 2436,
"s": 2397,
"text": "Similarly check for the multiple of 5."
},
{
"code": null,
"e": 2524,
"s": 2436,
"text": "If they are multiple of 3 or 5, add respective number to them to get the next multiple."
},
{
"code": null,
"e": 2612,
"s": 2524,
"text": "If they are multiple of 3 or 5, add respective number to them to get the next multiple."
},
{
"code": null,
"e": 2657,
"s": 2612,
"text": "Print the corresponding text to the console."
},
{
"code": null,
"e": 2702,
"s": 2657,
"text": "Print the corresponding text to the console."
},
{
"code": null,
"e": 2764,
"s": 2702,
"text": "Following is the implementation of the above algorithm in C++"
},
{
"code": null,
"e": 3459,
"s": 2764,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nvoid findMultiplesOf3And5(int n) {\n int threeMultiple = 3;\n int fiveMultiple = 5;\n for (int i = 1; i <= n; i++) {\n bool _3 = false, _5 = false;\n if (i == threeMultiple) {\n threeMultiple += 3;\n _3 = true;\n }\n if (i == fiveMultiple) {\n fiveMultiple += 5;\n _5 = true;\n }\n if (_3 && _5) {\n cout << \"Multiple of both 3 and 5\" << endl;\n }else if (_3) {\n cout << \"Multiple of 3\" << endl;\n }else if (_5) {\n cout << \"Multiple of 5\" << endl;\n }else {\n cout << i << endl;\n }\n }\n}\nint main() {\n findMultiplesOf3And5(100);\n return 0;\n}"
},
{
"code": null,
"e": 3526,
"s": 3459,
"text": "If you run the above code, then you will get the following result."
},
{
"code": null,
"e": 4404,
"s": 3526,
"text": "1\n2\nMultiple of 3\n4\nMultiple of 5\nMultiple of 3\n7\n8\nMultiple of 3\nMultiple of 5\n11\nMultiple of 3\n13\n14\nMultiple of both 3 and 5\n16\n17\nMultiple of 3\n19\nMultiple of 5\nMultiple of 3\n22\n23\nMultiple of 3\nMultiple of 5\n26\nMultiple of 3\n28\n29\nMultiple of both 3 and 5\n31\n32\nMultiple of 3\n34\nMultiple of 5\nMultiple of 3\n37\n38\nMultiple of 3\nMultiple of 5\n41\nMultiple of 3\n43\n44\nMultiple of both 3 and 5\n46\n47\nMultiple of 3\n49\nMultiple of 5\nMultiple of 3\n52\n53\nMultiple of 3\nMultiple of 5\n56\nMultiple of 3\n58\n59\nMultiple of both 3 and 5\n61\n62\nMultiple of 3\n64\nMultiple of 5\nMultiple of 3\n67\n68\nMultiple of 3\nMultiple of 5\n71\nMultiple of 3\n73\n74\nMultiple of both 3 and 5\n76\n77\nMultiple of 3\n79\nMultiple of 5\nMultiple of 3\n82\n83\nMultiple of 3\nMultiple of 5\n86\nMultiple of 3\n88\n89\nMultiple of both 3 and 5\n91\n92\nMultiple of 3\n94\nMultiple of 5\nMultiple of 3\n97\n98\nMultiple of 3\nMultiple of 5"
}
] |
Working with Magic numbers in Linux
|
08 Jul, 2022
This article aims at giving an introduction to magic numbers and file headers, how to extract a file based on magic numbers, and how to corrupt and repair a file based on magic numbers in the Linux environment.
Magic Numbers
Magic numbers are the first few bytes of a file that are unique to a particular file type. These unique bits are referred to as magic numbers, also sometimes referred to as a file signature.
These bytes can be used by the system to “differentiate between and recognize different files” without a file extension.
Locating Magic Numbers in File Signatures
Most files have the signatures in the bytes at the beginning of the file, but some file systems may even have the file signature at offsets other than the beginning. For example, file system ext2/ext3 has bytes 0x53 and 0xEF at the 1080th and 1081st position.
Some files, however, do not have magic numbers, such as plain text files, but can be identified by checking the character set (ASCII in the case of text files).This can be done by using the command:file -i *name_of_file*
file -i *name_of_file*
Magic numbers/File signatures are typically not visible to the user but can be seen by using a hex editor or by using the ‘xxd’ command as mentioned below. These bytes are essential for a file to be opened.
Changing/corrupting these bytes will render the file useless as most tools will not access these files due to potential damaging.
The file command in Linux reader reads the magic numbers of a file and displays the file type based on the magic number.
For example, let us take the example of a PNG file. We can view the hex of a file by typing the following command in a Linux terminal (kali Linux used in this article). This command creates a hexdump of the file we pass to it.xxd image.png | head
xxd image.png | head
This produces the following output:-
In this image, we see that the first set of bytes of the file are
89 50 4e 47 0d 0a 1a 0a
// magic number of PNG file
These numbers help the system identify the type of file being used. Some files that are not written with their extension, are identified with the help of these magic numbers.
An example of a Zip file, Similarly, use the above mentioned command on a zip file.
xxd test.zip | head
In the above image, we can see that the file starts with:
50 4b 03 04
// magic number of zip file
Appending One File to another and identifying the division with Magic numbers
We can use python to perform this operation. Essentially, we will read the bytes of two files, and write them one by one to another empty file. In this article, we will combine a PNG with a Zip file.
"""The first two lines open the two files to be read byte by byteThe third line opens an output file to be written to byte by byte""" input_file_1 = open("image.png", 'rb').read() input_file_2 = open("test.zip", 'rb').read()output_file = open("output.png" , 'wb') output_file.write(input_file_1)output_file.write(input_file_2)
Using this python code, we obtain a file output.png. On running the command:
xxd output.png | head
on this file, we notice that it begins with the same 8950 4e47 0d0a 1a0a hex. However, if we run the command
xxd output.png | grep "PK"
which will search for the magic numbers (PK is the ASCII equivalent of 50 4b) of a zip file amongst the hex,we will get the following output:
In this picture, we can see that the zip file magic numbers are present in the hex of the png, meaning that we have successfully appended the hex of the zip file to that of the png. The next step is to separate this zip file from the png.There is a simple utility, ‘binwalk’ that helps us perform this task easily by typing:
binwalk -e output.png
-e stands for extract
How to use the magic numbers and offsets to extract the zip file from the output :
Find the beginning offset of the file you wish to extract: In this example, we wish to extract the zip file from the PNG. So we first look for the ZIP header. As shown in the previous picture, we carry out the command ‘xxd output.png | grep “PK” ‘. In this picture, we see the offset on the left column. For the zip file, the offset will be 00001c90.Calculate the number of bits from the offset where your file header starts: We must now calculate the number of bits from the offset at which the zip file starts. We can manually count this and observe it to be 00001c95 (each hex value corresponds to 1 bit)Convert this hex value to decimal: This may be done by opening a python IDLE (type ‘python’ in a Linux terminal. We must now convert this value to a decimal. In a python IDLE, we must simply add 0x to the beginning of the value found in the previous step.Use the following command:'dd if=*input file* bs=1 skip=*value
calculated in step 3* of=*output file name*'In the above-mentioned command, ‘if’ stands for the input file, ‘skip’ denotes the number of bits that must be skipped to reach the beginning of the file that we wish to extract, ‘bs’ refers to the number of bytes that must be read at a time, and ‘of’ refers to the output file name.Refer to the picture below to see the usage of steps 3 and 4:File Extraction: We can now open up the present working directory from the terminal to view our extracted zip file by typing:nautilus ./
Find the beginning offset of the file you wish to extract: In this example, we wish to extract the zip file from the PNG. So we first look for the ZIP header. As shown in the previous picture, we carry out the command ‘xxd output.png | grep “PK” ‘. In this picture, we see the offset on the left column. For the zip file, the offset will be 00001c90.
Calculate the number of bits from the offset where your file header starts: We must now calculate the number of bits from the offset at which the zip file starts. We can manually count this and observe it to be 00001c95 (each hex value corresponds to 1 bit)
Convert this hex value to decimal: This may be done by opening a python IDLE (type ‘python’ in a Linux terminal. We must now convert this value to a decimal. In a python IDLE, we must simply add 0x to the beginning of the value found in the previous step.
Use the following command:'dd if=*input file* bs=1 skip=*value
calculated in step 3* of=*output file name*'In the above-mentioned command, ‘if’ stands for the input file, ‘skip’ denotes the number of bits that must be skipped to reach the beginning of the file that we wish to extract, ‘bs’ refers to the number of bytes that must be read at a time, and ‘of’ refers to the output file name.Refer to the picture below to see the usage of steps 3 and 4:
'dd if=*input file* bs=1 skip=*value
calculated in step 3* of=*output file name*'
In the above-mentioned command, ‘if’ stands for the input file, ‘skip’ denotes the number of bits that must be skipped to reach the beginning of the file that we wish to extract, ‘bs’ refers to the number of bytes that must be read at a time, and ‘of’ refers to the output file name.Refer to the picture below to see the usage of steps 3 and 4:
File Extraction: We can now open up the present working directory from the terminal to view our extracted zip file by typing:nautilus ./
nautilus ./
How to corrupt a file by changing its Magic Number?
Changing the magic numbers of a file renders the file useless. We will be showed an error whenever we try to open a file that has a distorted header.
Download hex editor: To corrupt a file, we require a hex editor. hexedit is a popular tool used for the same. You can install it using:sudo apt-get install hexedit
You can open the file by typinghexedit image.png
You will see an output like this:Change the file: To change a byte using hexedit, you simply have to move the cursor over a byte, and type what you would like to. For the sake of this article, I will change the magic numbers from 89 50 to 00 00.To save and exit, press ctrl X and then Y.
Download hex editor: To corrupt a file, we require a hex editor. hexedit is a popular tool used for the same. You can install it using:sudo apt-get install hexedit
You can open the file by typinghexedit image.png
You will see an output like this:
sudo apt-get install hexedit
You can open the file by typing
hexedit image.png
You will see an output like this:
Change the file: To change a byte using hexedit, you simply have to move the cursor over a byte, and type what you would like to. For the sake of this article, I will change the magic numbers from 89 50 to 00 00.To save and exit, press ctrl X and then Y.
In the above picture, we see that the first 2 bytes have been changed to 00 00, and on the right, we can see that the text has changed from .PNG to ..NG
How to repair a file that has a corrupted magic number?
Let us use the example shown in the picture above where I have corrupted the first two bytes of the PNG. If you try to open the PNG now, it will give you an error saying “Could not load file”, not a “PNG”. This is proof that a system looks at the magic number before opening a file. Knowing that the PNG magic numbers start with 89 50, we can change the bytes back to their original value.Let us look at another example, using a jpeg image.Lets first see what a working jpeg hex looks like:
the original magic number bytes are
FF D8 FF E0
A JPEG with corrupted magic bytes would look like this:
We notice that the magic bytes in this are
EE A8 CC 00
And hence the jpg file will not open if you try to open it. We get this error:
A JPG file typically has magic number “FFD8 DDE0”, “FFD8 FFDB” or “FFD8 FFE1”.With this knowledge, all we would have to do is try these combinations as headers for the file. Doing this requires the same process as file corruption.
Open hexeditChange the first few bytes by hovering with cursor and entering the required valuesSave (Ctrl X) and exitTry opening the file. Repeat steps with next possible magic number if the file does not open
Open hexeditChange the first few bytes by hovering with cursor and entering the required valuesSave (Ctrl X) and exitTry opening the file. Repeat steps with next possible magic number if the file does not open
Open hexedit
Change the first few bytes by hovering with cursor and entering the required values
Save (Ctrl X) and exit
Try opening the file. Repeat steps with next possible magic number if the file does not open
On changing the magic bytes to FFD8 FFE0, the picture opens properly.
This article is contributed by Deepak Srivatsav. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
gomathi nataraj
system-programming
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Jul, 2022"
},
{
"code": null,
"e": 239,
"s": 28,
"text": "This article aims at giving an introduction to magic numbers and file headers, how to extract a file based on magic numbers, and how to corrupt and repair a file based on magic numbers in the Linux environment."
},
{
"code": null,
"e": 253,
"s": 239,
"text": "Magic Numbers"
},
{
"code": null,
"e": 446,
"s": 253,
"text": "Magic numbers are the first few bytes of a file that are unique to a particular file type. These unique bits are referred to as magic numbers, also sometimes referred to as a file signature."
},
{
"code": null,
"e": 567,
"s": 446,
"text": "These bytes can be used by the system to “differentiate between and recognize different files” without a file extension."
},
{
"code": null,
"e": 609,
"s": 567,
"text": "Locating Magic Numbers in File Signatures"
},
{
"code": null,
"e": 869,
"s": 609,
"text": "Most files have the signatures in the bytes at the beginning of the file, but some file systems may even have the file signature at offsets other than the beginning. For example, file system ext2/ext3 has bytes 0x53 and 0xEF at the 1080th and 1081st position."
},
{
"code": null,
"e": 1091,
"s": 869,
"text": "Some files, however, do not have magic numbers, such as plain text files, but can be identified by checking the character set (ASCII in the case of text files).This can be done by using the command:file -i *name_of_file*\n"
},
{
"code": null,
"e": 1115,
"s": 1091,
"text": "file -i *name_of_file*\n"
},
{
"code": null,
"e": 1322,
"s": 1115,
"text": "Magic numbers/File signatures are typically not visible to the user but can be seen by using a hex editor or by using the ‘xxd’ command as mentioned below. These bytes are essential for a file to be opened."
},
{
"code": null,
"e": 1452,
"s": 1322,
"text": "Changing/corrupting these bytes will render the file useless as most tools will not access these files due to potential damaging."
},
{
"code": null,
"e": 1573,
"s": 1452,
"text": "The file command in Linux reader reads the magic numbers of a file and displays the file type based on the magic number."
},
{
"code": null,
"e": 1821,
"s": 1573,
"text": "For example, let us take the example of a PNG file. We can view the hex of a file by typing the following command in a Linux terminal (kali Linux used in this article). This command creates a hexdump of the file we pass to it.xxd image.png | head\n"
},
{
"code": null,
"e": 1843,
"s": 1821,
"text": "xxd image.png | head\n"
},
{
"code": null,
"e": 1880,
"s": 1843,
"text": "This produces the following output:-"
},
{
"code": null,
"e": 1946,
"s": 1880,
"text": "In this image, we see that the first set of bytes of the file are"
},
{
"code": null,
"e": 1999,
"s": 1946,
"text": "89 50 4e 47 0d 0a 1a 0a \n// magic number of PNG file"
},
{
"code": null,
"e": 2174,
"s": 1999,
"text": "These numbers help the system identify the type of file being used. Some files that are not written with their extension, are identified with the help of these magic numbers."
},
{
"code": null,
"e": 2258,
"s": 2174,
"text": "An example of a Zip file, Similarly, use the above mentioned command on a zip file."
},
{
"code": null,
"e": 2279,
"s": 2258,
"text": "xxd test.zip | head\n"
},
{
"code": null,
"e": 2337,
"s": 2279,
"text": "In the above image, we can see that the file starts with:"
},
{
"code": null,
"e": 2378,
"s": 2337,
"text": " 50 4b 03 04\n// magic number of zip file"
},
{
"code": null,
"e": 2456,
"s": 2378,
"text": "Appending One File to another and identifying the division with Magic numbers"
},
{
"code": null,
"e": 2656,
"s": 2456,
"text": "We can use python to perform this operation. Essentially, we will read the bytes of two files, and write them one by one to another empty file. In this article, we will combine a PNG with a Zip file."
},
{
"code": "\"\"\"The first two lines open the two files to be read byte by byteThe third line opens an output file to be written to byte by byte\"\"\" input_file_1 = open(\"image.png\", 'rb').read() input_file_2 = open(\"test.zip\", 'rb').read()output_file = open(\"output.png\" , 'wb') output_file.write(input_file_1)output_file.write(input_file_2)",
"e": 2985,
"s": 2656,
"text": null
},
{
"code": null,
"e": 3063,
"s": 2985,
"text": "Using this python code, we obtain a file output.png. On running the command:"
},
{
"code": null,
"e": 3085,
"s": 3063,
"text": "xxd output.png | head"
},
{
"code": null,
"e": 3194,
"s": 3085,
"text": "on this file, we notice that it begins with the same 8950 4e47 0d0a 1a0a hex. However, if we run the command"
},
{
"code": null,
"e": 3221,
"s": 3194,
"text": "xxd output.png | grep \"PK\""
},
{
"code": null,
"e": 3363,
"s": 3221,
"text": "which will search for the magic numbers (PK is the ASCII equivalent of 50 4b) of a zip file amongst the hex,we will get the following output:"
},
{
"code": null,
"e": 3688,
"s": 3363,
"text": "In this picture, we can see that the zip file magic numbers are present in the hex of the png, meaning that we have successfully appended the hex of the zip file to that of the png. The next step is to separate this zip file from the png.There is a simple utility, ‘binwalk’ that helps us perform this task easily by typing:"
},
{
"code": null,
"e": 3733,
"s": 3688,
"text": "binwalk -e output.png\n-e stands for extract\n"
},
{
"code": null,
"e": 3816,
"s": 3733,
"text": "How to use the magic numbers and offsets to extract the zip file from the output :"
},
{
"code": null,
"e": 5267,
"s": 3816,
"text": "Find the beginning offset of the file you wish to extract: In this example, we wish to extract the zip file from the PNG. So we first look for the ZIP header. As shown in the previous picture, we carry out the command ‘xxd output.png | grep “PK” ‘. In this picture, we see the offset on the left column. For the zip file, the offset will be 00001c90.Calculate the number of bits from the offset where your file header starts: We must now calculate the number of bits from the offset at which the zip file starts. We can manually count this and observe it to be 00001c95 (each hex value corresponds to 1 bit)Convert this hex value to decimal: This may be done by opening a python IDLE (type ‘python’ in a Linux terminal. We must now convert this value to a decimal. In a python IDLE, we must simply add 0x to the beginning of the value found in the previous step.Use the following command:'dd if=*input file* bs=1 skip=*value\ncalculated in step 3* of=*output file name*'In the above-mentioned command, ‘if’ stands for the input file, ‘skip’ denotes the number of bits that must be skipped to reach the beginning of the file that we wish to extract, ‘bs’ refers to the number of bytes that must be read at a time, and ‘of’ refers to the output file name.Refer to the picture below to see the usage of steps 3 and 4:File Extraction: We can now open up the present working directory from the terminal to view our extracted zip file by typing:nautilus ./\n"
},
{
"code": null,
"e": 5618,
"s": 5267,
"text": "Find the beginning offset of the file you wish to extract: In this example, we wish to extract the zip file from the PNG. So we first look for the ZIP header. As shown in the previous picture, we carry out the command ‘xxd output.png | grep “PK” ‘. In this picture, we see the offset on the left column. For the zip file, the offset will be 00001c90."
},
{
"code": null,
"e": 5876,
"s": 5618,
"text": "Calculate the number of bits from the offset where your file header starts: We must now calculate the number of bits from the offset at which the zip file starts. We can manually count this and observe it to be 00001c95 (each hex value corresponds to 1 bit)"
},
{
"code": null,
"e": 6132,
"s": 5876,
"text": "Convert this hex value to decimal: This may be done by opening a python IDLE (type ‘python’ in a Linux terminal. We must now convert this value to a decimal. In a python IDLE, we must simply add 0x to the beginning of the value found in the previous step."
},
{
"code": null,
"e": 6584,
"s": 6132,
"text": "Use the following command:'dd if=*input file* bs=1 skip=*value\ncalculated in step 3* of=*output file name*'In the above-mentioned command, ‘if’ stands for the input file, ‘skip’ denotes the number of bits that must be skipped to reach the beginning of the file that we wish to extract, ‘bs’ refers to the number of bytes that must be read at a time, and ‘of’ refers to the output file name.Refer to the picture below to see the usage of steps 3 and 4:"
},
{
"code": null,
"e": 6666,
"s": 6584,
"text": "'dd if=*input file* bs=1 skip=*value\ncalculated in step 3* of=*output file name*'"
},
{
"code": null,
"e": 7011,
"s": 6666,
"text": "In the above-mentioned command, ‘if’ stands for the input file, ‘skip’ denotes the number of bits that must be skipped to reach the beginning of the file that we wish to extract, ‘bs’ refers to the number of bytes that must be read at a time, and ‘of’ refers to the output file name.Refer to the picture below to see the usage of steps 3 and 4:"
},
{
"code": null,
"e": 7149,
"s": 7011,
"text": "File Extraction: We can now open up the present working directory from the terminal to view our extracted zip file by typing:nautilus ./\n"
},
{
"code": null,
"e": 7162,
"s": 7149,
"text": "nautilus ./\n"
},
{
"code": null,
"e": 7214,
"s": 7162,
"text": "How to corrupt a file by changing its Magic Number?"
},
{
"code": null,
"e": 7364,
"s": 7214,
"text": "Changing the magic numbers of a file renders the file useless. We will be showed an error whenever we try to open a file that has a distorted header."
},
{
"code": null,
"e": 7865,
"s": 7364,
"text": "Download hex editor: To corrupt a file, we require a hex editor. hexedit is a popular tool used for the same. You can install it using:sudo apt-get install hexedit\nYou can open the file by typinghexedit image.png\nYou will see an output like this:Change the file: To change a byte using hexedit, you simply have to move the cursor over a byte, and type what you would like to. For the sake of this article, I will change the magic numbers from 89 50 to 00 00.To save and exit, press ctrl X and then Y."
},
{
"code": null,
"e": 8112,
"s": 7865,
"text": "Download hex editor: To corrupt a file, we require a hex editor. hexedit is a popular tool used for the same. You can install it using:sudo apt-get install hexedit\nYou can open the file by typinghexedit image.png\nYou will see an output like this:"
},
{
"code": null,
"e": 8142,
"s": 8112,
"text": "sudo apt-get install hexedit\n"
},
{
"code": null,
"e": 8174,
"s": 8142,
"text": "You can open the file by typing"
},
{
"code": null,
"e": 8193,
"s": 8174,
"text": "hexedit image.png\n"
},
{
"code": null,
"e": 8227,
"s": 8193,
"text": "You will see an output like this:"
},
{
"code": null,
"e": 8482,
"s": 8227,
"text": "Change the file: To change a byte using hexedit, you simply have to move the cursor over a byte, and type what you would like to. For the sake of this article, I will change the magic numbers from 89 50 to 00 00.To save and exit, press ctrl X and then Y."
},
{
"code": null,
"e": 8635,
"s": 8482,
"text": "In the above picture, we see that the first 2 bytes have been changed to 00 00, and on the right, we can see that the text has changed from .PNG to ..NG"
},
{
"code": null,
"e": 8691,
"s": 8635,
"text": "How to repair a file that has a corrupted magic number?"
},
{
"code": null,
"e": 9182,
"s": 8691,
"text": "Let us use the example shown in the picture above where I have corrupted the first two bytes of the PNG. If you try to open the PNG now, it will give you an error saying “Could not load file”, not a “PNG”. This is proof that a system looks at the magic number before opening a file. Knowing that the PNG magic numbers start with 89 50, we can change the bytes back to their original value.Let us look at another example, using a jpeg image.Lets first see what a working jpeg hex looks like:"
},
{
"code": null,
"e": 9218,
"s": 9182,
"text": "the original magic number bytes are"
},
{
"code": null,
"e": 9231,
"s": 9218,
"text": "FF D8 FF E0\n"
},
{
"code": null,
"e": 9287,
"s": 9231,
"text": "A JPEG with corrupted magic bytes would look like this:"
},
{
"code": null,
"e": 9330,
"s": 9287,
"text": "We notice that the magic bytes in this are"
},
{
"code": null,
"e": 9343,
"s": 9330,
"text": "EE A8 CC 00\n"
},
{
"code": null,
"e": 9422,
"s": 9343,
"text": "And hence the jpg file will not open if you try to open it. We get this error:"
},
{
"code": null,
"e": 9653,
"s": 9422,
"text": "A JPG file typically has magic number “FFD8 DDE0”, “FFD8 FFDB” or “FFD8 FFE1”.With this knowledge, all we would have to do is try these combinations as headers for the file. Doing this requires the same process as file corruption."
},
{
"code": null,
"e": 9863,
"s": 9653,
"text": "Open hexeditChange the first few bytes by hovering with cursor and entering the required valuesSave (Ctrl X) and exitTry opening the file. Repeat steps with next possible magic number if the file does not open"
},
{
"code": null,
"e": 10073,
"s": 9863,
"text": "Open hexeditChange the first few bytes by hovering with cursor and entering the required valuesSave (Ctrl X) and exitTry opening the file. Repeat steps with next possible magic number if the file does not open"
},
{
"code": null,
"e": 10086,
"s": 10073,
"text": "Open hexedit"
},
{
"code": null,
"e": 10170,
"s": 10086,
"text": "Change the first few bytes by hovering with cursor and entering the required values"
},
{
"code": null,
"e": 10193,
"s": 10170,
"text": "Save (Ctrl X) and exit"
},
{
"code": null,
"e": 10286,
"s": 10193,
"text": "Try opening the file. Repeat steps with next possible magic number if the file does not open"
},
{
"code": null,
"e": 10356,
"s": 10286,
"text": "On changing the magic bytes to FFD8 FFE0, the picture opens properly."
},
{
"code": null,
"e": 10656,
"s": 10356,
"text": "This article is contributed by Deepak Srivatsav. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 10781,
"s": 10656,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 10797,
"s": 10781,
"text": "gomathi nataraj"
},
{
"code": null,
"e": 10816,
"s": 10797,
"text": "system-programming"
},
{
"code": null,
"e": 10827,
"s": 10816,
"text": "Linux-Unix"
}
] |
Maximum subset with bitwise OR equal to k
|
24 May, 2021
Given an array of non-negative integers and an integer k, find the subset of maximum length with bitwise OR equal to k.
Examples:
Input : arr[] = [1, 4, 2]
k = 3
Output : [1, 2]
Explanation: The bitwise OR of
1 and 2 equals 3. It is not possible to obtain
a subset of length greater than 2.
Input : arr[] = [1, 2, 5]
k = 4
Output : []
No subset's bitwise OR equals 4.
Method 1(Simple): The naive method would be to consider all the subsets. While considering a subset, compute its bitwise OR. If it equals k, compare the subset’s length with the maximum length so far and update the maximum length if required.
Method 2(Efficient): 0 OR 0 = 0 1 OR 0 = 1 1 OR 1 = 1 Hence, for all the positions in the binary representation of k with the bit equal to 0, the corresponding position in the binary representations of all the elements in the resulting subset should necessarily be 0. On the other hand, for positions in k with the bit equal to 1, there has to be at least one element with a 1 in the corresponding position. The rest of the elements can have either 0 or 1 in that position. It does not matter. Therefore, to obtain the resulting subset, traverse the initial array. While deciding if the element should be in the resulting subset or not, check whether there is any position in the binary representation of k which is 0 and the corresponding position in that element is 1. If there exists such a position, then ignore that element, else include it in the resulting subset.How to determine if there exists a position in the binary representation of k which is 0 and the corresponding position in an element is 1? Simply take the bitwise OR of k and that element. If it does not equal to k, then there exists such a position and the element has to be ignored. If their bitwise OR equals k, then include the current element in the resulting subset.The final step is to determine if there is at least one element with a 1 in a position with 1 in the corresponding position in k. Simply compute the bitwise OR of the resulting subset. If it equals k, then this is the final answer. Else no subset exists which satisfies the condition.
C++
Java
Python3
C#
PHP
Javascript
// CPP Program to find the maximum subset// with bitwise OR equal to k#include <bits/stdc++.h>using namespace std; // function to find the maximum subset with// bitwise OR equal to kvoid subsetBitwiseORk(int arr[], int n, int k){ vector<int> v; for (int i = 0; i < n; i++) { // If the bitwise OR of k and element // is equal to k, then include that element // in the subset if ((arr[i] | k) == k) v.push_back(arr[i]); } // Store the bitwise OR of elements in v int ans = 0; for (int i = 0; i < v.size(); i++) ans |= v[i]; // If ans is not equal to k, subset doesn't exist if (ans != k) { cout << "Subset does not exist" << endl; return; } for (int i = 0; i < v.size(); i++) cout << v[i] << ' ';} // Driver Codeint main(){ int k = 3; int arr[] = { 1, 4, 2 }; int n = sizeof(arr) / sizeof(arr[0]); subsetBitwiseORk(arr, n, k); return 0;}
// Java Program to find the maximum subset// with bitwise OR equal to kimport java.util.*; class GFG { // function to find the maximum subset // with bitwise OR equal to k static void subsetBitwiseORk(int arr[], int n, int k) { ArrayList<Integer> v = new ArrayList<Integer>(); for (int i = 0; i < n; i++) { // If the bitwise OR of k and // element is equal to k, then // include that element in the // subset if ((arr[i] | k) == k){ v.add(arr[i]); } } // Store the bitwise OR of elements // in v int ans = 0; for (int i = 0; i < v.size(); i++) ans = ans|v.get(i); // If ans is not equal to k, subset // doesn't exist if (ans != k) { System.out.println("Subset does" + " not exist" ); return; } for (int i = 0; i < v.size(); i++) System.out.print(v.get(i) + " " ); } // main function public static void main(String[] args) { int k = 3; int arr[] = { 1, 4, 2 }; int n = arr.length; subsetBitwiseORk(arr, n, k); }} // This code is contributed by Arnab Kundu.
# Python3 Program to find the# maximum subset with bitwise# OR equal to k # function to find the maximum# subset with bitwise OR equal to kdef subsetBitwiseORk(arr, n, k) : v = [] for i in range(0, n) : # If the bitwise OR of k # and element is equal to k, # then include that element # in the subset if ((arr[i] | k) == k) : v.append(arr[i]) # Store the bitwise OR # of elements in v ans = 0 for i in range(0, len(v)) : ans |= v[i] # If ans is not equal to # k, subset doesn't exist if (ans != k) : print ("Subset does not exist\n") return for i in range(0, len(v)) : print ("{} ".format(v[i]), end="") # Driver Codek = 3arr = [1, 4, 2]n = len(arr) subsetBitwiseORk(arr, n, k) # This code is contributed by# Manish Shaw(manishshaw1)
// C# Program to find the maximum subset// with bitwise OR equal to kusing System;using System.Collections; class GFG { // function to find the maximum subset // with bitwise OR equal to k static void subsetBitwiseORk(int []arr, int n, int k) { ArrayList v = new ArrayList(); for (int i = 0; i < n; i++) { // If the bitwise OR of k and // element is equal to k, then // include that element in the // subset if ((arr[i] | k) == k){ v.Add(arr[i]); } } // Store the bitwise OR of // elements in v int ans = 0; for (int i = 0; i < v.Count; i++) ans = ans|(int)v[i]; // If ans is not equal to k, subset // doesn't exist if (ans != k) { Console.WriteLine("Subset does" + " not exist" ); return; } for (int i = 0; i < v.Count; i++) Console.Write((int)v[i] + " " ); } // main function static public void Main(String []args) { int k = 3; int []arr = { 1, 4, 2 }; int n = arr.Length; subsetBitwiseORk(arr, n, k); }} // This code is contributed by Arnab Kundu
<?php// PHP Program to find the// maximum subset with bitwise// OR equal to k // function to find the maximum// subset with bitwise OR equal to kfunction subsetBitwiseORk($arr, $n, $k){ $v = array(); for ($i = 0; $i < $n; $i++) { // If the bitwise OR of k // and element is equal to k, // then include that element // in the subset if (($arr[$i] | $k) == $k) array_push($v, $arr[$i]); } // Store the bitwise OR // of elements in v $ans = 0; for ($i = 0; $i < count($v); $i++) $ans |= $v[$i]; // If ans is not equal to // k, subset doesn't exist if ($ans != $k) { echo ("Subset does not exist\n"); return; } for ($i = 0; $i < count($v); $i++) echo ($v[$i]." ");} // Driver Code$k = 3;$arr = array(1, 4, 2);$n = count($arr); subsetBitwiseORk($arr, $n, $k); // This code is contributed by// Manish Shaw(manishshaw1)?>
<script> // Javascript Program to find the maximum subset// with bitwise OR equal to k // function to find the maximum subset with// bitwise OR equal to kfunction subsetBitwiseORk(arr, n, k){ var v = []; for (var i = 0; i < n; i++) { // If the bitwise OR of k and element // is equal to k, then include that element // in the subset if ((arr[i] | k) == k) v.push(arr[i]); } // Store the bitwise OR of elements in v var ans = 0; for (var i = 0; i < v.length; i++) ans |= v[i]; // If ans is not equal to k, subset doesn't exist if (ans != k) { document.write( "Subset does not exist" ); return; } for (var i = 0; i < v.length; i++) document.write( v[i] + ' ');} // Driver Codevar k = 3;var arr = [1, 4, 2];var n = arr.length;subsetBitwiseORk(arr, n, k); </script>
Output :
1 2
Time complexity: O(N), where N is the size of the array.
andrew1234
manishshaw1
famously
Bitwise-OR
subset
Bit Magic
Bit Magic
subset
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Set, Clear and Toggle a given bit of a number in C
Find two numbers from their sum and XOR
Builtin functions of GCC compiler
Find a number X such that (X XOR A) is minimum and the count of set bits in X and B are equal
Calculate XOR from 1 to n.
Equal Sum and XOR of three Numbers
Calculate square of a number without using *, / and pow()
Reverse actual bits of the given number
Unique element in an array where all elements occur k times except one
Find XOR of two number without using XOR operator
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n24 May, 2021"
},
{
"code": null,
"e": 174,
"s": 54,
"text": "Given an array of non-negative integers and an integer k, find the subset of maximum length with bitwise OR equal to k."
},
{
"code": null,
"e": 186,
"s": 174,
"text": "Examples: "
},
{
"code": null,
"e": 444,
"s": 186,
"text": "Input : arr[] = [1, 4, 2]\n k = 3\nOutput : [1, 2]\nExplanation: The bitwise OR of \n1 and 2 equals 3. It is not possible to obtain \na subset of length greater than 2.\n\nInput : arr[] = [1, 2, 5]\n k = 4\nOutput : []\nNo subset's bitwise OR equals 4. "
},
{
"code": null,
"e": 687,
"s": 444,
"text": "Method 1(Simple): The naive method would be to consider all the subsets. While considering a subset, compute its bitwise OR. If it equals k, compare the subset’s length with the maximum length so far and update the maximum length if required."
},
{
"code": null,
"e": 2217,
"s": 687,
"text": "Method 2(Efficient): 0 OR 0 = 0 1 OR 0 = 1 1 OR 1 = 1 Hence, for all the positions in the binary representation of k with the bit equal to 0, the corresponding position in the binary representations of all the elements in the resulting subset should necessarily be 0. On the other hand, for positions in k with the bit equal to 1, there has to be at least one element with a 1 in the corresponding position. The rest of the elements can have either 0 or 1 in that position. It does not matter. Therefore, to obtain the resulting subset, traverse the initial array. While deciding if the element should be in the resulting subset or not, check whether there is any position in the binary representation of k which is 0 and the corresponding position in that element is 1. If there exists such a position, then ignore that element, else include it in the resulting subset.How to determine if there exists a position in the binary representation of k which is 0 and the corresponding position in an element is 1? Simply take the bitwise OR of k and that element. If it does not equal to k, then there exists such a position and the element has to be ignored. If their bitwise OR equals k, then include the current element in the resulting subset.The final step is to determine if there is at least one element with a 1 in a position with 1 in the corresponding position in k. Simply compute the bitwise OR of the resulting subset. If it equals k, then this is the final answer. Else no subset exists which satisfies the condition. "
},
{
"code": null,
"e": 2221,
"s": 2217,
"text": "C++"
},
{
"code": null,
"e": 2226,
"s": 2221,
"text": "Java"
},
{
"code": null,
"e": 2234,
"s": 2226,
"text": "Python3"
},
{
"code": null,
"e": 2237,
"s": 2234,
"text": "C#"
},
{
"code": null,
"e": 2241,
"s": 2237,
"text": "PHP"
},
{
"code": null,
"e": 2252,
"s": 2241,
"text": "Javascript"
},
{
"code": "// CPP Program to find the maximum subset// with bitwise OR equal to k#include <bits/stdc++.h>using namespace std; // function to find the maximum subset with// bitwise OR equal to kvoid subsetBitwiseORk(int arr[], int n, int k){ vector<int> v; for (int i = 0; i < n; i++) { // If the bitwise OR of k and element // is equal to k, then include that element // in the subset if ((arr[i] | k) == k) v.push_back(arr[i]); } // Store the bitwise OR of elements in v int ans = 0; for (int i = 0; i < v.size(); i++) ans |= v[i]; // If ans is not equal to k, subset doesn't exist if (ans != k) { cout << \"Subset does not exist\" << endl; return; } for (int i = 0; i < v.size(); i++) cout << v[i] << ' ';} // Driver Codeint main(){ int k = 3; int arr[] = { 1, 4, 2 }; int n = sizeof(arr) / sizeof(arr[0]); subsetBitwiseORk(arr, n, k); return 0;}",
"e": 3207,
"s": 2252,
"text": null
},
{
"code": "// Java Program to find the maximum subset// with bitwise OR equal to kimport java.util.*; class GFG { // function to find the maximum subset // with bitwise OR equal to k static void subsetBitwiseORk(int arr[], int n, int k) { ArrayList<Integer> v = new ArrayList<Integer>(); for (int i = 0; i < n; i++) { // If the bitwise OR of k and // element is equal to k, then // include that element in the // subset if ((arr[i] | k) == k){ v.add(arr[i]); } } // Store the bitwise OR of elements // in v int ans = 0; for (int i = 0; i < v.size(); i++) ans = ans|v.get(i); // If ans is not equal to k, subset // doesn't exist if (ans != k) { System.out.println(\"Subset does\" + \" not exist\" ); return; } for (int i = 0; i < v.size(); i++) System.out.print(v.get(i) + \" \" ); } // main function public static void main(String[] args) { int k = 3; int arr[] = { 1, 4, 2 }; int n = arr.length; subsetBitwiseORk(arr, n, k); }} // This code is contributed by Arnab Kundu.",
"e": 4549,
"s": 3207,
"text": null
},
{
"code": "# Python3 Program to find the# maximum subset with bitwise# OR equal to k # function to find the maximum# subset with bitwise OR equal to kdef subsetBitwiseORk(arr, n, k) : v = [] for i in range(0, n) : # If the bitwise OR of k # and element is equal to k, # then include that element # in the subset if ((arr[i] | k) == k) : v.append(arr[i]) # Store the bitwise OR # of elements in v ans = 0 for i in range(0, len(v)) : ans |= v[i] # If ans is not equal to # k, subset doesn't exist if (ans != k) : print (\"Subset does not exist\\n\") return for i in range(0, len(v)) : print (\"{} \".format(v[i]), end=\"\") # Driver Codek = 3arr = [1, 4, 2]n = len(arr) subsetBitwiseORk(arr, n, k) # This code is contributed by# Manish Shaw(manishshaw1)",
"e": 5410,
"s": 4549,
"text": null
},
{
"code": "// C# Program to find the maximum subset// with bitwise OR equal to kusing System;using System.Collections; class GFG { // function to find the maximum subset // with bitwise OR equal to k static void subsetBitwiseORk(int []arr, int n, int k) { ArrayList v = new ArrayList(); for (int i = 0; i < n; i++) { // If the bitwise OR of k and // element is equal to k, then // include that element in the // subset if ((arr[i] | k) == k){ v.Add(arr[i]); } } // Store the bitwise OR of // elements in v int ans = 0; for (int i = 0; i < v.Count; i++) ans = ans|(int)v[i]; // If ans is not equal to k, subset // doesn't exist if (ans != k) { Console.WriteLine(\"Subset does\" + \" not exist\" ); return; } for (int i = 0; i < v.Count; i++) Console.Write((int)v[i] + \" \" ); } // main function static public void Main(String []args) { int k = 3; int []arr = { 1, 4, 2 }; int n = arr.Length; subsetBitwiseORk(arr, n, k); }} // This code is contributed by Arnab Kundu",
"e": 6728,
"s": 5410,
"text": null
},
{
"code": "<?php// PHP Program to find the// maximum subset with bitwise// OR equal to k // function to find the maximum// subset with bitwise OR equal to kfunction subsetBitwiseORk($arr, $n, $k){ $v = array(); for ($i = 0; $i < $n; $i++) { // If the bitwise OR of k // and element is equal to k, // then include that element // in the subset if (($arr[$i] | $k) == $k) array_push($v, $arr[$i]); } // Store the bitwise OR // of elements in v $ans = 0; for ($i = 0; $i < count($v); $i++) $ans |= $v[$i]; // If ans is not equal to // k, subset doesn't exist if ($ans != $k) { echo (\"Subset does not exist\\n\"); return; } for ($i = 0; $i < count($v); $i++) echo ($v[$i].\" \");} // Driver Code$k = 3;$arr = array(1, 4, 2);$n = count($arr); subsetBitwiseORk($arr, $n, $k); // This code is contributed by// Manish Shaw(manishshaw1)?>",
"e": 7665,
"s": 6728,
"text": null
},
{
"code": "<script> // Javascript Program to find the maximum subset// with bitwise OR equal to k // function to find the maximum subset with// bitwise OR equal to kfunction subsetBitwiseORk(arr, n, k){ var v = []; for (var i = 0; i < n; i++) { // If the bitwise OR of k and element // is equal to k, then include that element // in the subset if ((arr[i] | k) == k) v.push(arr[i]); } // Store the bitwise OR of elements in v var ans = 0; for (var i = 0; i < v.length; i++) ans |= v[i]; // If ans is not equal to k, subset doesn't exist if (ans != k) { document.write( \"Subset does not exist\" ); return; } for (var i = 0; i < v.length; i++) document.write( v[i] + ' ');} // Driver Codevar k = 3;var arr = [1, 4, 2];var n = arr.length;subsetBitwiseORk(arr, n, k); </script>",
"e": 8530,
"s": 7665,
"text": null
},
{
"code": null,
"e": 8541,
"s": 8530,
"text": "Output : "
},
{
"code": null,
"e": 8545,
"s": 8541,
"text": "1 2"
},
{
"code": null,
"e": 8603,
"s": 8545,
"text": "Time complexity: O(N), where N is the size of the array. "
},
{
"code": null,
"e": 8614,
"s": 8603,
"text": "andrew1234"
},
{
"code": null,
"e": 8626,
"s": 8614,
"text": "manishshaw1"
},
{
"code": null,
"e": 8635,
"s": 8626,
"text": "famously"
},
{
"code": null,
"e": 8646,
"s": 8635,
"text": "Bitwise-OR"
},
{
"code": null,
"e": 8653,
"s": 8646,
"text": "subset"
},
{
"code": null,
"e": 8663,
"s": 8653,
"text": "Bit Magic"
},
{
"code": null,
"e": 8673,
"s": 8663,
"text": "Bit Magic"
},
{
"code": null,
"e": 8680,
"s": 8673,
"text": "subset"
},
{
"code": null,
"e": 8778,
"s": 8680,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8829,
"s": 8778,
"text": "Set, Clear and Toggle a given bit of a number in C"
},
{
"code": null,
"e": 8869,
"s": 8829,
"text": "Find two numbers from their sum and XOR"
},
{
"code": null,
"e": 8903,
"s": 8869,
"text": "Builtin functions of GCC compiler"
},
{
"code": null,
"e": 8997,
"s": 8903,
"text": "Find a number X such that (X XOR A) is minimum and the count of set bits in X and B are equal"
},
{
"code": null,
"e": 9024,
"s": 8997,
"text": "Calculate XOR from 1 to n."
},
{
"code": null,
"e": 9059,
"s": 9024,
"text": "Equal Sum and XOR of three Numbers"
},
{
"code": null,
"e": 9117,
"s": 9059,
"text": "Calculate square of a number without using *, / and pow()"
},
{
"code": null,
"e": 9157,
"s": 9117,
"text": "Reverse actual bits of the given number"
},
{
"code": null,
"e": 9228,
"s": 9157,
"text": "Unique element in an array where all elements occur k times except one"
}
] |
Python program to display Astrological sign or Zodiac sign for a given data of birth.
|
Given date of birth, our task is to display astrological sign or Zodiac sign.
Input : Day = 13, Month = November
Output : Scorpio.
Step 1 : input date of birth.
Step 2 : checks month and date within the valid range of a specified zodiac.
Step 3 : display zodiac sign.
def zodiac_sign(day, month):
# checks month and date within the valid range
# of a specified zodiac
if month == 'december':
astro_sign = 'Sagittarius' if (day < 22) else 'capricorn'
elif month == 'january':
astro_sign = 'Capricorn' if (day < 20) else 'aquarius'
elif month == 'february':
astro_sign = 'Aquarius' if (day < 19) else 'pisces'
elif month == 'march':
astro_sign = 'Pisces' if (day < 21) else 'aries'
elif month == 'april':
astro_sign = 'Aries' if (day < 20) else 'taurus'
elif month == 'may':
astro_sign = 'Taurus' if (day < 21) else 'gemini'
elif month == 'june':
astro_sign = 'Gemini' if (day < 21) else 'cancer'
elif month == 'july':
astro_sign = 'Cancer' if (day < 23) else 'leo'
elif month == 'august':
astro_sign = 'Leo' if (day < 23) else 'virgo'
elif month == 'september':
astro_sign = 'Virgo' if (day < 23) else 'libra'
elif month == 'october':
astro_sign = 'Libra' if (day < 23) else 'scorpio'
elif month == 'november':
astro_sign = 'scorpio' if (day < 22) else 'sagittarius'
print(astro_sign)
# Driver code
if __name__ == '__main__':
d = int(input("Enter Day ::>"))
m = input("Enter the Month ::>")
zodiac_sign(d, m)
Enter Day ::>13
Enter the Month ::>november
scorpio
|
[
{
"code": null,
"e": 1265,
"s": 1187,
"text": "Given date of birth, our task is to display astrological sign or Zodiac sign."
},
{
"code": null,
"e": 1318,
"s": 1265,
"text": "Input : Day = 13, Month = November\nOutput : Scorpio."
},
{
"code": null,
"e": 1455,
"s": 1318,
"text": "Step 1 : input date of birth.\nStep 2 : checks month and date within the valid range of a specified zodiac.\nStep 3 : display zodiac sign."
},
{
"code": null,
"e": 2713,
"s": 1455,
"text": "def zodiac_sign(day, month):\n # checks month and date within the valid range\n # of a specified zodiac\n if month == 'december':\n astro_sign = 'Sagittarius' if (day < 22) else 'capricorn'\n elif month == 'january':\n astro_sign = 'Capricorn' if (day < 20) else 'aquarius'\n elif month == 'february':\n astro_sign = 'Aquarius' if (day < 19) else 'pisces'\n elif month == 'march':\n astro_sign = 'Pisces' if (day < 21) else 'aries'\n elif month == 'april':\n astro_sign = 'Aries' if (day < 20) else 'taurus'\n elif month == 'may':\n astro_sign = 'Taurus' if (day < 21) else 'gemini'\n elif month == 'june':\n astro_sign = 'Gemini' if (day < 21) else 'cancer'\n elif month == 'july':\n astro_sign = 'Cancer' if (day < 23) else 'leo'\n elif month == 'august':\n astro_sign = 'Leo' if (day < 23) else 'virgo'\n elif month == 'september':\n astro_sign = 'Virgo' if (day < 23) else 'libra'\n elif month == 'october':\n astro_sign = 'Libra' if (day < 23) else 'scorpio'\n elif month == 'november':\n astro_sign = 'scorpio' if (day < 22) else 'sagittarius'\n print(astro_sign)\n\n# Driver code\nif __name__ == '__main__':\nd = int(input(\"Enter Day ::>\"))\nm = input(\"Enter the Month ::>\")\nzodiac_sign(d, m)"
},
{
"code": null,
"e": 2765,
"s": 2713,
"text": "Enter Day ::>13\nEnter the Month ::>november\nscorpio"
}
] |
All Pair Testing
|
All-pairs also known as pairwise testing is a testing approach taken for testing the software using combinatorial method. It's a method to test all the possible discrete combinations of the parameters involved.
Assume we have a piece of software to be tested which has got 10 input fields and 10 possible settings for each input field. Then, there are 10^10 possible inputs to be tested. In this case, exhaustive testing is impossible even if we wish to test all combinations.
Let us also understand the concept of All-pairs testing by taking an example.
An application with simple list box with 10 elements (Let's say 0,1,2,3,4,5,6,7,8,9) along with a checkbox, radio button, Text Box and OK Button. The Constraint for the Text box is it can accept values only between 1 and 100. Below are the values that each one of the GUI objects can take:
List Box - 0,1,2,3,4,5,6,7,8,9
Check Box - Checked or Unchecked
Radio Button - ON or OFF
Text Box - Any Value between 1 and 100
Exhaustive combination of the application is calculated.
List Box = 10
Check Box = 2
Radio Button = 2
Text Box = 100
Total Number of Test Cases using Cartesian Method : 10*2*2*100 = 4000
Total Number of Test Cases including Negative Cases will be > 4000
Now, the idea is to bring down the number of test cases. We will first try to find out the number of cases using the conventional software testing technique. We can consider the list box values as 0 and others as 0 is neither positive nor negative. Radio button and check box values cannot be reduced. So each one of them will have 2 combinations (ON or OFF). The Text box values can be reduced into three inputs (Valid Integer, Invalid Integer, Alpha-Special Character).
Now, we will calculate the number of cases using software testing technique is 2*2*2*3 = 24 (including negative cases).
Now, we can still reduce the combination further into All-pairs technique.
Step 1 : Order the values such that one with most number of values is the first and the least is placed as the last variable.
Step 2 : Now, start filling the table column by column. List box can take 2 values.
Step 3 : The next column under discussion would be check box. Again, Check box can take 2 values.
Step 4 : Now, we need to ensure that we cover all combinations between list box and Check box.
Step 5 : Now, we will use the same strategy for checking the Radio Button. It can take 2 values.
Step 6 : Verify if all the pair values are covered as shown in the table below.
Exhaustive Combination results in > 4000 Test Cases.
Conventional Software Testing technique results in 24 Test Cases.
Pair Wise Software Testing technique results in just 6 Test Cases.
|
[
{
"code": null,
"e": 6090,
"s": 5879,
"text": "All-pairs also known as pairwise testing is a testing approach taken for testing the software using combinatorial method. It's a method to test all the possible discrete combinations of the parameters involved."
},
{
"code": null,
"e": 6356,
"s": 6090,
"text": "Assume we have a piece of software to be tested which has got 10 input fields and 10 possible settings for each input field. Then, there are 10^10 possible inputs to be tested. In this case, exhaustive testing is impossible even if we wish to test all combinations."
},
{
"code": null,
"e": 6434,
"s": 6356,
"text": "Let us also understand the concept of All-pairs testing by taking an example."
},
{
"code": null,
"e": 6724,
"s": 6434,
"text": "An application with simple list box with 10 elements (Let's say 0,1,2,3,4,5,6,7,8,9) along with a checkbox, radio button, Text Box and OK Button. The Constraint for the Text box is it can accept values only between 1 and 100. Below are the values that each one of the GUI objects can take:"
},
{
"code": null,
"e": 6756,
"s": 6724,
"text": "List Box - 0,1,2,3,4,5,6,7,8,9"
},
{
"code": null,
"e": 6789,
"s": 6756,
"text": "Check Box - Checked or Unchecked"
},
{
"code": null,
"e": 6814,
"s": 6789,
"text": "Radio Button - ON or OFF"
},
{
"code": null,
"e": 6853,
"s": 6814,
"text": "Text Box - Any Value between 1 and 100"
},
{
"code": null,
"e": 6910,
"s": 6853,
"text": "Exhaustive combination of the application is calculated."
},
{
"code": null,
"e": 7108,
"s": 6910,
"text": "List Box = 10\nCheck Box = 2\nRadio Button = 2\nText Box = 100\n\nTotal Number of Test Cases using Cartesian Method : 10*2*2*100 = 4000\nTotal Number of Test Cases including Negative Cases will be > 4000"
},
{
"code": null,
"e": 7580,
"s": 7108,
"text": "Now, the idea is to bring down the number of test cases. We will first try to find out the number of cases using the conventional software testing technique. We can consider the list box values as 0 and others as 0 is neither positive nor negative. Radio button and check box values cannot be reduced. So each one of them will have 2 combinations (ON or OFF). The Text box values can be reduced into three inputs (Valid Integer, Invalid Integer, Alpha-Special Character)."
},
{
"code": null,
"e": 7700,
"s": 7580,
"text": "Now, we will calculate the number of cases using software testing technique is 2*2*2*3 = 24 (including negative cases)."
},
{
"code": null,
"e": 7775,
"s": 7700,
"text": "Now, we can still reduce the combination further into All-pairs technique."
},
{
"code": null,
"e": 7902,
"s": 7775,
"text": "Step 1 : Order the values such that one with most number of values is the first and the least is placed as the last variable.\n"
},
{
"code": null,
"e": 7986,
"s": 7902,
"text": "Step 2 : Now, start filling the table column by column. List box can take 2 values."
},
{
"code": null,
"e": 8084,
"s": 7986,
"text": "Step 3 : The next column under discussion would be check box. Again, Check box can take 2 values."
},
{
"code": null,
"e": 8179,
"s": 8084,
"text": "Step 4 : Now, we need to ensure that we cover all combinations between list box and Check box."
},
{
"code": null,
"e": 8276,
"s": 8179,
"text": "Step 5 : Now, we will use the same strategy for checking the Radio Button. It can take 2 values."
},
{
"code": null,
"e": 8356,
"s": 8276,
"text": "Step 6 : Verify if all the pair values are covered as shown in the table below."
}
] |
Designing Deterministic Finite Automata (Set 2)
|
28 Jun, 2020
Prerequisite – Designing finite automata, previous article: Designing Deterministic Finite Automata (Set 1)In this article, we will see some designing of Deterministic Finite Automata (DFA).
Problem-1: Construction of a DFA for the set of string over {a, b} such that length of the string |w| is divisible by 2 i.e, |w| mod 2 = 0.
Explanation – The desired language will be like:
L = {?, aa, ab, ba, bb, aaaa, bbbb, ............}
The state transition diagram of the language will be like:
Here, state A represent set of all string of length even (0, 2, 4, ...), and state B represent set of all string of length odd (1, 3, 5, ...).
Number of states: n
If |W| mod n = 0
def stateA(n): if(len(n)==0): print("Accepted") else: #on any input call function stateB if (n[0]=='0' or n[0]=='1'): stateB(n[1:]) def stateB(n): if(len(n)==0): print("Not Accepted") else: #on any input call function stateA if (n[0]=='0' or n[0]=='1'): stateA(n[1:]) #take inputn=input() #call stateA#to check the inputstateA(n)
The above automata will accept all the strings having the length of the string divisible by 2. When the length of the string is 1, then it will go from state A to B. When the length of the string is 2, then it will go from state B to A and so on. State A is the final state i.e, it accept all the string having length divisible by 2.
Problem-2: Construction of a DFA for the set of string over {a, b} such that length of the string |w| is not divisible by 2 i.e, |w| mod 2 = 1.
Explanation – The desired language will be like:
L = {a, b, aaa, aab, aba, abb, aaaaa, bbbb, .......}
The state transition diagram of the language will be like:
Here, state A represent set of all string of length even (0, 2, 4, ...), and state B represent set of all string of length odd (1, 3, 5, ...).
def stateA(n): if(len(n)==0): print("Not Accepted") else: #on any input call function stateB if (n[0]=='0' or n[0]=='1'): stateB(n[1:]) def stateB(n): if(len(n)==0): print("Accepted") else: #on any input call function stateA if (n[0]=='0' or n[0]=='1'): stateA(n[1:]) #take inputn=input() #call stateA#to check the inputstateA(n)
The above automata will accept all the strings having the length of the string not divisible by 2. When the length of the string is 1, then it will go from state A to B. When the length of the string is 2, then it will go from state B to A and so on. State B is the final state i.e, it accept all the string having length not divisible by 2.
Problem-3: Construction of a DFA for the set of string over {a, b} such that length of the string |w| is divisible by 3 i.e, |w| mod 3 = 0.
Explanation – The desired language will be like:
L = {?, aaa, aab, aba, abb, aaaaaa, bbbbbb, .......}
The state transition diagram of the language will be like:
Here, state A represents set for which string’s length divided by 3 then remainder is zero (0), state B represents set for which string’s length divided by 3 then the remainder is one (1), and state C represents set for which string’s length divided by 3 then the remainder is two (2).
Number of states: n
If |W| mod n = 0
def stateA(n): if(len(n)==0): print("Accepted") else: #on any input call function stateB if (n[0]=='0' or n[0]=='1'): stateB(n[1:]) def stateB(n): if(len(n)==0): print("Not Accepted") else: #on any input call function stateC if (n[0]=='0' or n[0]=='1'): stateC(n[1:]) def stateC(n): if(len(n)==0): print("Not Accepted") else: #on any input call function stateA if (n[0]=='0' or n[0]=='1'): stateA(n[1:]) #take inputn=input() #call stateA#to check the inputstateA(n)
The above automata will accept all the strings having the length of the string divisible by 3. When the length of the string is 1, then it will go from state A to B. When the length of the string is 2, then it will go from state B to C and When the length of the string is 3, then it will go from state C to A (final state). State A is the final state i.e, it accepts all the string having the length divisible by 3.
Problem-4: Construction of a DFA for the set of string over {a, b} such that length of the string |w| is not divisible by 3 i.e, |w| mod 3 = 1.
Explanation – The desired language will be like:
L = {a, b, aa, ab, ba, bb, aaaa, bbbb, ........}
The state transition diagram of the language will be like:
Here, state A represents set for which string’s length divided by 3 then remainder is zero (0), state B represents set for which string’s length divided by 3 then the remainder is one (1), and state C represents set for which string’s length divided by 3 then the remainder is two (2).
def stateA(n): if(len(n)==0): print("Not Accepted") else: #on any input call function stateB if (n[0]=='0' or n[0]=='1'): stateB(n[1:]) def stateB(n): if(len(n)==0): print("Accepted") else: #on any input call function stateC if (n[0]=='0' or n[0]=='1'): stateC(n[1:]) def stateC(n): if(len(n)==0): print("Not Accepted") else: #on any input call function stateA if (n[0]=='0' or n[0]=='1'): stateA(n[1:]) #take inputn=input() #call stateA#to check the inputstateA(n)
The above automata will accept all the strings having the length of the string not divisible by 3. When the length of the string is 1, then it will go from state A to B. When the length of the string is 2, then it will go from state B to C and When the length of the string is 3, then it will go from state C to A. State B and C are the final state i.e, it accepts all the string having the length not divisible by 3.
_mridul_bhardwaj_
GATE CS
Theory of Computation & Automata
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Mutual exclusion in distributed system
Three address code in Compiler
S - attributed and L - attributed SDTs in Syntax directed translation
Types of Operating Systems
Code Optimization in Compiler Design
Difference between DFA and NFA
Removal of ambiguity (Converting an Ambiguous grammar into Unambiguous grammar)
Post Correspondence Problem
Church’s Thesis for Turing Machine
Variation of Turing Machine
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n28 Jun, 2020"
},
{
"code": null,
"e": 243,
"s": 52,
"text": "Prerequisite – Designing finite automata, previous article: Designing Deterministic Finite Automata (Set 1)In this article, we will see some designing of Deterministic Finite Automata (DFA)."
},
{
"code": null,
"e": 383,
"s": 243,
"text": "Problem-1: Construction of a DFA for the set of string over {a, b} such that length of the string |w| is divisible by 2 i.e, |w| mod 2 = 0."
},
{
"code": null,
"e": 432,
"s": 383,
"text": "Explanation – The desired language will be like:"
},
{
"code": null,
"e": 483,
"s": 432,
"text": "L = {?, aa, ab, ba, bb, aaaa, bbbb, ............} "
},
{
"code": null,
"e": 542,
"s": 483,
"text": "The state transition diagram of the language will be like:"
},
{
"code": null,
"e": 685,
"s": 542,
"text": "Here, state A represent set of all string of length even (0, 2, 4, ...), and state B represent set of all string of length odd (1, 3, 5, ...)."
},
{
"code": null,
"e": 723,
"s": 685,
"text": "Number of states: n\nIf |W| mod n = 0 "
},
{
"code": "def stateA(n): if(len(n)==0): print(\"Accepted\") else: #on any input call function stateB if (n[0]=='0' or n[0]=='1'): stateB(n[1:]) def stateB(n): if(len(n)==0): print(\"Not Accepted\") else: #on any input call function stateA if (n[0]=='0' or n[0]=='1'): stateA(n[1:]) #take inputn=input() #call stateA#to check the inputstateA(n)",
"e": 1175,
"s": 723,
"text": null
},
{
"code": null,
"e": 1509,
"s": 1175,
"text": "The above automata will accept all the strings having the length of the string divisible by 2. When the length of the string is 1, then it will go from state A to B. When the length of the string is 2, then it will go from state B to A and so on. State A is the final state i.e, it accept all the string having length divisible by 2."
},
{
"code": null,
"e": 1653,
"s": 1509,
"text": "Problem-2: Construction of a DFA for the set of string over {a, b} such that length of the string |w| is not divisible by 2 i.e, |w| mod 2 = 1."
},
{
"code": null,
"e": 1702,
"s": 1653,
"text": "Explanation – The desired language will be like:"
},
{
"code": null,
"e": 1756,
"s": 1702,
"text": "L = {a, b, aaa, aab, aba, abb, aaaaa, bbbb, .......} "
},
{
"code": null,
"e": 1815,
"s": 1756,
"text": "The state transition diagram of the language will be like:"
},
{
"code": null,
"e": 1958,
"s": 1815,
"text": "Here, state A represent set of all string of length even (0, 2, 4, ...), and state B represent set of all string of length odd (1, 3, 5, ...)."
},
{
"code": "def stateA(n): if(len(n)==0): print(\"Not Accepted\") else: #on any input call function stateB if (n[0]=='0' or n[0]=='1'): stateB(n[1:]) def stateB(n): if(len(n)==0): print(\"Accepted\") else: #on any input call function stateA if (n[0]=='0' or n[0]=='1'): stateA(n[1:]) #take inputn=input() #call stateA#to check the inputstateA(n)",
"e": 2410,
"s": 1958,
"text": null
},
{
"code": null,
"e": 2752,
"s": 2410,
"text": "The above automata will accept all the strings having the length of the string not divisible by 2. When the length of the string is 1, then it will go from state A to B. When the length of the string is 2, then it will go from state B to A and so on. State B is the final state i.e, it accept all the string having length not divisible by 2."
},
{
"code": null,
"e": 2892,
"s": 2752,
"text": "Problem-3: Construction of a DFA for the set of string over {a, b} such that length of the string |w| is divisible by 3 i.e, |w| mod 3 = 0."
},
{
"code": null,
"e": 2941,
"s": 2892,
"text": "Explanation – The desired language will be like:"
},
{
"code": null,
"e": 2995,
"s": 2941,
"text": "L = {?, aaa, aab, aba, abb, aaaaaa, bbbbbb, .......} "
},
{
"code": null,
"e": 3054,
"s": 2995,
"text": "The state transition diagram of the language will be like:"
},
{
"code": null,
"e": 3340,
"s": 3054,
"text": "Here, state A represents set for which string’s length divided by 3 then remainder is zero (0), state B represents set for which string’s length divided by 3 then the remainder is one (1), and state C represents set for which string’s length divided by 3 then the remainder is two (2)."
},
{
"code": null,
"e": 3378,
"s": 3340,
"text": "Number of states: n\nIf |W| mod n = 0 "
},
{
"code": "def stateA(n): if(len(n)==0): print(\"Accepted\") else: #on any input call function stateB if (n[0]=='0' or n[0]=='1'): stateB(n[1:]) def stateB(n): if(len(n)==0): print(\"Not Accepted\") else: #on any input call function stateC if (n[0]=='0' or n[0]=='1'): stateC(n[1:]) def stateC(n): if(len(n)==0): print(\"Not Accepted\") else: #on any input call function stateA if (n[0]=='0' or n[0]=='1'): stateA(n[1:]) #take inputn=input() #call stateA#to check the inputstateA(n)",
"e": 4036,
"s": 3378,
"text": null
},
{
"code": null,
"e": 4453,
"s": 4036,
"text": "The above automata will accept all the strings having the length of the string divisible by 3. When the length of the string is 1, then it will go from state A to B. When the length of the string is 2, then it will go from state B to C and When the length of the string is 3, then it will go from state C to A (final state). State A is the final state i.e, it accepts all the string having the length divisible by 3."
},
{
"code": null,
"e": 4597,
"s": 4453,
"text": "Problem-4: Construction of a DFA for the set of string over {a, b} such that length of the string |w| is not divisible by 3 i.e, |w| mod 3 = 1."
},
{
"code": null,
"e": 4646,
"s": 4597,
"text": "Explanation – The desired language will be like:"
},
{
"code": null,
"e": 4696,
"s": 4646,
"text": "L = {a, b, aa, ab, ba, bb, aaaa, bbbb, ........} "
},
{
"code": null,
"e": 4755,
"s": 4696,
"text": "The state transition diagram of the language will be like:"
},
{
"code": null,
"e": 5041,
"s": 4755,
"text": "Here, state A represents set for which string’s length divided by 3 then remainder is zero (0), state B represents set for which string’s length divided by 3 then the remainder is one (1), and state C represents set for which string’s length divided by 3 then the remainder is two (2)."
},
{
"code": "def stateA(n): if(len(n)==0): print(\"Not Accepted\") else: #on any input call function stateB if (n[0]=='0' or n[0]=='1'): stateB(n[1:]) def stateB(n): if(len(n)==0): print(\"Accepted\") else: #on any input call function stateC if (n[0]=='0' or n[0]=='1'): stateC(n[1:]) def stateC(n): if(len(n)==0): print(\"Not Accepted\") else: #on any input call function stateA if (n[0]=='0' or n[0]=='1'): stateA(n[1:]) #take inputn=input() #call stateA#to check the inputstateA(n)",
"e": 5699,
"s": 5041,
"text": null
},
{
"code": null,
"e": 6117,
"s": 5699,
"text": "The above automata will accept all the strings having the length of the string not divisible by 3. When the length of the string is 1, then it will go from state A to B. When the length of the string is 2, then it will go from state B to C and When the length of the string is 3, then it will go from state C to A. State B and C are the final state i.e, it accepts all the string having the length not divisible by 3."
},
{
"code": null,
"e": 6135,
"s": 6117,
"text": "_mridul_bhardwaj_"
},
{
"code": null,
"e": 6143,
"s": 6135,
"text": "GATE CS"
},
{
"code": null,
"e": 6176,
"s": 6143,
"text": "Theory of Computation & Automata"
},
{
"code": null,
"e": 6274,
"s": 6176,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6313,
"s": 6274,
"text": "Mutual exclusion in distributed system"
},
{
"code": null,
"e": 6344,
"s": 6313,
"text": "Three address code in Compiler"
},
{
"code": null,
"e": 6414,
"s": 6344,
"text": "S - attributed and L - attributed SDTs in Syntax directed translation"
},
{
"code": null,
"e": 6441,
"s": 6414,
"text": "Types of Operating Systems"
},
{
"code": null,
"e": 6478,
"s": 6441,
"text": "Code Optimization in Compiler Design"
},
{
"code": null,
"e": 6509,
"s": 6478,
"text": "Difference between DFA and NFA"
},
{
"code": null,
"e": 6589,
"s": 6509,
"text": "Removal of ambiguity (Converting an Ambiguous grammar into Unambiguous grammar)"
},
{
"code": null,
"e": 6617,
"s": 6589,
"text": "Post Correspondence Problem"
},
{
"code": null,
"e": 6652,
"s": 6617,
"text": "Church’s Thesis for Turing Machine"
}
] |
Thread Scheduling
|
03 Feb, 2022
Scheduling of threads involves two boundary scheduling,
Scheduling of user level threads (ULT) to kernel level threads (KLT) via lightweight process (LWP) by the application developer.
Scheduling of kernel level threads by the system scheduler to perform different unique os functions.
Lightweight Process (LWP) : Light-weight process are threads in the user space that acts as an interface for the ULT to access the physical CPU resources. Thread library schedules which thread of a process to run on which LWP and how long. The number of LWP created by the thread library depends on the type of application. In the case of an I/O bound application, the number of LWP depends on the number of user-level threads. This is because when an LWP is blocked on an I/O operation, then to invoke the other ULT the thread library needs to create and schedule another LWP. Thus, in an I/O bound application, the number of LWP is equal to the number of the ULT. In the case of a CPU bound application, it depends only on the application. Each LWP is attached to a separate kernel-level thread.
In real-time, the first boundary of thread scheduling is beyond specifying the scheduling policy and the priority. It requires two controls to be specified for the User level threads: Contention scope, and Allocation domain. These are explained as following below.
1. Contention Scope : The word contention here refers to the competition or fight among the User level threads to access the kernel resources. Thus, this control defines the extent to which contention takes place. It is defined by the application developer using the thread library. Depending upon the extent of contention it is classified as Process Contention Scope and System Contention Scope.
Process Contention Scope (PCS) – The contention takes place among threads within a same process. The thread library schedules the high-prioritized PCS thread to access the resources via available LWPs (priority as specified by the application developer during thread creation). System Contention Scope (SCS) – The contention takes place among all threads in the system. In this case, every SCS thread is associated to each LWP by the thread library and are scheduled by the system scheduler to access the kernel resources. In LINUX and UNIX operating systems, the POSIX Pthread library provides a function Pthread_attr_setscope to define the type of contention scope for a thread during its creation.
Process Contention Scope (PCS) – The contention takes place among threads within a same process. The thread library schedules the high-prioritized PCS thread to access the resources via available LWPs (priority as specified by the application developer during thread creation).
System Contention Scope (SCS) – The contention takes place among all threads in the system. In this case, every SCS thread is associated to each LWP by the thread library and are scheduled by the system scheduler to access the kernel resources. In LINUX and UNIX operating systems, the POSIX Pthread library provides a function Pthread_attr_setscope to define the type of contention scope for a thread during its creation.
In LINUX and UNIX operating systems, the POSIX Pthread library provides a function Pthread_attr_setscope to define the type of contention scope for a thread during its creation.
int Pthread_attr_setscope(pthread_attr_t *attr, int scope)
The first parameter denotes to which thread within the process the scope is defined. The second parameter defines the scope of contention for the thread pointed. It takes two values.
The first parameter denotes to which thread within the process the scope is defined. The second parameter defines the scope of contention for the thread pointed. It takes two values.
PTHREAD_SCOPE_SYSTEM
PTHREAD_SCOPE_PROCESS
If the scope value specified is not supported by the system, then the function returns ENOTSUP.
If the scope value specified is not supported by the system, then the function returns ENOTSUP.
2. Allocation Domain : The allocation domain is a set of one or more resources for which a thread is competing. In a multicore system, there may be one or more allocation domains where each consists of one or more cores. One ULT can be a part of one or more allocation domain. Due to this high complexity in dealing with hardware and software architectural interfaces, this control is not specified. But by default, the multicore system will have an interface that affects the allocation domain of a thread.
Consider a scenario, an operating system with three process P1, P2, P3 and 10 user level threads (T1 to T10) with a single allocation domain. 100% of CPU resources will be distributed among all the three processes. The amount of CPU resources allocated to each process and to each thread depends on the contention scope, scheduling policy and priority of each thread defined by the application developer using thread library and also depends on the system scheduler. These User level threads are of a different contention scope.
In this case, the contention for allocation domain takes place as follows,
Process P1: All PCS threads T1, T2, T3 of Process P1 will compete among themselves. The PCS threads of the same process can share one or more LWP. T1 and T2 share an LWP and T3 are allocated to a separate LWP. Between T1 and T2 allocation of kernel resources via LWP is based on preemptive priority scheduling by the thread library. A Thread with a high priority will preempt low priority threads. Whereas, thread T1 of process p1 cannot preempt thread T3 of process p3 even if the priority of T1 is greater than the priority of T3. If the priority is equal, then the allocation of ULT to available LWPs is based on the scheduling policy of threads by the system scheduler(not by thread library, in this case). Process P2: Both SCS threads T4 and T5 of process P2 will compete with processes P1 as a whole and with SCS threads T8, T9, T10 of process P3. The system scheduler will schedule the kernel resources among P1, T4, T5, T8, T9, T10, and PCS threads (T6, T7) of process P3 considering each as a separate process. Here, the Thread library has no control of scheduling the ULT to the kernel resources. Process P3: Combination of PCS and SCS threads. Consider if the system scheduler allocates 50% of CPU resources to process P3, then 25% of resources is for process scoped threads and the remaining 25% for system scoped threads. The PCS threads T6 and T7 will be allocated to access the 25% resources based on the priority by the thread library. The SCS threads T8, T9, T10 will divide the 25% resources among themselves and access the kernel resources via separate LWP and KLT. The SCS scheduling is by the system scheduler.
Process P1: All PCS threads T1, T2, T3 of Process P1 will compete among themselves. The PCS threads of the same process can share one or more LWP. T1 and T2 share an LWP and T3 are allocated to a separate LWP. Between T1 and T2 allocation of kernel resources via LWP is based on preemptive priority scheduling by the thread library. A Thread with a high priority will preempt low priority threads. Whereas, thread T1 of process p1 cannot preempt thread T3 of process p3 even if the priority of T1 is greater than the priority of T3. If the priority is equal, then the allocation of ULT to available LWPs is based on the scheduling policy of threads by the system scheduler(not by thread library, in this case).
Process P2: Both SCS threads T4 and T5 of process P2 will compete with processes P1 as a whole and with SCS threads T8, T9, T10 of process P3. The system scheduler will schedule the kernel resources among P1, T4, T5, T8, T9, T10, and PCS threads (T6, T7) of process P3 considering each as a separate process. Here, the Thread library has no control of scheduling the ULT to the kernel resources.
Process P3: Combination of PCS and SCS threads. Consider if the system scheduler allocates 50% of CPU resources to process P3, then 25% of resources is for process scoped threads and the remaining 25% for system scoped threads. The PCS threads T6 and T7 will be allocated to access the 25% resources based on the priority by the thread library. The SCS threads T8, T9, T10 will divide the 25% resources among themselves and access the kernel resources via separate LWP and KLT. The SCS scheduling is by the system scheduler.
Note: For every system call to access the kernel resources, a Kernel Level thread is created and associated to separate LWP by the system scheduler.
Number of Kernel Level Threads = Total Number of LWP
Total Number of LWP = Number of LWP for SCS + Number of LWP for PCS
Number of LWP for SCS = Number of SCS threads
Number of LWP for PCS = Depends on application developer
Here,
Number of SCS threads = 5
Number of LWP for PCS = 3
Number of SCS threads = 5
Number of LWP for SCS = 5
Total Number of LWP = 8 (=5+3)
Number of Kernel Level Threads = 8
Advantages of PCS over SCS :
If all threads are PCS, then context switching, synchronization, scheduling everything takes place within the userspace. This reduces system calls and achieves better performance.
PCS is cheaper than SCS.
PCS threads share one or more available LWPs. For every SCS thread, a separate LWP is associated.For every system call, a separate KLT is created.
The number of KLT and LWPs created highly depends on the number of SCS threads created. This increases the kernel complexity of handling scheduling and synchronization. Thereby, results in a limitation over SCS thread creation, stating that, the number of SCS threads to be smaller than the number of PCS threads.
If the system has more than one allocation domain, then scheduling and synchronization of resources becomes more tedious. Issues arise when an SCS thread is a part of more than one allocation domain, the system has to handle n number of interfaces.
The second boundary of thread scheduling involves CPU scheduling by the system scheduler. The scheduler considers each kernel-level thread as a separate process and provides access to the kernel resources.
Thread Scheduler & Thread Priority | GeeksforGeeks - YouTubeGeeksforGeeks530K subscribersThread Scheduler & Thread Priority | 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:32•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=7q22vVYKpnQ" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
?list=PLqM7alHXFySEJYFqrpxG4eTbUAiX6jD0Y
rkbhola5
Operating Systems
Write From Home
Operating Systems
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n03 Feb, 2022"
},
{
"code": null,
"e": 110,
"s": 52,
"text": "Scheduling of threads involves two boundary scheduling, "
},
{
"code": null,
"e": 239,
"s": 110,
"text": "Scheduling of user level threads (ULT) to kernel level threads (KLT) via lightweight process (LWP) by the application developer."
},
{
"code": null,
"e": 340,
"s": 239,
"text": "Scheduling of kernel level threads by the system scheduler to perform different unique os functions."
},
{
"code": null,
"e": 1139,
"s": 340,
"text": "Lightweight Process (LWP) : Light-weight process are threads in the user space that acts as an interface for the ULT to access the physical CPU resources. Thread library schedules which thread of a process to run on which LWP and how long. The number of LWP created by the thread library depends on the type of application. In the case of an I/O bound application, the number of LWP depends on the number of user-level threads. This is because when an LWP is blocked on an I/O operation, then to invoke the other ULT the thread library needs to create and schedule another LWP. Thus, in an I/O bound application, the number of LWP is equal to the number of the ULT. In the case of a CPU bound application, it depends only on the application. Each LWP is attached to a separate kernel-level thread. "
},
{
"code": null,
"e": 1407,
"s": 1141,
"text": "In real-time, the first boundary of thread scheduling is beyond specifying the scheduling policy and the priority. It requires two controls to be specified for the User level threads: Contention scope, and Allocation domain. These are explained as following below. "
},
{
"code": null,
"e": 1805,
"s": 1407,
"text": "1. Contention Scope : The word contention here refers to the competition or fight among the User level threads to access the kernel resources. Thus, this control defines the extent to which contention takes place. It is defined by the application developer using the thread library. Depending upon the extent of contention it is classified as Process Contention Scope and System Contention Scope. "
},
{
"code": null,
"e": 2511,
"s": 1807,
"text": "Process Contention Scope (PCS) – The contention takes place among threads within a same process. The thread library schedules the high-prioritized PCS thread to access the resources via available LWPs (priority as specified by the application developer during thread creation). System Contention Scope (SCS) – The contention takes place among all threads in the system. In this case, every SCS thread is associated to each LWP by the thread library and are scheduled by the system scheduler to access the kernel resources. In LINUX and UNIX operating systems, the POSIX Pthread library provides a function Pthread_attr_setscope to define the type of contention scope for a thread during its creation. "
},
{
"code": null,
"e": 2791,
"s": 2511,
"text": "Process Contention Scope (PCS) – The contention takes place among threads within a same process. The thread library schedules the high-prioritized PCS thread to access the resources via available LWPs (priority as specified by the application developer during thread creation). "
},
{
"code": null,
"e": 3218,
"s": 2793,
"text": "System Contention Scope (SCS) – The contention takes place among all threads in the system. In this case, every SCS thread is associated to each LWP by the thread library and are scheduled by the system scheduler to access the kernel resources. In LINUX and UNIX operating systems, the POSIX Pthread library provides a function Pthread_attr_setscope to define the type of contention scope for a thread during its creation. "
},
{
"code": null,
"e": 3398,
"s": 3218,
"text": "In LINUX and UNIX operating systems, the POSIX Pthread library provides a function Pthread_attr_setscope to define the type of contention scope for a thread during its creation. "
},
{
"code": null,
"e": 3458,
"s": 3398,
"text": "int Pthread_attr_setscope(pthread_attr_t *attr, int scope) "
},
{
"code": null,
"e": 3643,
"s": 3458,
"text": "The first parameter denotes to which thread within the process the scope is defined. The second parameter defines the scope of contention for the thread pointed. It takes two values. "
},
{
"code": null,
"e": 3828,
"s": 3643,
"text": "The first parameter denotes to which thread within the process the scope is defined. The second parameter defines the scope of contention for the thread pointed. It takes two values. "
},
{
"code": null,
"e": 3872,
"s": 3828,
"text": "PTHREAD_SCOPE_SYSTEM\nPTHREAD_SCOPE_PROCESS "
},
{
"code": null,
"e": 3970,
"s": 3872,
"text": "If the scope value specified is not supported by the system, then the function returns ENOTSUP. "
},
{
"code": null,
"e": 4068,
"s": 3970,
"text": "If the scope value specified is not supported by the system, then the function returns ENOTSUP. "
},
{
"code": null,
"e": 4579,
"s": 4070,
"text": "2. Allocation Domain : The allocation domain is a set of one or more resources for which a thread is competing. In a multicore system, there may be one or more allocation domains where each consists of one or more cores. One ULT can be a part of one or more allocation domain. Due to this high complexity in dealing with hardware and software architectural interfaces, this control is not specified. But by default, the multicore system will have an interface that affects the allocation domain of a thread. "
},
{
"code": null,
"e": 5109,
"s": 4579,
"text": "Consider a scenario, an operating system with three process P1, P2, P3 and 10 user level threads (T1 to T10) with a single allocation domain. 100% of CPU resources will be distributed among all the three processes. The amount of CPU resources allocated to each process and to each thread depends on the contention scope, scheduling policy and priority of each thread defined by the application developer using thread library and also depends on the system scheduler. These User level threads are of a different contention scope. "
},
{
"code": null,
"e": 5187,
"s": 5111,
"text": "In this case, the contention for allocation domain takes place as follows, "
},
{
"code": null,
"e": 6825,
"s": 5189,
"text": "Process P1: All PCS threads T1, T2, T3 of Process P1 will compete among themselves. The PCS threads of the same process can share one or more LWP. T1 and T2 share an LWP and T3 are allocated to a separate LWP. Between T1 and T2 allocation of kernel resources via LWP is based on preemptive priority scheduling by the thread library. A Thread with a high priority will preempt low priority threads. Whereas, thread T1 of process p1 cannot preempt thread T3 of process p3 even if the priority of T1 is greater than the priority of T3. If the priority is equal, then the allocation of ULT to available LWPs is based on the scheduling policy of threads by the system scheduler(not by thread library, in this case). Process P2: Both SCS threads T4 and T5 of process P2 will compete with processes P1 as a whole and with SCS threads T8, T9, T10 of process P3. The system scheduler will schedule the kernel resources among P1, T4, T5, T8, T9, T10, and PCS threads (T6, T7) of process P3 considering each as a separate process. Here, the Thread library has no control of scheduling the ULT to the kernel resources. Process P3: Combination of PCS and SCS threads. Consider if the system scheduler allocates 50% of CPU resources to process P3, then 25% of resources is for process scoped threads and the remaining 25% for system scoped threads. The PCS threads T6 and T7 will be allocated to access the 25% resources based on the priority by the thread library. The SCS threads T8, T9, T10 will divide the 25% resources among themselves and access the kernel resources via separate LWP and KLT. The SCS scheduling is by the system scheduler. "
},
{
"code": null,
"e": 7538,
"s": 6825,
"text": "Process P1: All PCS threads T1, T2, T3 of Process P1 will compete among themselves. The PCS threads of the same process can share one or more LWP. T1 and T2 share an LWP and T3 are allocated to a separate LWP. Between T1 and T2 allocation of kernel resources via LWP is based on preemptive priority scheduling by the thread library. A Thread with a high priority will preempt low priority threads. Whereas, thread T1 of process p1 cannot preempt thread T3 of process p3 even if the priority of T1 is greater than the priority of T3. If the priority is equal, then the allocation of ULT to available LWPs is based on the scheduling policy of threads by the system scheduler(not by thread library, in this case). "
},
{
"code": null,
"e": 7936,
"s": 7538,
"text": "Process P2: Both SCS threads T4 and T5 of process P2 will compete with processes P1 as a whole and with SCS threads T8, T9, T10 of process P3. The system scheduler will schedule the kernel resources among P1, T4, T5, T8, T9, T10, and PCS threads (T6, T7) of process P3 considering each as a separate process. Here, the Thread library has no control of scheduling the ULT to the kernel resources. "
},
{
"code": null,
"e": 8463,
"s": 7936,
"text": "Process P3: Combination of PCS and SCS threads. Consider if the system scheduler allocates 50% of CPU resources to process P3, then 25% of resources is for process scoped threads and the remaining 25% for system scoped threads. The PCS threads T6 and T7 will be allocated to access the 25% resources based on the priority by the thread library. The SCS threads T8, T9, T10 will divide the 25% resources among themselves and access the kernel resources via separate LWP and KLT. The SCS scheduling is by the system scheduler. "
},
{
"code": null,
"e": 8614,
"s": 8463,
"text": "Note: For every system call to access the kernel resources, a Kernel Level thread is created and associated to separate LWP by the system scheduler. "
},
{
"code": null,
"e": 8840,
"s": 8614,
"text": "Number of Kernel Level Threads = Total Number of LWP \nTotal Number of LWP = Number of LWP for SCS + Number of LWP for PCS\nNumber of LWP for SCS = Number of SCS threads\nNumber of LWP for PCS = Depends on application developer "
},
{
"code": null,
"e": 8848,
"s": 8840,
"text": "Here, "
},
{
"code": null,
"e": 9025,
"s": 8848,
"text": "Number of SCS threads = 5 \nNumber of LWP for PCS = 3 \nNumber of SCS threads = 5 \nNumber of LWP for SCS = 5 \nTotal Number of LWP = 8 (=5+3)\nNumber of Kernel Level Threads = 8 "
},
{
"code": null,
"e": 9056,
"s": 9025,
"text": "Advantages of PCS over SCS : "
},
{
"code": null,
"e": 9238,
"s": 9056,
"text": "If all threads are PCS, then context switching, synchronization, scheduling everything takes place within the userspace. This reduces system calls and achieves better performance. "
},
{
"code": null,
"e": 9265,
"s": 9238,
"text": "PCS is cheaper than SCS. "
},
{
"code": null,
"e": 9414,
"s": 9265,
"text": "PCS threads share one or more available LWPs. For every SCS thread, a separate LWP is associated.For every system call, a separate KLT is created. "
},
{
"code": null,
"e": 9730,
"s": 9414,
"text": "The number of KLT and LWPs created highly depends on the number of SCS threads created. This increases the kernel complexity of handling scheduling and synchronization. Thereby, results in a limitation over SCS thread creation, stating that, the number of SCS threads to be smaller than the number of PCS threads. "
},
{
"code": null,
"e": 9981,
"s": 9730,
"text": "If the system has more than one allocation domain, then scheduling and synchronization of resources becomes more tedious. Issues arise when an SCS thread is a part of more than one allocation domain, the system has to handle n number of interfaces. "
},
{
"code": null,
"e": 10189,
"s": 9981,
"text": "The second boundary of thread scheduling involves CPU scheduling by the system scheduler. The scheduler considers each kernel-level thread as a separate process and provides access to the kernel resources. "
},
{
"code": null,
"e": 11075,
"s": 10189,
"text": "Thread Scheduler & Thread Priority | GeeksforGeeks - YouTubeGeeksforGeeks530K subscribersThread Scheduler & Thread Priority | 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:32•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=7q22vVYKpnQ\" 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": 11117,
"s": 11075,
"text": "?list=PLqM7alHXFySEJYFqrpxG4eTbUAiX6jD0Y "
},
{
"code": null,
"e": 11126,
"s": 11117,
"text": "rkbhola5"
},
{
"code": null,
"e": 11144,
"s": 11126,
"text": "Operating Systems"
},
{
"code": null,
"e": 11160,
"s": 11144,
"text": "Write From Home"
},
{
"code": null,
"e": 11178,
"s": 11160,
"text": "Operating Systems"
}
] |
Circular (Oval like) button using canvas in kivy (using .kv file)
|
19 Jan, 2022
Kivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, linux and Windows etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications.In this article we will going to learn about how can we create a rounded or circular button in kivy using canvas. You must have a very clear concept of canvas, button and their properties to learn how can you make buttons like this. As we know canvas is the root object used for drawing by a Widget. Each Widget in Kivy already has a Canvas by default. When you create a widget, you can create all the instructions needed for drawing. To use canvas you must have to import the graphics in your file.
from kivy.graphics import Rectangle, Color
Some important properties used in this article – border : 1) Border used for BorderImage graphics instruction. Used with background_normal and background_down. Can be used for custom backgrounds. 2) It must be a list of four values: (bottom, right, top, left). 3) border is a ListProperty and defaults to (16, 16, 16, 16)Button behavior : 1) The Button Behavior mix in class provides Button behavior. 2) You can combine this class with other widgets, such as an Image, to provide alternative buttons that preserve Kivy button behavior.
Basic Approach -
-> import kivy
-> import kivy App
-> import widget
-> import Canvas i.e.:
from kivy.graphics import Rectangle, Color
-> set minimum version(optional)
-> Extend the Widget class
-> Create the App Class
-> create the .kv file:
-> create the button using the canvas
-> Use border property to give them a circular shape.
-> Add action/callback if needed
-> return a Widget
-> Run an instance of the class
Kivy Tutorial – Learn Kivy with Examples
Implementation of the Approachmain.py
Python3
## Sample Python application demonstrating the## working of canvas with buttonbehaviour i.e## creating a circular button in Kivy using .kv file #################################################### import kivy moduleimport kivy # this restrict the kivy version i.e# below this kivy version you cannot# use the app or softwarekivy.require("1.9.1") # base Class of your App inherits from the App class.# app:always refers to the instance of your applicationfrom kivy.app import App # From graphics module we are importing# Rectangle and Color as they are# basic building of canvas.from kivy.graphics import Rectangle, Color # The ButtonBehavior mixin class provides Button behavior.from kivy.uix.button import ButtonBehavior # The Label widget is for rendering text.from kivy.uix.label import Label # class in which we are creating the canvasclass CircularButton(ButtonBehavior, Label): pass # Create the App Classclass BtnApp(App): def build(self): return CircularButton() # run the AppBtnApp().run()
.kv file
Python3
# .kv file of creating a circular button using canvas <CircularButton>: # Creating Circular button canvas: # Color is different if button is pressed Color: rgb: (0, 1, 0, 1) if self.state == 'normal' else (1, 0, 1, 1) # Rounded rectangle canvas RoundedRectangle: # Giving the size and the position size: (self.size) pos: (self.pos) # This will force the rectangle to be the circle radius: [400, ] # Print the text when touched or button pressed on_release: print("This is the button made up by the canvas")
Output:
Note: Widgets are still rectangles. That means that even if you click on the rounded corners, the button still receive the event.
germanshephered48
Python-gui
Python-kivy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Convert integer to string in Python
Python OOPs Concepts
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Jan, 2022"
},
{
"code": null,
"e": 765,
"s": 28,
"text": "Kivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, linux and Windows etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications.In this article we will going to learn about how can we create a rounded or circular button in kivy using canvas. You must have a very clear concept of canvas, button and their properties to learn how can you make buttons like this. As we know canvas is the root object used for drawing by a Widget. Each Widget in Kivy already has a Canvas by default. When you create a widget, you can create all the instructions needed for drawing. To use canvas you must have to import the graphics in your file. "
},
{
"code": null,
"e": 808,
"s": 765,
"text": "from kivy.graphics import Rectangle, Color"
},
{
"code": null,
"e": 1347,
"s": 810,
"text": "Some important properties used in this article – border : 1) Border used for BorderImage graphics instruction. Used with background_normal and background_down. Can be used for custom backgrounds. 2) It must be a list of four values: (bottom, right, top, left). 3) border is a ListProperty and defaults to (16, 16, 16, 16)Button behavior : 1) The Button Behavior mix in class provides Button behavior. 2) You can combine this class with other widgets, such as an Image, to provide alternative buttons that preserve Kivy button behavior. "
},
{
"code": null,
"e": 1785,
"s": 1349,
"text": "Basic Approach -\n-> import kivy\n-> import kivy App\n-> import widget\n-> import Canvas i.e.:\n from kivy.graphics import Rectangle, Color\n-> set minimum version(optional)\n-> Extend the Widget class\n-> Create the App Class\n-> create the .kv file:\n -> create the button using the canvas\n -> Use border property to give them a circular shape.\n -> Add action/callback if needed\n-> return a Widget\n-> Run an instance of the class"
},
{
"code": null,
"e": 1828,
"s": 1787,
"text": "Kivy Tutorial – Learn Kivy with Examples"
},
{
"code": null,
"e": 1868,
"s": 1828,
"text": "Implementation of the Approachmain.py "
},
{
"code": null,
"e": 1876,
"s": 1868,
"text": "Python3"
},
{
"code": "## Sample Python application demonstrating the## working of canvas with buttonbehaviour i.e## creating a circular button in Kivy using .kv file #################################################### import kivy moduleimport kivy # this restrict the kivy version i.e# below this kivy version you cannot# use the app or softwarekivy.require(\"1.9.1\") # base Class of your App inherits from the App class.# app:always refers to the instance of your applicationfrom kivy.app import App # From graphics module we are importing# Rectangle and Color as they are# basic building of canvas.from kivy.graphics import Rectangle, Color # The ButtonBehavior mixin class provides Button behavior.from kivy.uix.button import ButtonBehavior # The Label widget is for rendering text.from kivy.uix.label import Label # class in which we are creating the canvasclass CircularButton(ButtonBehavior, Label): pass # Create the App Classclass BtnApp(App): def build(self): return CircularButton() # run the AppBtnApp().run()",
"e": 2898,
"s": 1876,
"text": null
},
{
"code": null,
"e": 2909,
"s": 2898,
"text": ".kv file "
},
{
"code": null,
"e": 2917,
"s": 2909,
"text": "Python3"
},
{
"code": "# .kv file of creating a circular button using canvas <CircularButton>: # Creating Circular button canvas: # Color is different if button is pressed Color: rgb: (0, 1, 0, 1) if self.state == 'normal' else (1, 0, 1, 1) # Rounded rectangle canvas RoundedRectangle: # Giving the size and the position size: (self.size) pos: (self.pos) # This will force the rectangle to be the circle radius: [400, ] # Print the text when touched or button pressed on_release: print(\"This is the button made up by the canvas\")",
"e": 3584,
"s": 2917,
"text": null
},
{
"code": null,
"e": 3594,
"s": 3584,
"text": "Output: "
},
{
"code": null,
"e": 3727,
"s": 3596,
"text": "Note: Widgets are still rectangles. That means that even if you click on the rounded corners, the button still receive the event. "
},
{
"code": null,
"e": 3745,
"s": 3727,
"text": "germanshephered48"
},
{
"code": null,
"e": 3756,
"s": 3745,
"text": "Python-gui"
},
{
"code": null,
"e": 3768,
"s": 3756,
"text": "Python-kivy"
},
{
"code": null,
"e": 3775,
"s": 3768,
"text": "Python"
},
{
"code": null,
"e": 3873,
"s": 3775,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3891,
"s": 3873,
"text": "Python Dictionary"
},
{
"code": null,
"e": 3933,
"s": 3891,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3955,
"s": 3933,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3981,
"s": 3955,
"text": "Python String | replace()"
},
{
"code": null,
"e": 4013,
"s": 3981,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 4042,
"s": 4013,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 4069,
"s": 4042,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 4099,
"s": 4069,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 4135,
"s": 4099,
"text": "Convert integer to string in Python"
}
] |
How to Convert all LinkedHashMap Values to a List in Java?
|
17 Dec, 2020
The task is to convert all LinkedHashMap values to a list in java. LinkedHashMap is an implementation of a Map. The Map and List are two different data structures. The Map stores key-value pairs while the List is an ordered collection of elements.
To convert all values of the LinkedHashMap to a List using the values() method. The values() method of the LinkedHashMap class returns a Collection view of all the values contained in the map object. You can then use this collection to convert it to a List object.
Syntax:
LinkedHashMap.values()
Return Value: The method is used to return a collection view containing all the values of the map.
Example 1:
Java
// Java program to Convert all LinkedHashMap values to a// List import java.util.ArrayList;import java.util.LinkedHashMap;import java.util.List; public class LinkedHashMapToListExample { public static void main(String[] args) { // instance of linkedhashmap LinkedHashMap<Integer, Integer> lhmap = new LinkedHashMap<Integer, Integer>(); // add mappings lhmap.put(1, 11); lhmap.put(2, 22); lhmap.put(3, 33); // convert values to a list List<Integer> listValues = new ArrayList<Integer>(lhmap.values()); // print values System.out.println("List contains:"); for (Integer value : listValues) { System.out.println(value); } }}
List contains:
11
22
33
Example 2:
Java
// Java program to Convert all LinkedHashMap values to a// List import java.util.ArrayList;import java.util.LinkedHashMap;import java.util.List; public class LinkedHashMapToListExample { public static void main(String[] args) { // instance of linkedhashmap LinkedHashMap<Integer, String> lhmap = new LinkedHashMap<Integer, String>(); // add mappings lhmap.put(10, "Geeks"); lhmap.put(15, "4"); lhmap.put(20, "Geeks"); lhmap.put(25, "Welcomes"); lhmap.put(30, "You"); // convert values to a list List<String> listValues = new ArrayList<String>(lhmap.values()); // print values System.out.println("List contains:"); for (String value : listValues) { System.out.println(value); } }}
List contains:
Geeks
4
Geeks
Welcomes
You
Java-LinkedHashMap
java-list
Picked
Technical Scripter 2020
Java
Java Programs
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
Interfaces in Java
Stream In Java
ArrayList in Java
Collections in Java
Initializing a List in Java
Java Programming Examples
Convert a String to Character Array in Java
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 Dec, 2020"
},
{
"code": null,
"e": 276,
"s": 28,
"text": "The task is to convert all LinkedHashMap values to a list in java. LinkedHashMap is an implementation of a Map. The Map and List are two different data structures. The Map stores key-value pairs while the List is an ordered collection of elements."
},
{
"code": null,
"e": 541,
"s": 276,
"text": "To convert all values of the LinkedHashMap to a List using the values() method. The values() method of the LinkedHashMap class returns a Collection view of all the values contained in the map object. You can then use this collection to convert it to a List object."
},
{
"code": null,
"e": 549,
"s": 541,
"text": "Syntax:"
},
{
"code": null,
"e": 572,
"s": 549,
"text": "LinkedHashMap.values()"
},
{
"code": null,
"e": 671,
"s": 572,
"text": "Return Value: The method is used to return a collection view containing all the values of the map."
},
{
"code": null,
"e": 682,
"s": 671,
"text": "Example 1:"
},
{
"code": null,
"e": 687,
"s": 682,
"text": "Java"
},
{
"code": "// Java program to Convert all LinkedHashMap values to a// List import java.util.ArrayList;import java.util.LinkedHashMap;import java.util.List; public class LinkedHashMapToListExample { public static void main(String[] args) { // instance of linkedhashmap LinkedHashMap<Integer, Integer> lhmap = new LinkedHashMap<Integer, Integer>(); // add mappings lhmap.put(1, 11); lhmap.put(2, 22); lhmap.put(3, 33); // convert values to a list List<Integer> listValues = new ArrayList<Integer>(lhmap.values()); // print values System.out.println(\"List contains:\"); for (Integer value : listValues) { System.out.println(value); } }}",
"e": 1447,
"s": 687,
"text": null
},
{
"code": null,
"e": 1471,
"s": 1447,
"text": "List contains:\n11\n22\n33"
},
{
"code": null,
"e": 1482,
"s": 1471,
"text": "Example 2:"
},
{
"code": null,
"e": 1487,
"s": 1482,
"text": "Java"
},
{
"code": "// Java program to Convert all LinkedHashMap values to a// List import java.util.ArrayList;import java.util.LinkedHashMap;import java.util.List; public class LinkedHashMapToListExample { public static void main(String[] args) { // instance of linkedhashmap LinkedHashMap<Integer, String> lhmap = new LinkedHashMap<Integer, String>(); // add mappings lhmap.put(10, \"Geeks\"); lhmap.put(15, \"4\"); lhmap.put(20, \"Geeks\"); lhmap.put(25, \"Welcomes\"); lhmap.put(30, \"You\"); // convert values to a list List<String> listValues = new ArrayList<String>(lhmap.values()); // print values System.out.println(\"List contains:\"); for (String value : listValues) { System.out.println(value); } }}",
"e": 2319,
"s": 1487,
"text": null
},
{
"code": null,
"e": 2361,
"s": 2319,
"text": "List contains:\nGeeks\n4\nGeeks\nWelcomes\nYou"
},
{
"code": null,
"e": 2380,
"s": 2361,
"text": "Java-LinkedHashMap"
},
{
"code": null,
"e": 2390,
"s": 2380,
"text": "java-list"
},
{
"code": null,
"e": 2397,
"s": 2390,
"text": "Picked"
},
{
"code": null,
"e": 2421,
"s": 2397,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 2426,
"s": 2421,
"text": "Java"
},
{
"code": null,
"e": 2440,
"s": 2426,
"text": "Java Programs"
},
{
"code": null,
"e": 2459,
"s": 2440,
"text": "Technical Scripter"
},
{
"code": null,
"e": 2464,
"s": 2459,
"text": "Java"
},
{
"code": null,
"e": 2562,
"s": 2464,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2613,
"s": 2562,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 2632,
"s": 2613,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 2647,
"s": 2632,
"text": "Stream In Java"
},
{
"code": null,
"e": 2665,
"s": 2647,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 2685,
"s": 2665,
"text": "Collections in Java"
},
{
"code": null,
"e": 2713,
"s": 2685,
"text": "Initializing a List in Java"
},
{
"code": null,
"e": 2739,
"s": 2713,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 2783,
"s": 2739,
"text": "Convert a String to Character Array in Java"
},
{
"code": null,
"e": 2817,
"s": 2783,
"text": "Convert Double to Integer in Java"
}
] |
Edit Distance | DP using Memoization
|
20 May, 2022
Given two strings str1 and str2 and below operations that can be performed on str1. Find the minimum number of edits (operations) required to convert ‘str1’ into ‘str2’.
Insert
Remove
Replace
All of the above operations are of equal cost.
Examples:
Input: str1 = “geek”, str2 = “gesek” Output: 1 We can convert str1 into str2 by inserting a ‘s’.
Input: str1 = “cat”, str2 = “cut” Output: 1 We can convert str1 into str2 by replacing ‘a’ with ‘u’.
Input: str1 = “sunday”, str2 = “saturday” Output: 3 Last three and first characters are same. We basically need to convert “un” to “atur”. This can be done using below three operations. Replace ‘n’ with ‘r’, insert t, insert a
What are the subproblems in this case? The idea is to process all characters one by one starting from either from left or right sides of both strings. Let us traverse from right corner, there are two possibilities for every pair of characters being traversed. The following are the conditions:
If last characters of two strings are same, nothing much to do. Ignore last characters and get count for remaining strings. So we recur for lengths m-1 and n-1.Else (If last characters are not same), we consider all operations on ‘str1’, consider all three operations on last character of first string, recursively compute minimum cost for all three operations, and take minimum of three values. Insert: Recur for m and n-1Remove: Recur for m-1 and nReplace: Recur for m-1 and n-1
If last characters of two strings are same, nothing much to do. Ignore last characters and get count for remaining strings. So we recur for lengths m-1 and n-1.
Else (If last characters are not same), we consider all operations on ‘str1’, consider all three operations on last character of first string, recursively compute minimum cost for all three operations, and take minimum of three values. Insert: Recur for m and n-1Remove: Recur for m-1 and nReplace: Recur for m-1 and n-1
Insert: Recur for m and n-1
Remove: Recur for m-1 and n
Replace: Recur for m-1 and n-1
Below is the implementation of the above approach:
C++
Java
Python
C#
Javascript
// A Naive recursive C++ program to find minimum number// operations to convert str1 to str2#include <bits/stdc++.h>using namespace std; // Utility function to find minimum of three numbersint min(int x, int y, int z){ return min(min(x, y), z);} int editDist(string str1, string str2, int m, int n){ // If first string is empty, the only option is to // insert all characters of second string into first if (m == 0) return n; // If second string is empty, the only option is to // remove all characters of first string if (n == 0) return m; // If last characters of two strings are same, nothing // much to do. Ignore last characters and get count for // remaining strings. if (str1[m - 1] == str2[n - 1]) return editDist(str1, str2, m - 1, n - 1); // If last characters are not same, consider all three // operations on last character of first string, recursively // compute minimum cost for all three operations and take // minimum of three values. return 1 + min(editDist(str1, str2, m, n - 1), // Insert editDist(str1, str2, m - 1, n), // Remove editDist(str1, str2, m - 1, n - 1) // Replace );} // Driver programint main(){ // your code goes here string str1 = "sunday"; string str2 = "saturday"; cout << editDist(str1, str2, str1.length(), str2.length()); return 0;}
// A Naive recursive Java program to find minimum number// operations to convert str1 to str2class EDIST { static int min(int x, int y, int z) { if (x <= y && x <= z) return x; if (y <= x && y <= z) return y; else return z; } static int editDist(String str1, String str2, int m, int n) { // If first string is empty, the only option is to // insert all characters of second string into first if (m == 0) return n; // If second string is empty, the only option is to // remove all characters of first string if (n == 0) return m; // If last characters of two strings are same, nothing // much to do. Ignore last characters and get count for // remaining strings. if (str1.charAt(m - 1) == str2.charAt(n - 1)) return editDist(str1, str2, m - 1, n - 1); // If last characters are not same, consider all three // operations on last character of first string, recursively // compute minimum cost for all three operations and take // minimum of three values. return 1 + min(editDist(str1, str2, m, n - 1), // Insert editDist(str1, str2, m - 1, n), // Remove editDist(str1, str2, m - 1, n - 1) // Replace ); } public static void main(String args[]) { String str1 = "sunday"; String str2 = "saturday"; System.out.println(editDist(str1, str2, str1.length(), str2.length())); }}
# A Naive recursive Python program to find minimum number# operations to convert str1 to str2def editDistance(str1, str2, m, n): # If first string is empty, the only option is to # insert all characters of second string into first if m == 0: return n # If second string is empty, the only option is to # remove all characters of first string if n == 0: return m # If last characters of two strings are same, nothing # much to do. Ignore last characters and get count for # remaining strings. if str1[m-1]== str2[n-1]: return editDistance(str1, str2, m-1, n-1) # If last characters are not same, consider all three # operations on last character of first string, recursively # compute minimum cost for all three operations and take # minimum of three values. return 1 + min(editDistance(str1, str2, m, n-1), # Insert editDistance(str1, str2, m-1, n), # Remove editDistance(str1, str2, m-1, n-1) # Replace ) # Driver program to test the above functionstr1 = "sunday"str2 = "saturday"print editDistance(str1, str2, len(str1), len(str2))
// A Naive recursive C# program to// find minimum numberoperations// to convert str1 to str2using System; class GFG { static int min(int x, int y, int z) { if (x <= y && x <= z) return x; if (y <= x && y <= z) return y; else return z; } static int editDist(String str1, String str2, int m, int n) { // If first string is empty, the only option is to // insert all characters of second string into first if (m == 0) return n; // If second string is empty, the only option is to // remove all characters of first string if (n == 0) return m; // If last characters of two strings are same, nothing // much to do. Ignore last characters and get count for // remaining strings. if (str1[m - 1] == str2[n - 1]) return editDist(str1, str2, m - 1, n - 1); // If last characters are not same, consider all three // operations on last character of first string, recursively // compute minimum cost for all three operations and take // minimum of three values. return 1 + min(editDist(str1, str2, m, n - 1), // Insert editDist(str1, str2, m - 1, n), // Remove editDist(str1, str2, m - 1, n - 1) // Replace ); } // Driver code public static void Main() { String str1 = "sunday"; String str2 = "saturday"; Console.WriteLine(editDist(str1, str2, str1.Length, str2.Length)); }}
<script> // A Naive recursive Javascript// program to find minimum number// operations to convert str1 to str2 // Utility function to find minimum of three numbersfunction min(x, y, z){ return Math.min(Math.min(x, y), z);} function editDist(str1, str2, m, n){ // If first string is empty, the only option is to // insert all characters of second string into first if (m == 0) return n; // If second string is empty, the only option is to // remove all characters of first string if (n == 0) return m; // If last characters of two strings are same, nothing // much to do. Ignore last characters and get count for // remaining strings. if (str1[m - 1] == str2[n - 1]) return editDist(str1, str2, m - 1, n - 1); // If last characters are not same, consider all three // operations on last character of first string, recursively // compute minimum cost for all three operations and take // minimum of three values. return 1 + min(editDist(str1, str2, m, n - 1), // Insert editDist(str1, str2, m - 1, n), // Remove editDist(str1, str2, m - 1, n - 1) // Replace );} // Driver program// your code goes herevar str1 = "sunday";var str2 = "saturday";document.write( editDist(str1, str2, str1.length, str2.length)); </script>
Output:
3
The time complexity of above solution is O(3^n) which is exponential. The worst-case happens when none of characters of two strings match. Below is a recursive call diagram for worst case.
We can see that many subproblems are solved, again and again, for example, eD(2, 2) is called three times. Since same subproblems are called again, this problem has Overlapping Subproblems property. So Edit Distance problem has both properties (see this and this) of a dynamic programming problem. Like other typical Dynamic Programming(DP) problems, recomputations of same subproblems can be avoided by constructing a temporary array that stores results of subproblems. The bottom-up approach can be found here.
The problem can also be solved using top-down Dynamic Programming and using memoization. In the recursive code, memoization can be used to avoid overlapping problems. There are several repetitive calls which can be computed in O(1) if the value is stored when called for the first time. On observing the recursive code, it is seen that a maximum of two parameters is changing their value on every recursive call. There will be cases when the same recursive call has been called previously. Since two parameters are not constant, a 2-D array can be used to avoid repetitive calls. Hence the return value is stored in some 2-D array. Below are the steps:
Initialize a 2-D DP array of size m *n with -1 at all the index.
On every recursive call, store the return value at dp[m][n] so that if func(m, n) is called again, it can be answered in O(1) without using recursion.
Check if the recursive call has been visited previously or not by checking the value at dp[m][n].
Below is the implementation of the above approach:
C++
Java
Python3
Javascript
// A memoization program to find minimum number// operations to convert str1 to str2#include <bits/stdc++.h>using namespace std; // Maximum 2-D array column sizeconst int maximum = 1000; // Utility function to find minimum of three numbersint min(int x, int y, int z){ return min(min(x, y), z);} int editDist(string str1, string str2, int m, int n, int dp[][maximum]){ // If first string is empty, the only option is to // insert all characters of second string into first if (m == 0) return n; // If second string is empty, the only option is to // remove all characters of first string if (n == 0) return m; // if the recursive call has been // called previously, then return // the stored value that was calculated // previously if (dp[m - 1][n - 1] != -1) return dp[m - 1][n - 1]; // If last characters of two strings are same, nothing // much to do. Ignore last characters and get count for // remaining strings. // Store the returned value at dp[m-1][n-1] // considering 1-based indexing if (str1[m - 1] == str2[n - 1]) return dp[m - 1][n - 1] = editDist(str1, str2, m - 1, n - 1, dp); // If last characters are not same, consider all three // operations on last character of first string, recursively // compute minimum cost for all three operations and take // minimum of three values. // Store the returned value at dp[m-1][n-1] // considering 1-based indexing return dp[m - 1][n - 1] = 1 + min(editDist(str1, str2, m, n - 1, dp), // Insert editDist(str1, str2, m - 1, n, dp), // Remove editDist(str1, str2, m - 1, n - 1, dp) // Replace );} // Driver Codeint main(){ string str1 = "sunday"; string str2 = "saturday"; int m = str1.length(); int n = str2.length(); // Declare a dp array which stores // the answer to recursive calls int dp[m][maximum]; // initially all index with -1 memset(dp, -1, sizeof dp); // Function call // memoization and top-down approach cout << editDist(str1, str2, m, n, dp); return 0;}
// A memoization program to find minimum number// operations to convert str1 to str2import java.util.*; class GFG{ // Maximum 2-D array column size static int maximum = 1000; // Utility function to find minimum of three numbers static int min(int x, int y, int z) { return Math.min((Math.min(x, y)), z); } static int editDist(String str1, String str2, int m, int n, int[][] dp) { // If first string is empty, the only option is to // insert all characters of second string into first if (m == 0) return n; // If second string is empty, the only option is to // remove all characters of first string if (n == 0) return m; // if the recursive call has been // called previously, then return // the stored value that was calculated // previously if (dp[m - 1][n - 1] != -1) return dp[m - 1][n - 1]; // If last characters of two strings are same, // nothing much to do. Ignore last characters and // get count for remaining strings. // Store the returned value at dp[m-1][n-1] // considering 1-based indexing if (str1.charAt(m - 1) == str2.charAt(n - 1)) return dp[m - 1][n - 1] = editDist(str1, str2, m - 1, n - 1, dp); // If last characters are not same, consider all // three operations on last character of first // string, recursively compute minimum cost for all // three operations and take minimum of three // values. // Store the returned value at dp[m-1][n-1] // considering 1-based indexing return dp[m - 1][n - 1] = 1 + min(editDist(str1, str2, m, n - 1, dp), // Insert editDist(str1, str2, m - 1, n, dp), // Remove editDist(str1, str2, m - 1, n - 1, dp) // Replace ); } // Driver code public static void main(String[] args) { String str1 = "sunday"; String str2 = "saturday"; int m = str1.length(); int n = str2.length(); // Declare a dp array which stores // the answer to recursive calls int[][] dp = new int[m][maximum]; for (int i = 0; i < dp.length; i++) Arrays.fill(dp[i], -1); // Function call // memoization and top-down approach System.out.println(editDist(str1, str2, m, n, dp)); }} // This code is contributed by Karandeep Singh
# A memoization program to find minimum number# operations to convert str1 to str2def editDistance(str1, str2, m, n, d = {}): key = m, n # If first string is empty, the only option # is to insert all characters of second # string into first if m == 0: return n # If second string is empty, the only # option is to remove all characters # of first string if n == 0: return m if key in d: return d[key] # If last characters of two strings are same, # nothing much to do. Ignore last characters # and get count for remaining strings. if str1[m - 1] == str2[n - 1]: return editDistance(str1, str2, m - 1, n - 1) # If last characters are not same, consider # all three operations on last character of # first string, recursively compute minimum # cost for all three operations and take # minimum of three values. # Store the returned value at dp[m-1][n-1] # considering 1-based indexing d[key] = 1 + min(editDistance(str1, str2, m, n - 1), # Insert editDistance(str1, str2, m - 1, n), # Remove editDistance(str1, str2, m - 1, n - 1)) # Replace return d[key] # Driver codestr1 = "sunday"str2 = "saturday" print(editDistance(str1, str2, len(str1), len(str2))) # This code is contributed by puranjanprithu
<script> // A memoization program to find minimum number// operations to convert str1 to str2 // Maximum 2-D array column sizeconst maximum = 1000; // Utility function to find minimum of three numbersfunction min(x, y, z){ return Math.min(Math.min(x, y), z);} function editDist(str1, str2, m, n, dp){ // If first string is empty, the only option is to // insert all characters of second string into first if (m == 0) return n; // If second string is empty, the only option is to // remove all characters of first string if (n == 0) return m; // if the recursive call has been // called previously, then return // the stored value that was calculated // previously if (dp[m - 1][n - 1] != -1) return dp[m - 1][n - 1]; // If last characters of two strings are same, nothing // much to do. Ignore last characters and get count for // remaining strings. // Store the returned value at dp[m-1][n-1] // considering 1-based indexing if (str1[m - 1] == str2[n - 1]) return dp[m - 1][n - 1] = editDist(str1, str2, m - 1, n - 1, dp); // If last characters are not same, consider all three // operations on last character of first string, recursively // compute minimum cost for all three operations and take // minimum of three values. // Store the returned value at dp[m-1][n-1] // considering 1-based indexing return dp[m - 1][n - 1] = 1 + min(editDist(str1, str2, m, n - 1, dp), // Insert editDist(str1, str2, m - 1, n, dp), // Remove editDist(str1, str2, m - 1, n - 1, dp) // Replace );} // Driver Code let str1 = "sunday";let str2 = "saturday";let m = str1.length;let n = str2.length; // Declare a dp array which stores// the answer to recursive calls// initially all index with -1let dp = new Array(m);for(let i = 0; i < m; i++){ dp[i] = new Array(maximum).fill(-1);} // Function call// memoization and top-down approachdocument.write(editDist(str1, str2, m, n, dp)); // This code is contributed by shinjanpatra </script>
Output:
3
Time Complexity: O(M * N) Auxiliary Space: O(M * N)
nidhi_biet
puranjanprithu
sweetyty
famously
karandeep1234
shinjanpatra
Memoization
Dynamic Programming
Strings
Strings
Dynamic Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Subset Sum Problem | DP-25
Longest Palindromic Substring | Set 1
Floyd Warshall Algorithm | DP-16
Find if there is a path between two vertices in an undirected graph
Matrix Chain Multiplication | DP-8
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": 54,
"s": 26,
"text": "\n20 May, 2022"
},
{
"code": null,
"e": 225,
"s": 54,
"text": "Given two strings str1 and str2 and below operations that can be performed on str1. Find the minimum number of edits (operations) required to convert ‘str1’ into ‘str2’. "
},
{
"code": null,
"e": 232,
"s": 225,
"text": "Insert"
},
{
"code": null,
"e": 239,
"s": 232,
"text": "Remove"
},
{
"code": null,
"e": 247,
"s": 239,
"text": "Replace"
},
{
"code": null,
"e": 295,
"s": 247,
"text": "All of the above operations are of equal cost. "
},
{
"code": null,
"e": 306,
"s": 295,
"text": "Examples: "
},
{
"code": null,
"e": 403,
"s": 306,
"text": "Input: str1 = “geek”, str2 = “gesek” Output: 1 We can convert str1 into str2 by inserting a ‘s’."
},
{
"code": null,
"e": 504,
"s": 403,
"text": "Input: str1 = “cat”, str2 = “cut” Output: 1 We can convert str1 into str2 by replacing ‘a’ with ‘u’."
},
{
"code": null,
"e": 731,
"s": 504,
"text": "Input: str1 = “sunday”, str2 = “saturday” Output: 3 Last three and first characters are same. We basically need to convert “un” to “atur”. This can be done using below three operations. Replace ‘n’ with ‘r’, insert t, insert a"
},
{
"code": null,
"e": 1026,
"s": 731,
"text": "What are the subproblems in this case? The idea is to process all characters one by one starting from either from left or right sides of both strings. Let us traverse from right corner, there are two possibilities for every pair of characters being traversed. The following are the conditions: "
},
{
"code": null,
"e": 1507,
"s": 1026,
"text": "If last characters of two strings are same, nothing much to do. Ignore last characters and get count for remaining strings. So we recur for lengths m-1 and n-1.Else (If last characters are not same), we consider all operations on ‘str1’, consider all three operations on last character of first string, recursively compute minimum cost for all three operations, and take minimum of three values. Insert: Recur for m and n-1Remove: Recur for m-1 and nReplace: Recur for m-1 and n-1"
},
{
"code": null,
"e": 1668,
"s": 1507,
"text": "If last characters of two strings are same, nothing much to do. Ignore last characters and get count for remaining strings. So we recur for lengths m-1 and n-1."
},
{
"code": null,
"e": 1989,
"s": 1668,
"text": "Else (If last characters are not same), we consider all operations on ‘str1’, consider all three operations on last character of first string, recursively compute minimum cost for all three operations, and take minimum of three values. Insert: Recur for m and n-1Remove: Recur for m-1 and nReplace: Recur for m-1 and n-1"
},
{
"code": null,
"e": 2017,
"s": 1989,
"text": "Insert: Recur for m and n-1"
},
{
"code": null,
"e": 2045,
"s": 2017,
"text": "Remove: Recur for m-1 and n"
},
{
"code": null,
"e": 2076,
"s": 2045,
"text": "Replace: Recur for m-1 and n-1"
},
{
"code": null,
"e": 2128,
"s": 2076,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 2132,
"s": 2128,
"text": "C++"
},
{
"code": null,
"e": 2137,
"s": 2132,
"text": "Java"
},
{
"code": null,
"e": 2144,
"s": 2137,
"text": "Python"
},
{
"code": null,
"e": 2147,
"s": 2144,
"text": "C#"
},
{
"code": null,
"e": 2158,
"s": 2147,
"text": "Javascript"
},
{
"code": "// A Naive recursive C++ program to find minimum number// operations to convert str1 to str2#include <bits/stdc++.h>using namespace std; // Utility function to find minimum of three numbersint min(int x, int y, int z){ return min(min(x, y), z);} int editDist(string str1, string str2, int m, int n){ // If first string is empty, the only option is to // insert all characters of second string into first if (m == 0) return n; // If second string is empty, the only option is to // remove all characters of first string if (n == 0) return m; // If last characters of two strings are same, nothing // much to do. Ignore last characters and get count for // remaining strings. if (str1[m - 1] == str2[n - 1]) return editDist(str1, str2, m - 1, n - 1); // If last characters are not same, consider all three // operations on last character of first string, recursively // compute minimum cost for all three operations and take // minimum of three values. return 1 + min(editDist(str1, str2, m, n - 1), // Insert editDist(str1, str2, m - 1, n), // Remove editDist(str1, str2, m - 1, n - 1) // Replace );} // Driver programint main(){ // your code goes here string str1 = \"sunday\"; string str2 = \"saturday\"; cout << editDist(str1, str2, str1.length(), str2.length()); return 0;}",
"e": 3574,
"s": 2158,
"text": null
},
{
"code": "// A Naive recursive Java program to find minimum number// operations to convert str1 to str2class EDIST { static int min(int x, int y, int z) { if (x <= y && x <= z) return x; if (y <= x && y <= z) return y; else return z; } static int editDist(String str1, String str2, int m, int n) { // If first string is empty, the only option is to // insert all characters of second string into first if (m == 0) return n; // If second string is empty, the only option is to // remove all characters of first string if (n == 0) return m; // If last characters of two strings are same, nothing // much to do. Ignore last characters and get count for // remaining strings. if (str1.charAt(m - 1) == str2.charAt(n - 1)) return editDist(str1, str2, m - 1, n - 1); // If last characters are not same, consider all three // operations on last character of first string, recursively // compute minimum cost for all three operations and take // minimum of three values. return 1 + min(editDist(str1, str2, m, n - 1), // Insert editDist(str1, str2, m - 1, n), // Remove editDist(str1, str2, m - 1, n - 1) // Replace ); } public static void main(String args[]) { String str1 = \"sunday\"; String str2 = \"saturday\"; System.out.println(editDist(str1, str2, str1.length(), str2.length())); }}",
"e": 5155,
"s": 3574,
"text": null
},
{
"code": "# A Naive recursive Python program to find minimum number# operations to convert str1 to str2def editDistance(str1, str2, m, n): # If first string is empty, the only option is to # insert all characters of second string into first if m == 0: return n # If second string is empty, the only option is to # remove all characters of first string if n == 0: return m # If last characters of two strings are same, nothing # much to do. Ignore last characters and get count for # remaining strings. if str1[m-1]== str2[n-1]: return editDistance(str1, str2, m-1, n-1) # If last characters are not same, consider all three # operations on last character of first string, recursively # compute minimum cost for all three operations and take # minimum of three values. return 1 + min(editDistance(str1, str2, m, n-1), # Insert editDistance(str1, str2, m-1, n), # Remove editDistance(str1, str2, m-1, n-1) # Replace ) # Driver program to test the above functionstr1 = \"sunday\"str2 = \"saturday\"print editDistance(str1, str2, len(str1), len(str2))",
"e": 6323,
"s": 5155,
"text": null
},
{
"code": "// A Naive recursive C# program to// find minimum numberoperations// to convert str1 to str2using System; class GFG { static int min(int x, int y, int z) { if (x <= y && x <= z) return x; if (y <= x && y <= z) return y; else return z; } static int editDist(String str1, String str2, int m, int n) { // If first string is empty, the only option is to // insert all characters of second string into first if (m == 0) return n; // If second string is empty, the only option is to // remove all characters of first string if (n == 0) return m; // If last characters of two strings are same, nothing // much to do. Ignore last characters and get count for // remaining strings. if (str1[m - 1] == str2[n - 1]) return editDist(str1, str2, m - 1, n - 1); // If last characters are not same, consider all three // operations on last character of first string, recursively // compute minimum cost for all three operations and take // minimum of three values. return 1 + min(editDist(str1, str2, m, n - 1), // Insert editDist(str1, str2, m - 1, n), // Remove editDist(str1, str2, m - 1, n - 1) // Replace ); } // Driver code public static void Main() { String str1 = \"sunday\"; String str2 = \"saturday\"; Console.WriteLine(editDist(str1, str2, str1.Length, str2.Length)); }}",
"e": 7934,
"s": 6323,
"text": null
},
{
"code": "<script> // A Naive recursive Javascript// program to find minimum number// operations to convert str1 to str2 // Utility function to find minimum of three numbersfunction min(x, y, z){ return Math.min(Math.min(x, y), z);} function editDist(str1, str2, m, n){ // If first string is empty, the only option is to // insert all characters of second string into first if (m == 0) return n; // If second string is empty, the only option is to // remove all characters of first string if (n == 0) return m; // If last characters of two strings are same, nothing // much to do. Ignore last characters and get count for // remaining strings. if (str1[m - 1] == str2[n - 1]) return editDist(str1, str2, m - 1, n - 1); // If last characters are not same, consider all three // operations on last character of first string, recursively // compute minimum cost for all three operations and take // minimum of three values. return 1 + min(editDist(str1, str2, m, n - 1), // Insert editDist(str1, str2, m - 1, n), // Remove editDist(str1, str2, m - 1, n - 1) // Replace );} // Driver program// your code goes herevar str1 = \"sunday\";var str2 = \"saturday\";document.write( editDist(str1, str2, str1.length, str2.length)); </script>",
"e": 9276,
"s": 7934,
"text": null
},
{
"code": null,
"e": 9285,
"s": 9276,
"text": "Output: "
},
{
"code": null,
"e": 9287,
"s": 9285,
"text": "3"
},
{
"code": null,
"e": 9478,
"s": 9287,
"text": "The time complexity of above solution is O(3^n) which is exponential. The worst-case happens when none of characters of two strings match. Below is a recursive call diagram for worst case. "
},
{
"code": null,
"e": 9991,
"s": 9478,
"text": "We can see that many subproblems are solved, again and again, for example, eD(2, 2) is called three times. Since same subproblems are called again, this problem has Overlapping Subproblems property. So Edit Distance problem has both properties (see this and this) of a dynamic programming problem. Like other typical Dynamic Programming(DP) problems, recomputations of same subproblems can be avoided by constructing a temporary array that stores results of subproblems. The bottom-up approach can be found here."
},
{
"code": null,
"e": 10645,
"s": 9991,
"text": "The problem can also be solved using top-down Dynamic Programming and using memoization. In the recursive code, memoization can be used to avoid overlapping problems. There are several repetitive calls which can be computed in O(1) if the value is stored when called for the first time. On observing the recursive code, it is seen that a maximum of two parameters is changing their value on every recursive call. There will be cases when the same recursive call has been called previously. Since two parameters are not constant, a 2-D array can be used to avoid repetitive calls. Hence the return value is stored in some 2-D array. Below are the steps: "
},
{
"code": null,
"e": 10710,
"s": 10645,
"text": "Initialize a 2-D DP array of size m *n with -1 at all the index."
},
{
"code": null,
"e": 10861,
"s": 10710,
"text": "On every recursive call, store the return value at dp[m][n] so that if func(m, n) is called again, it can be answered in O(1) without using recursion."
},
{
"code": null,
"e": 10959,
"s": 10861,
"text": "Check if the recursive call has been visited previously or not by checking the value at dp[m][n]."
},
{
"code": null,
"e": 11012,
"s": 10959,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 11016,
"s": 11012,
"text": "C++"
},
{
"code": null,
"e": 11021,
"s": 11016,
"text": "Java"
},
{
"code": null,
"e": 11029,
"s": 11021,
"text": "Python3"
},
{
"code": null,
"e": 11040,
"s": 11029,
"text": "Javascript"
},
{
"code": "// A memoization program to find minimum number// operations to convert str1 to str2#include <bits/stdc++.h>using namespace std; // Maximum 2-D array column sizeconst int maximum = 1000; // Utility function to find minimum of three numbersint min(int x, int y, int z){ return min(min(x, y), z);} int editDist(string str1, string str2, int m, int n, int dp[][maximum]){ // If first string is empty, the only option is to // insert all characters of second string into first if (m == 0) return n; // If second string is empty, the only option is to // remove all characters of first string if (n == 0) return m; // if the recursive call has been // called previously, then return // the stored value that was calculated // previously if (dp[m - 1][n - 1] != -1) return dp[m - 1][n - 1]; // If last characters of two strings are same, nothing // much to do. Ignore last characters and get count for // remaining strings. // Store the returned value at dp[m-1][n-1] // considering 1-based indexing if (str1[m - 1] == str2[n - 1]) return dp[m - 1][n - 1] = editDist(str1, str2, m - 1, n - 1, dp); // If last characters are not same, consider all three // operations on last character of first string, recursively // compute minimum cost for all three operations and take // minimum of three values. // Store the returned value at dp[m-1][n-1] // considering 1-based indexing return dp[m - 1][n - 1] = 1 + min(editDist(str1, str2, m, n - 1, dp), // Insert editDist(str1, str2, m - 1, n, dp), // Remove editDist(str1, str2, m - 1, n - 1, dp) // Replace );} // Driver Codeint main(){ string str1 = \"sunday\"; string str2 = \"saturday\"; int m = str1.length(); int n = str2.length(); // Declare a dp array which stores // the answer to recursive calls int dp[m][maximum]; // initially all index with -1 memset(dp, -1, sizeof dp); // Function call // memoization and top-down approach cout << editDist(str1, str2, m, n, dp); return 0;}",
"e": 13227,
"s": 11040,
"text": null
},
{
"code": "// A memoization program to find minimum number// operations to convert str1 to str2import java.util.*; class GFG{ // Maximum 2-D array column size static int maximum = 1000; // Utility function to find minimum of three numbers static int min(int x, int y, int z) { return Math.min((Math.min(x, y)), z); } static int editDist(String str1, String str2, int m, int n, int[][] dp) { // If first string is empty, the only option is to // insert all characters of second string into first if (m == 0) return n; // If second string is empty, the only option is to // remove all characters of first string if (n == 0) return m; // if the recursive call has been // called previously, then return // the stored value that was calculated // previously if (dp[m - 1][n - 1] != -1) return dp[m - 1][n - 1]; // If last characters of two strings are same, // nothing much to do. Ignore last characters and // get count for remaining strings. // Store the returned value at dp[m-1][n-1] // considering 1-based indexing if (str1.charAt(m - 1) == str2.charAt(n - 1)) return dp[m - 1][n - 1] = editDist(str1, str2, m - 1, n - 1, dp); // If last characters are not same, consider all // three operations on last character of first // string, recursively compute minimum cost for all // three operations and take minimum of three // values. // Store the returned value at dp[m-1][n-1] // considering 1-based indexing return dp[m - 1][n - 1] = 1 + min(editDist(str1, str2, m, n - 1, dp), // Insert editDist(str1, str2, m - 1, n, dp), // Remove editDist(str1, str2, m - 1, n - 1, dp) // Replace ); } // Driver code public static void main(String[] args) { String str1 = \"sunday\"; String str2 = \"saturday\"; int m = str1.length(); int n = str2.length(); // Declare a dp array which stores // the answer to recursive calls int[][] dp = new int[m][maximum]; for (int i = 0; i < dp.length; i++) Arrays.fill(dp[i], -1); // Function call // memoization and top-down approach System.out.println(editDist(str1, str2, m, n, dp)); }} // This code is contributed by Karandeep Singh",
"e": 15572,
"s": 13227,
"text": null
},
{
"code": "# A memoization program to find minimum number# operations to convert str1 to str2def editDistance(str1, str2, m, n, d = {}): key = m, n # If first string is empty, the only option # is to insert all characters of second # string into first if m == 0: return n # If second string is empty, the only # option is to remove all characters # of first string if n == 0: return m if key in d: return d[key] # If last characters of two strings are same, # nothing much to do. Ignore last characters # and get count for remaining strings. if str1[m - 1] == str2[n - 1]: return editDistance(str1, str2, m - 1, n - 1) # If last characters are not same, consider # all three operations on last character of # first string, recursively compute minimum # cost for all three operations and take # minimum of three values. # Store the returned value at dp[m-1][n-1] # considering 1-based indexing d[key] = 1 + min(editDistance(str1, str2, m, n - 1), # Insert editDistance(str1, str2, m - 1, n), # Remove editDistance(str1, str2, m - 1, n - 1)) # Replace return d[key] # Driver codestr1 = \"sunday\"str2 = \"saturday\" print(editDistance(str1, str2, len(str1), len(str2))) # This code is contributed by puranjanprithu",
"e": 16930,
"s": 15572,
"text": null
},
{
"code": "<script> // A memoization program to find minimum number// operations to convert str1 to str2 // Maximum 2-D array column sizeconst maximum = 1000; // Utility function to find minimum of three numbersfunction min(x, y, z){ return Math.min(Math.min(x, y), z);} function editDist(str1, str2, m, n, dp){ // If first string is empty, the only option is to // insert all characters of second string into first if (m == 0) return n; // If second string is empty, the only option is to // remove all characters of first string if (n == 0) return m; // if the recursive call has been // called previously, then return // the stored value that was calculated // previously if (dp[m - 1][n - 1] != -1) return dp[m - 1][n - 1]; // If last characters of two strings are same, nothing // much to do. Ignore last characters and get count for // remaining strings. // Store the returned value at dp[m-1][n-1] // considering 1-based indexing if (str1[m - 1] == str2[n - 1]) return dp[m - 1][n - 1] = editDist(str1, str2, m - 1, n - 1, dp); // If last characters are not same, consider all three // operations on last character of first string, recursively // compute minimum cost for all three operations and take // minimum of three values. // Store the returned value at dp[m-1][n-1] // considering 1-based indexing return dp[m - 1][n - 1] = 1 + min(editDist(str1, str2, m, n - 1, dp), // Insert editDist(str1, str2, m - 1, n, dp), // Remove editDist(str1, str2, m - 1, n - 1, dp) // Replace );} // Driver Code let str1 = \"sunday\";let str2 = \"saturday\";let m = str1.length;let n = str2.length; // Declare a dp array which stores// the answer to recursive calls// initially all index with -1let dp = new Array(m);for(let i = 0; i < m; i++){ dp[i] = new Array(maximum).fill(-1);} // Function call// memoization and top-down approachdocument.write(editDist(str1, str2, m, n, dp)); // This code is contributed by shinjanpatra </script>",
"e": 19046,
"s": 16930,
"text": null
},
{
"code": null,
"e": 19055,
"s": 19046,
"text": "Output: "
},
{
"code": null,
"e": 19057,
"s": 19055,
"text": "3"
},
{
"code": null,
"e": 19110,
"s": 19057,
"text": "Time Complexity: O(M * N) Auxiliary Space: O(M * N) "
},
{
"code": null,
"e": 19121,
"s": 19110,
"text": "nidhi_biet"
},
{
"code": null,
"e": 19136,
"s": 19121,
"text": "puranjanprithu"
},
{
"code": null,
"e": 19145,
"s": 19136,
"text": "sweetyty"
},
{
"code": null,
"e": 19154,
"s": 19145,
"text": "famously"
},
{
"code": null,
"e": 19168,
"s": 19154,
"text": "karandeep1234"
},
{
"code": null,
"e": 19181,
"s": 19168,
"text": "shinjanpatra"
},
{
"code": null,
"e": 19193,
"s": 19181,
"text": "Memoization"
},
{
"code": null,
"e": 19213,
"s": 19193,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 19221,
"s": 19213,
"text": "Strings"
},
{
"code": null,
"e": 19229,
"s": 19221,
"text": "Strings"
},
{
"code": null,
"e": 19249,
"s": 19229,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 19347,
"s": 19249,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 19374,
"s": 19347,
"text": "Subset Sum Problem | DP-25"
},
{
"code": null,
"e": 19412,
"s": 19374,
"text": "Longest Palindromic Substring | Set 1"
},
{
"code": null,
"e": 19445,
"s": 19412,
"text": "Floyd Warshall Algorithm | DP-16"
},
{
"code": null,
"e": 19513,
"s": 19445,
"text": "Find if there is a path between two vertices in an undirected graph"
},
{
"code": null,
"e": 19548,
"s": 19513,
"text": "Matrix Chain Multiplication | DP-8"
},
{
"code": null,
"e": 19594,
"s": 19548,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 19619,
"s": 19594,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 19679,
"s": 19619,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 19694,
"s": 19679,
"text": "C++ Data Types"
}
] |
Assembly - Arithmetic Instructions
|
The INC instruction is used for incrementing an operand by one. It works on a single operand that can be either in a register or in memory.
The INC instruction has the following syntax −
INC destination
The operand destination could be an 8-bit, 16-bit or 32-bit operand.
INC EBX ; Increments 32-bit register
INC DL ; Increments 8-bit register
INC [count] ; Increments the count variable
The DEC instruction is used for decrementing an operand by one. It works on a single operand that can be either in a register or in memory.
The DEC instruction has the following syntax −
DEC destination
The operand destination could be an 8-bit, 16-bit or 32-bit operand.
segment .data
count dw 0
value db 15
segment .text
inc [count]
dec [value]
mov ebx, count
inc word [ebx]
mov esi, value
dec byte [esi]
The ADD and SUB instructions are used for performing simple addition/subtraction of binary data in byte, word and doubleword size, i.e., for adding or subtracting 8-bit, 16-bit or 32-bit operands, respectively.
The ADD and SUB instructions have the following syntax −
ADD/SUB destination, source
The ADD/SUB instruction can take place between −
Register to register
Memory to register
Register to memory
Register to constant data
Memory to constant data
However, like other instructions, memory-to-memory operations are not possible using ADD/SUB instructions. An ADD or SUB operation sets or clears the overflow and carry flags.
The following example will ask two digits from the user, store the digits in the EAX and EBX register, respectively, add the values, store the result in a memory location 'res' and finally display the result.
SYS_EXIT equ 1
SYS_READ equ 3
SYS_WRITE equ 4
STDIN equ 0
STDOUT equ 1
segment .data
msg1 db "Enter a digit ", 0xA,0xD
len1 equ $- msg1
msg2 db "Please enter a second digit", 0xA,0xD
len2 equ $- msg2
msg3 db "The sum is: "
len3 equ $- msg3
segment .bss
num1 resb 2
num2 resb 2
res resb 1
section .text
global _start ;must be declared for using gcc
_start: ;tell linker entry point
mov eax, SYS_WRITE
mov ebx, STDOUT
mov ecx, msg1
mov edx, len1
int 0x80
mov eax, SYS_READ
mov ebx, STDIN
mov ecx, num1
mov edx, 2
int 0x80
mov eax, SYS_WRITE
mov ebx, STDOUT
mov ecx, msg2
mov edx, len2
int 0x80
mov eax, SYS_READ
mov ebx, STDIN
mov ecx, num2
mov edx, 2
int 0x80
mov eax, SYS_WRITE
mov ebx, STDOUT
mov ecx, msg3
mov edx, len3
int 0x80
; moving the first number to eax register and second number to ebx
; and subtracting ascii '0' to convert it into a decimal number
mov eax, [num1]
sub eax, '0'
mov ebx, [num2]
sub ebx, '0'
; add eax and ebx
add eax, ebx
; add '0' to to convert the sum from decimal to ASCII
add eax, '0'
; storing the sum in memory location res
mov [res], eax
; print the sum
mov eax, SYS_WRITE
mov ebx, STDOUT
mov ecx, res
mov edx, 1
int 0x80
exit:
mov eax, SYS_EXIT
xor ebx, ebx
int 0x80
When the above code is compiled and executed, it produces the following result −
Enter a digit:
3
Please enter a second digit:
4
The sum is:
7
The program with hardcoded variables −
section .text
global _start ;must be declared for using gcc
_start: ;tell linker entry point
mov eax,'3'
sub eax, '0'
mov ebx, '4'
sub ebx, '0'
add eax, ebx
add eax, '0'
mov [sum], eax
mov ecx,msg
mov edx, len
mov ebx,1 ;file descriptor (stdout)
mov eax,4 ;system call number (sys_write)
int 0x80 ;call kernel
mov ecx,sum
mov edx, 1
mov ebx,1 ;file descriptor (stdout)
mov eax,4 ;system call number (sys_write)
int 0x80 ;call kernel
mov eax,1 ;system call number (sys_exit)
int 0x80 ;call kernel
section .data
msg db "The sum is:", 0xA,0xD
len equ $ - msg
segment .bss
sum resb 1
When the above code is compiled and executed, it produces the following result −
The sum is:
7
There are two instructions for multiplying binary data. The MUL (Multiply) instruction handles unsigned data and the IMUL (Integer Multiply) handles signed data. Both instructions affect the Carry and Overflow flag.
The syntax for the MUL/IMUL instructions is as follows −
MUL/IMUL multiplier
Multiplicand in both cases will be in an accumulator, depending upon the size of the multiplicand and the multiplier and the generated product is also stored in two registers depending upon the size of the operands. Following section explains MUL instructions with three different cases −
When two bytes are multiplied −
The multiplicand is in the AL register, and the multiplier is a byte in the memory or in another register. The product is in AX. High-order 8 bits of the product is stored in AH and the low-order 8 bits are stored in AL.
When two one-word values are multiplied −
The multiplicand should be in the AX register, and the multiplier is a word in memory or another register. For example, for an instruction like MUL DX, you must store the multiplier in DX and the multiplicand in AX.
The resultant product is a doubleword, which will need two registers. The high-order (leftmost) portion gets stored in DX and the lower-order (rightmost) portion gets stored in AX.
When two doubleword values are multiplied −
When two doubleword values are multiplied, the multiplicand should be in EAX and the multiplier is a doubleword value stored in memory or in another register. The product generated is stored in the EDX:EAX registers, i.e., the high order 32 bits gets stored in the EDX register and the low order 32-bits are stored in the EAX register.
MOV AL, 10
MOV DL, 25
MUL DL
...
MOV DL, 0FFH ; DL= -1
MOV AL, 0BEH ; AL = -66
IMUL DL
The following example multiplies 3 with 2, and displays the result −
section .text
global _start ;must be declared for using gcc
_start: ;tell linker entry point
mov al,'3'
sub al, '0'
mov bl, '2'
sub bl, '0'
mul bl
add al, '0'
mov [res], al
mov ecx,msg
mov edx, len
mov ebx,1 ;file descriptor (stdout)
mov eax,4 ;system call number (sys_write)
int 0x80 ;call kernel
mov ecx,res
mov edx, 1
mov ebx,1 ;file descriptor (stdout)
mov eax,4 ;system call number (sys_write)
int 0x80 ;call kernel
mov eax,1 ;system call number (sys_exit)
int 0x80 ;call kernel
section .data
msg db "The result is:", 0xA,0xD
len equ $- msg
segment .bss
res resb 1
When the above code is compiled and executed, it produces the following result −
The result is:
6
The division operation generates two elements - a quotient and a remainder. In case of multiplication, overflow does not occur because double-length registers are used to keep the product. However, in case of division, overflow may occur. The processor generates an interrupt if overflow occurs.
The DIV (Divide) instruction is used for unsigned data and the IDIV (Integer Divide) is used for signed data.
The format for the DIV/IDIV instruction −
DIV/IDIV divisor
The dividend is in an accumulator. Both the instructions can work with 8-bit, 16-bit or 32-bit operands. The operation affects all six status flags. Following section explains three cases of division with different operand size −
When the divisor is 1 byte −
The dividend is assumed to be in the AX register (16 bits). After division, the quotient goes to the AL register and the remainder goes to the AH register.
When the divisor is 1 word −
The dividend is assumed to be 32 bits long and in the DX:AX registers. The high-order 16 bits are in DX and the low-order 16 bits are in AX. After division, the 16-bit quotient goes to the AX register and the 16-bit remainder goes to the DX register.
When the divisor is doubleword −
The dividend is assumed to be 64 bits long and in the EDX:EAX registers. The high-order 32 bits are in EDX and the low-order 32 bits are in EAX. After division, the 32-bit quotient goes to the EAX register and the 32-bit remainder goes to the EDX register.
The following example divides 8 with 2. The dividend 8 is stored in the 16-bit AX register and the divisor 2 is stored in the 8-bit BL register.
section .text
global _start ;must be declared for using gcc
_start: ;tell linker entry point
mov ax,'8'
sub ax, '0'
mov bl, '2'
sub bl, '0'
div bl
add ax, '0'
mov [res], ax
mov ecx,msg
mov edx, len
mov ebx,1 ;file descriptor (stdout)
mov eax,4 ;system call number (sys_write)
int 0x80 ;call kernel
mov ecx,res
mov edx, 1
mov ebx,1 ;file descriptor (stdout)
mov eax,4 ;system call number (sys_write)
int 0x80 ;call kernel
mov eax,1 ;system call number (sys_exit)
int 0x80 ;call kernel
section .data
msg db "The result is:", 0xA,0xD
len equ $- msg
segment .bss
res resb 1
When the above code is compiled and executed, it produces the following result −
The result is:
|
[
{
"code": null,
"e": 2359,
"s": 2219,
"text": "The INC instruction is used for incrementing an operand by one. It works on a single operand that can be either in a register or in memory."
},
{
"code": null,
"e": 2406,
"s": 2359,
"text": "The INC instruction has the following syntax −"
},
{
"code": null,
"e": 2423,
"s": 2406,
"text": "INC destination\n"
},
{
"code": null,
"e": 2492,
"s": 2423,
"text": "The operand destination could be an 8-bit, 16-bit or 32-bit operand."
},
{
"code": null,
"e": 2620,
"s": 2492,
"text": "INC EBX\t ; Increments 32-bit register\nINC DL ; Increments 8-bit register\nINC [count] ; Increments the count variable"
},
{
"code": null,
"e": 2760,
"s": 2620,
"text": "The DEC instruction is used for decrementing an operand by one. It works on a single operand that can be either in a register or in memory."
},
{
"code": null,
"e": 2807,
"s": 2760,
"text": "The DEC instruction has the following syntax −"
},
{
"code": null,
"e": 2824,
"s": 2807,
"text": "DEC destination\n"
},
{
"code": null,
"e": 2893,
"s": 2824,
"text": "The operand destination could be an 8-bit, 16-bit or 32-bit operand."
},
{
"code": null,
"e": 3060,
"s": 2893,
"text": "segment .data\n count dw 0\n value db 15\n\t\nsegment .text\n inc [count]\n dec [value]\n\t\n mov ebx, count\n inc word [ebx]\n\t\n mov esi, value\n dec byte [esi]"
},
{
"code": null,
"e": 3271,
"s": 3060,
"text": "The ADD and SUB instructions are used for performing simple addition/subtraction of binary data in byte, word and doubleword size, i.e., for adding or subtracting 8-bit, 16-bit or 32-bit operands, respectively."
},
{
"code": null,
"e": 3328,
"s": 3271,
"text": "The ADD and SUB instructions have the following syntax −"
},
{
"code": null,
"e": 3357,
"s": 3328,
"text": "ADD/SUB\tdestination, source\n"
},
{
"code": null,
"e": 3406,
"s": 3357,
"text": "The ADD/SUB instruction can take place between −"
},
{
"code": null,
"e": 3427,
"s": 3406,
"text": "Register to register"
},
{
"code": null,
"e": 3446,
"s": 3427,
"text": "Memory to register"
},
{
"code": null,
"e": 3465,
"s": 3446,
"text": "Register to memory"
},
{
"code": null,
"e": 3491,
"s": 3465,
"text": "Register to constant data"
},
{
"code": null,
"e": 3515,
"s": 3491,
"text": "Memory to constant data"
},
{
"code": null,
"e": 3691,
"s": 3515,
"text": "However, like other instructions, memory-to-memory operations are not possible using ADD/SUB instructions. An ADD or SUB operation sets or clears the overflow and carry flags."
},
{
"code": null,
"e": 3900,
"s": 3691,
"text": "The following example will ask two digits from the user, store the digits in the EAX and EBX register, respectively, add the values, store the result in a memory location 'res' and finally display the result."
},
{
"code": null,
"e": 5513,
"s": 3900,
"text": "SYS_EXIT equ 1\nSYS_READ equ 3\nSYS_WRITE equ 4\nSTDIN equ 0\nSTDOUT equ 1\n\nsegment .data \n\n msg1 db \"Enter a digit \", 0xA,0xD \n len1 equ $- msg1 \n\n msg2 db \"Please enter a second digit\", 0xA,0xD \n len2 equ $- msg2 \n\n msg3 db \"The sum is: \"\n len3 equ $- msg3\n\nsegment .bss\n\n num1 resb 2 \n num2 resb 2 \n res resb 1 \n\nsection\t.text\n global _start ;must be declared for using gcc\n\t\n_start: ;tell linker entry point\n mov eax, SYS_WRITE \n mov ebx, STDOUT \n mov ecx, msg1 \n mov edx, len1 \n int 0x80 \n\n mov eax, SYS_READ \n mov ebx, STDIN \n mov ecx, num1 \n mov edx, 2\n int 0x80 \n\n mov eax, SYS_WRITE \n mov ebx, STDOUT \n mov ecx, msg2 \n mov edx, len2 \n int 0x80\n\n mov eax, SYS_READ \n mov ebx, STDIN \n mov ecx, num2 \n mov edx, 2\n int 0x80 \n\n mov eax, SYS_WRITE \n mov ebx, STDOUT \n mov ecx, msg3 \n mov edx, len3 \n int 0x80\n\n ; moving the first number to eax register and second number to ebx\n ; and subtracting ascii '0' to convert it into a decimal number\n\t\n mov eax, [num1]\n sub eax, '0'\n\t\n mov ebx, [num2]\n sub ebx, '0'\n\n ; add eax and ebx\n add eax, ebx\n ; add '0' to to convert the sum from decimal to ASCII\n add eax, '0'\n\n ; storing the sum in memory location res\n mov [res], eax\n\n ; print the sum \n mov eax, SYS_WRITE \n mov ebx, STDOUT\n mov ecx, res \n mov edx, 1 \n int 0x80\n\nexit: \n \n mov eax, SYS_EXIT \n xor ebx, ebx \n int 0x80"
},
{
"code": null,
"e": 5594,
"s": 5513,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 5657,
"s": 5594,
"text": "Enter a digit:\n3\nPlease enter a second digit:\n4\nThe sum is:\n7\n"
},
{
"code": null,
"e": 5696,
"s": 5657,
"text": "The program with hardcoded variables −"
},
{
"code": null,
"e": 6391,
"s": 5696,
"text": "section\t.text\n global _start ;must be declared for using gcc\n\t\n_start: ;tell linker entry point\n mov\teax,'3'\n sub eax, '0'\n\t\n mov \tebx, '4'\n sub ebx, '0'\n add \teax, ebx\n add\teax, '0'\n\t\n mov \t[sum], eax\n mov\tecx,msg\t\n mov\tedx, len\n mov\tebx,1\t;file descriptor (stdout)\n mov\teax,4\t;system call number (sys_write)\n int\t0x80\t;call kernel\n\t\n mov\tecx,sum\n mov\tedx, 1\n mov\tebx,1\t;file descriptor (stdout)\n mov\teax,4\t;system call number (sys_write)\n int\t0x80\t;call kernel\n\t\n mov\teax,1\t;system call number (sys_exit)\n int\t0x80\t;call kernel\n\t\nsection .data\n msg db \"The sum is:\", 0xA,0xD \n len equ $ - msg \n segment .bss\n sum resb 1"
},
{
"code": null,
"e": 6472,
"s": 6391,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 6487,
"s": 6472,
"text": "The sum is:\n7\n"
},
{
"code": null,
"e": 6703,
"s": 6487,
"text": "There are two instructions for multiplying binary data. The MUL (Multiply) instruction handles unsigned data and the IMUL (Integer Multiply) handles signed data. Both instructions affect the Carry and Overflow flag."
},
{
"code": null,
"e": 6760,
"s": 6703,
"text": "The syntax for the MUL/IMUL instructions is as follows −"
},
{
"code": null,
"e": 6781,
"s": 6760,
"text": "MUL/IMUL multiplier\n"
},
{
"code": null,
"e": 7070,
"s": 6781,
"text": "Multiplicand in both cases will be in an accumulator, depending upon the size of the multiplicand and the multiplier and the generated product is also stored in two registers depending upon the size of the operands. Following section explains MUL instructions with three different cases −"
},
{
"code": null,
"e": 7102,
"s": 7070,
"text": "When two bytes are multiplied −"
},
{
"code": null,
"e": 7323,
"s": 7102,
"text": "The multiplicand is in the AL register, and the multiplier is a byte in the memory or in another register. The product is in AX. High-order 8 bits of the product is stored in AH and the low-order 8 bits are stored in AL."
},
{
"code": null,
"e": 7365,
"s": 7323,
"text": "When two one-word values are multiplied −"
},
{
"code": null,
"e": 7581,
"s": 7365,
"text": "The multiplicand should be in the AX register, and the multiplier is a word in memory or another register. For example, for an instruction like MUL DX, you must store the multiplier in DX and the multiplicand in AX."
},
{
"code": null,
"e": 7762,
"s": 7581,
"text": "The resultant product is a doubleword, which will need two registers. The high-order (leftmost) portion gets stored in DX and the lower-order (rightmost) portion gets stored in AX."
},
{
"code": null,
"e": 7806,
"s": 7762,
"text": "When two doubleword values are multiplied −"
},
{
"code": null,
"e": 8142,
"s": 7806,
"text": "When two doubleword values are multiplied, the multiplicand should be in EAX and the multiplier is a doubleword value stored in memory or in another register. The product generated is stored in the EDX:EAX registers, i.e., the high order 32 bits gets stored in the EDX register and the low order 32-bits are stored in the EAX register."
},
{
"code": null,
"e": 8229,
"s": 8142,
"text": "MOV AL, 10\nMOV DL, 25\nMUL DL\n...\nMOV DL, 0FFH\t; DL= -1\nMOV AL, 0BEH\t; AL = -66\nIMUL DL"
},
{
"code": null,
"e": 8298,
"s": 8229,
"text": "The following example multiplies 3 with 2, and displays the result −"
},
{
"code": null,
"e": 8971,
"s": 8298,
"text": "section\t.text\n global _start ;must be declared for using gcc\n\t\n_start: ;tell linker entry point\n\n mov\tal,'3'\n sub al, '0'\n\t\n mov \tbl, '2'\n sub bl, '0'\n mul \tbl\n add\tal, '0'\n\t\n mov \t[res], al\n mov\tecx,msg\t\n mov\tedx, len\n mov\tebx,1\t;file descriptor (stdout)\n mov\teax,4\t;system call number (sys_write)\n int\t0x80\t;call kernel\n\t\n mov\tecx,res\n mov\tedx, 1\n mov\tebx,1\t;file descriptor (stdout)\n mov\teax,4\t;system call number (sys_write)\n int\t0x80\t;call kernel\n\t\n mov\teax,1\t;system call number (sys_exit)\n int\t0x80\t;call kernel\n\nsection .data\nmsg db \"The result is:\", 0xA,0xD \nlen equ $- msg \nsegment .bss\nres resb 1"
},
{
"code": null,
"e": 9052,
"s": 8971,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 9070,
"s": 9052,
"text": "The result is:\n6\n"
},
{
"code": null,
"e": 9366,
"s": 9070,
"text": "The division operation generates two elements - a quotient and a remainder. In case of multiplication, overflow does not occur because double-length registers are used to keep the product. However, in case of division, overflow may occur. The processor generates an interrupt if overflow occurs."
},
{
"code": null,
"e": 9476,
"s": 9366,
"text": "The DIV (Divide) instruction is used for unsigned data and the IDIV (Integer Divide) is used for signed data."
},
{
"code": null,
"e": 9518,
"s": 9476,
"text": "The format for the DIV/IDIV instruction −"
},
{
"code": null,
"e": 9536,
"s": 9518,
"text": "DIV/IDIV\tdivisor\n"
},
{
"code": null,
"e": 9766,
"s": 9536,
"text": "The dividend is in an accumulator. Both the instructions can work with 8-bit, 16-bit or 32-bit operands. The operation affects all six status flags. Following section explains three cases of division with different operand size −"
},
{
"code": null,
"e": 9795,
"s": 9766,
"text": "When the divisor is 1 byte −"
},
{
"code": null,
"e": 9951,
"s": 9795,
"text": "The dividend is assumed to be in the AX register (16 bits). After division, the quotient goes to the AL register and the remainder goes to the AH register."
},
{
"code": null,
"e": 9980,
"s": 9951,
"text": "When the divisor is 1 word −"
},
{
"code": null,
"e": 10231,
"s": 9980,
"text": "The dividend is assumed to be 32 bits long and in the DX:AX registers. The high-order 16 bits are in DX and the low-order 16 bits are in AX. After division, the 16-bit quotient goes to the AX register and the 16-bit remainder goes to the DX register."
},
{
"code": null,
"e": 10264,
"s": 10231,
"text": "When the divisor is doubleword −"
},
{
"code": null,
"e": 10521,
"s": 10264,
"text": "The dividend is assumed to be 64 bits long and in the EDX:EAX registers. The high-order 32 bits are in EDX and the low-order 32 bits are in EAX. After division, the 32-bit quotient goes to the EAX register and the 32-bit remainder goes to the EDX register."
},
{
"code": null,
"e": 10666,
"s": 10521,
"text": "The following example divides 8 with 2. The dividend 8 is stored in the 16-bit AX register and the divisor 2 is stored in the 8-bit BL register."
},
{
"code": null,
"e": 11339,
"s": 10666,
"text": "section\t.text\n global _start ;must be declared for using gcc\n\t\n_start: ;tell linker entry point\n mov\tax,'8'\n sub ax, '0'\n\t\n mov \tbl, '2'\n sub bl, '0'\n div \tbl\n add\tax, '0'\n\t\n mov \t[res], ax\n mov\tecx,msg\t\n mov\tedx, len\n mov\tebx,1\t;file descriptor (stdout)\n mov\teax,4\t;system call number (sys_write)\n int\t0x80\t;call kernel\n\t\n mov\tecx,res\n mov\tedx, 1\n mov\tebx,1\t;file descriptor (stdout)\n mov\teax,4\t;system call number (sys_write)\n int\t0x80\t;call kernel\n\t\n mov\teax,1\t;system call number (sys_exit)\n int\t0x80\t;call kernel\n\t\nsection .data\nmsg db \"The result is:\", 0xA,0xD \nlen equ $- msg \nsegment .bss\nres resb 1"
},
{
"code": null,
"e": 11420,
"s": 11339,
"text": "When the above code is compiled and executed, it produces the following result −"
}
] |
The String in Switch Case in Java
|
The introduction of Java 7 enhanced the switch case i.e. it support string as well.
At first, set a string −
String department = "AKD05";
Now, use the same string in switch as shown below −
switch(department)
Now, check for every string using case as we normally do while using SWITCH CASE. Following is an example to implement String in Switch Case −
public class Demo {
public static void main(String[] args) {
String department = "AKD05";
switch(department) {
case "AKD01":
System.out.println("Finance");
break;
case "AKD02":
System.out.println("Sales");
break;
case "AKD03":
System.out.println("Production");
break;
case "AKD04":
System.out.println("Marketing");
break;
case "AKD05":
System.out.println("Operations");
break;
default:
System.out.println("None!");
}
}
}
Operations
|
[
{
"code": null,
"e": 1271,
"s": 1187,
"text": "The introduction of Java 7 enhanced the switch case i.e. it support string as well."
},
{
"code": null,
"e": 1296,
"s": 1271,
"text": "At first, set a string −"
},
{
"code": null,
"e": 1325,
"s": 1296,
"text": "String department = \"AKD05\";"
},
{
"code": null,
"e": 1377,
"s": 1325,
"text": "Now, use the same string in switch as shown below −"
},
{
"code": null,
"e": 1396,
"s": 1377,
"text": "switch(department)"
},
{
"code": null,
"e": 1539,
"s": 1396,
"text": "Now, check for every string using case as we normally do while using SWITCH CASE. Following is an example to implement String in Switch Case −"
},
{
"code": null,
"e": 2170,
"s": 1539,
"text": "public class Demo {\n public static void main(String[] args) {\n String department = \"AKD05\";\n switch(department) {\n case \"AKD01\":\n System.out.println(\"Finance\");\n break;\n case \"AKD02\":\n System.out.println(\"Sales\");\n break;\n case \"AKD03\":\n System.out.println(\"Production\");\n break;\n case \"AKD04\":\n System.out.println(\"Marketing\");\n break;\n case \"AKD05\":\n System.out.println(\"Operations\");\n break;\n default:\n System.out.println(\"None!\");\n }\n }\n}"
},
{
"code": null,
"e": 2181,
"s": 2170,
"text": "Operations"
}
] |
How to strip out HTML tags from a string using JavaScript ?
|
19 Jun, 2020
To strip out all the HTML tags from a string there are lots of procedures in JavaScript. In order to strip out tags we can use replace() function and can also use .textContent property, .innerText property from HTML DOM. HTML tags are of two types opening tag and closing tag.
Opening tag: It starts with a ‘<‘, followed by an HTML keyword and ends with a ‘>‘. <html>, <br>, <title> are some examples of HTML opening tags.
Closing tag: It starts with a ‘</‘, followed by an HTML keyword and ends with a ‘>‘.</html>, </title> are examples of HTML closing tags.
Below examples illustrate the both approaches:
Example 1: The ‘<‘, ‘</’, ‘>’, can be used to identify a word as an HTML tag in a string. The following examples show how to strip out HTML tags using replace() function and a regular expression, which identifies an HTML tag in the input string. A regular expression is a better way to find the HTML tags and remove them easily.
Program: In JavaScript, the following code strips a string of the HTML tags.<script>function removeTags(str) { if ((str===null) || (str==='')) return false; else str = str.toString(); // Regular expression to identify HTML tags in // the input string. Replacing the identified // HTML tag with a null string. return str.replace( /(<([^>]+)>)/ig, '');}document.write(removeTags( '<html>Welcome to GeeksforGeeks.</html>'));;</script>
<script>function removeTags(str) { if ((str===null) || (str==='')) return false; else str = str.toString(); // Regular expression to identify HTML tags in // the input string. Replacing the identified // HTML tag with a null string. return str.replace( /(<([^>]+)>)/ig, '');}document.write(removeTags( '<html>Welcome to GeeksforGeeks.</html>'));;</script>
Output:Welcome to GeeksforGeeks.
Welcome to GeeksforGeeks.
Example 2: The .textContent property returns the text content of the specified node and all its descendants. The .innerText property do the same thing as .textContent property.
Program: In JavaScript, the following code strips a string of the HTML tags.<script> // HTML tags contain text var html = "<p>A Computer Science " + "Portal for Geeks</p>"; var div = document.createElement("div"); div.innerHTML = html; var text = div.textContent || div.innerText || ""; document.write(text)</script>
<script> // HTML tags contain text var html = "<p>A Computer Science " + "Portal for Geeks</p>"; var div = document.createElement("div"); div.innerHTML = html; var text = div.textContent || div.innerText || ""; document.write(text)</script>
Output:A Computer Science Portal for Geeks
A Computer Science Portal for Geeks
JavaScript-Misc
Picked
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
How to append HTML code to a div using JavaScript ?
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Jun, 2020"
},
{
"code": null,
"e": 305,
"s": 28,
"text": "To strip out all the HTML tags from a string there are lots of procedures in JavaScript. In order to strip out tags we can use replace() function and can also use .textContent property, .innerText property from HTML DOM. HTML tags are of two types opening tag and closing tag."
},
{
"code": null,
"e": 451,
"s": 305,
"text": "Opening tag: It starts with a ‘<‘, followed by an HTML keyword and ends with a ‘>‘. <html>, <br>, <title> are some examples of HTML opening tags."
},
{
"code": null,
"e": 588,
"s": 451,
"text": "Closing tag: It starts with a ‘</‘, followed by an HTML keyword and ends with a ‘>‘.</html>, </title> are examples of HTML closing tags."
},
{
"code": null,
"e": 635,
"s": 588,
"text": "Below examples illustrate the both approaches:"
},
{
"code": null,
"e": 964,
"s": 635,
"text": "Example 1: The ‘<‘, ‘</’, ‘>’, can be used to identify a word as an HTML tag in a string. The following examples show how to strip out HTML tags using replace() function and a regular expression, which identifies an HTML tag in the input string. A regular expression is a better way to find the HTML tags and remove them easily."
},
{
"code": null,
"e": 1463,
"s": 964,
"text": "Program: In JavaScript, the following code strips a string of the HTML tags.<script>function removeTags(str) { if ((str===null) || (str==='')) return false; else str = str.toString(); // Regular expression to identify HTML tags in // the input string. Replacing the identified // HTML tag with a null string. return str.replace( /(<([^>]+)>)/ig, '');}document.write(removeTags( '<html>Welcome to GeeksforGeeks.</html>'));;</script> "
},
{
"code": "<script>function removeTags(str) { if ((str===null) || (str==='')) return false; else str = str.toString(); // Regular expression to identify HTML tags in // the input string. Replacing the identified // HTML tag with a null string. return str.replace( /(<([^>]+)>)/ig, '');}document.write(removeTags( '<html>Welcome to GeeksforGeeks.</html>'));;</script> ",
"e": 1886,
"s": 1463,
"text": null
},
{
"code": null,
"e": 1919,
"s": 1886,
"text": "Output:Welcome to GeeksforGeeks."
},
{
"code": null,
"e": 1945,
"s": 1919,
"text": "Welcome to GeeksforGeeks."
},
{
"code": null,
"e": 2122,
"s": 1945,
"text": "Example 2: The .textContent property returns the text content of the specified node and all its descendants. The .innerText property do the same thing as .textContent property."
},
{
"code": null,
"e": 2471,
"s": 2122,
"text": "Program: In JavaScript, the following code strips a string of the HTML tags.<script> // HTML tags contain text var html = \"<p>A Computer Science \" + \"Portal for Geeks</p>\"; var div = document.createElement(\"div\"); div.innerHTML = html; var text = div.textContent || div.innerText || \"\"; document.write(text)</script>"
},
{
"code": "<script> // HTML tags contain text var html = \"<p>A Computer Science \" + \"Portal for Geeks</p>\"; var div = document.createElement(\"div\"); div.innerHTML = html; var text = div.textContent || div.innerText || \"\"; document.write(text)</script>",
"e": 2744,
"s": 2471,
"text": null
},
{
"code": null,
"e": 2787,
"s": 2744,
"text": "Output:A Computer Science Portal for Geeks"
},
{
"code": null,
"e": 2823,
"s": 2787,
"text": "A Computer Science Portal for Geeks"
},
{
"code": null,
"e": 2839,
"s": 2823,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 2846,
"s": 2839,
"text": "Picked"
},
{
"code": null,
"e": 2857,
"s": 2846,
"text": "JavaScript"
},
{
"code": null,
"e": 2874,
"s": 2857,
"text": "Web Technologies"
},
{
"code": null,
"e": 2901,
"s": 2874,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 2999,
"s": 2901,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3060,
"s": 2999,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3132,
"s": 3060,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 3172,
"s": 3132,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 3213,
"s": 3172,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 3265,
"s": 3213,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 3298,
"s": 3265,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 3360,
"s": 3298,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3421,
"s": 3360,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3471,
"s": 3421,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
How to dynamically get the content height of a div using AngularJS ?
|
26 Jul, 2021
The content height of a div can dynamically get using clientHeight and scrollHeight properties depending upon the user requirement. If a user wants to know the space required by actual displayed content including the space taken by padding but not including the scrollbars, margins, or borders, then the user can use any of the following procedures that will return the height of the entire content of an element.
Using Element.clientHeight property
Using Element.scrollHeight property
Example 1: Content Height of div using clientHeight property will return the height of the entire content of an element.
HTML
<!DOCTYPE html><html> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> </script> <style> #div1 { height: 100px; width: 300px; border: 2px solid black; overflow: scroll; } h1 { color: green; } </style></head> <body> <center> <h1>GeeksforGeeks</h1> <h3>Getting Content height</h3> <div id="div1"> Calculate content height of a div on GeeksforGeek. GeeksforGeeks is a computer science portal which helps students to learn various programming language and master data structures and algorithms. There are various courses available to learn new skills. </div> <br> <button onclick="contentheight()"> Content height of Div </button> <p id="p1"></p> </center> <script> function contentheight() { var ans = "Content-height: " + angular.element(document .getElementById("div1").clientHeight) + "px<br>"; document.getElementById("p1").innerHTML = ans; } </script></body> </html>
Output:
Before Click on the button:
After Click on the button:
Example 2: Content Height of div using scrollHeight property will return the height of the entire content of an element.
HTML
<!DOCTYPE html><html> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> </script> <style> #div1 { height: 100px; width: 300px; border: 2px solid black; overflow: scroll; } h1 { color: green; } </style></head> <body> <center> <h1>GeeksforGeeks</h1> <h3>Getting Content height</h3> <div id="div1"> Calculate content height of a div on GeeksforGeek. GeeksforGeeks is a computer science portal which helps students to learn various programming language and master data structures and algorithms. There are various courses available to learn new skills. </div> <br> <button onclick="contentheight()"> Content height of Div </button> <p id="p1"></p> </center> <script> function contentheight() { var ans = "Content-height: " + angular.element(document .getElementById("div1").scrollHeight) + "px<br>"; document.getElementById("p1").innerHTML = ans; } </script></body> </html>
Output:
Before Click on the button:
After Click on the button:
sweetyty
AngularJS-Misc
CSS-Misc
HTML-Misc
JavaScript-Misc
AngularJS
CSS
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": "\n26 Jul, 2021"
},
{
"code": null,
"e": 442,
"s": 28,
"text": "The content height of a div can dynamically get using clientHeight and scrollHeight properties depending upon the user requirement. If a user wants to know the space required by actual displayed content including the space taken by padding but not including the scrollbars, margins, or borders, then the user can use any of the following procedures that will return the height of the entire content of an element."
},
{
"code": null,
"e": 478,
"s": 442,
"text": "Using Element.clientHeight property"
},
{
"code": null,
"e": 514,
"s": 478,
"text": "Using Element.scrollHeight property"
},
{
"code": null,
"e": 635,
"s": 514,
"text": "Example 1: Content Height of div using clientHeight property will return the height of the entire content of an element."
},
{
"code": null,
"e": 640,
"s": 635,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js\"> </script> <style> #div1 { height: 100px; width: 300px; border: 2px solid black; overflow: scroll; } h1 { color: green; } </style></head> <body> <center> <h1>GeeksforGeeks</h1> <h3>Getting Content height</h3> <div id=\"div1\"> Calculate content height of a div on GeeksforGeek. GeeksforGeeks is a computer science portal which helps students to learn various programming language and master data structures and algorithms. There are various courses available to learn new skills. </div> <br> <button onclick=\"contentheight()\"> Content height of Div </button> <p id=\"p1\"></p> </center> <script> function contentheight() { var ans = \"Content-height: \" + angular.element(document .getElementById(\"div1\").clientHeight) + \"px<br>\"; document.getElementById(\"p1\").innerHTML = ans; } </script></body> </html>",
"e": 1904,
"s": 640,
"text": null
},
{
"code": null,
"e": 1912,
"s": 1904,
"text": "Output:"
},
{
"code": null,
"e": 1940,
"s": 1912,
"text": "Before Click on the button:"
},
{
"code": null,
"e": 1969,
"s": 1942,
"text": "After Click on the button:"
},
{
"code": null,
"e": 2092,
"s": 1971,
"text": "Example 2: Content Height of div using scrollHeight property will return the height of the entire content of an element."
},
{
"code": null,
"e": 2097,
"s": 2092,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js\"> </script> <style> #div1 { height: 100px; width: 300px; border: 2px solid black; overflow: scroll; } h1 { color: green; } </style></head> <body> <center> <h1>GeeksforGeeks</h1> <h3>Getting Content height</h3> <div id=\"div1\"> Calculate content height of a div on GeeksforGeek. GeeksforGeeks is a computer science portal which helps students to learn various programming language and master data structures and algorithms. There are various courses available to learn new skills. </div> <br> <button onclick=\"contentheight()\"> Content height of Div </button> <p id=\"p1\"></p> </center> <script> function contentheight() { var ans = \"Content-height: \" + angular.element(document .getElementById(\"div1\").scrollHeight) + \"px<br>\"; document.getElementById(\"p1\").innerHTML = ans; } </script></body> </html>",
"e": 3358,
"s": 2097,
"text": null
},
{
"code": null,
"e": 3366,
"s": 3358,
"text": "Output:"
},
{
"code": null,
"e": 3394,
"s": 3366,
"text": "Before Click on the button:"
},
{
"code": null,
"e": 3423,
"s": 3396,
"text": "After Click on the button:"
},
{
"code": null,
"e": 3434,
"s": 3425,
"text": "sweetyty"
},
{
"code": null,
"e": 3449,
"s": 3434,
"text": "AngularJS-Misc"
},
{
"code": null,
"e": 3458,
"s": 3449,
"text": "CSS-Misc"
},
{
"code": null,
"e": 3468,
"s": 3458,
"text": "HTML-Misc"
},
{
"code": null,
"e": 3484,
"s": 3468,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 3494,
"s": 3484,
"text": "AngularJS"
},
{
"code": null,
"e": 3498,
"s": 3494,
"text": "CSS"
},
{
"code": null,
"e": 3503,
"s": 3498,
"text": "HTML"
},
{
"code": null,
"e": 3514,
"s": 3503,
"text": "JavaScript"
},
{
"code": null,
"e": 3531,
"s": 3514,
"text": "Web Technologies"
},
{
"code": null,
"e": 3536,
"s": 3531,
"text": "HTML"
}
] |
Ruby | Time rfc2822 function
|
07 Jan, 2020
Time#rfc2822() : rfc2822() is a Time class method which returns the string which represents the time as date-time defined by RFC 2822Format:
day-of-week, DD month-name CCYY hh:mm:ss zone
Syntax: Time.rfc2822()
Parameter: Time values
Return: the string which represents the time as date-time defined by RFC 2822
Example #1 :
# Ruby code for Time.rfc2822() method # loading libraryrequire 'time' # declaring time a = Time.new(2019) # declaring timeb = Time.new(2019, 10) # declaring timec = Time.new(2019, 12, 31) # Time puts "Time a : #{a}\n\n"puts "Time b : #{b}\n\n"puts "Time c : #{c}\n\n\n\n" # rfc2822 form puts "Time a rfc2822 form : #{a.rfc2822}\n\n"puts "Time b rfc2822 form : #{b.rfc2822}\n\n"puts "Time c rfc2822 form : #{c.rfc2822}\n\n"
Output :
Time a : 2019-01-01 00:00:00 +0100
Time b : 2019-10-01 00:00:00 +0200
Time c : 2019-12-31 00:00:00 +0100
Time a rfc2822 form : 3600
Time b rfc2822 form : 7200
Time c rfc2822 form : 3600
Example #2 :
# Ruby code for Time.rfc2822() method # loading libraryrequire 'time' # declaring time a = Time.now # declaring timeb = Time.new(1000, 10, 10) # declaring timec = Time.new(2020, 12) # Time puts "Time a : #{a}\n\n"puts "Time b : #{b}\n\n"puts "Time c : #{c}\n\n\n\n" # rfc2822 form puts "Time a rfc2822 form : #{a.rfc2822}\n\n"puts "Time b rfc2822 form : #{b.rfc2822}\n\n"puts "Time c rfc2822 form : #{c.rfc2822}\n\n"
Output :
Time a : 2019-08-27 04:05:51 +0200
Time b : 1000-10-10 00:00:00 +0053
Time c : 2020-12-01 00:00:00 +0100
Time a rfc2822 form : Tue, 27 Aug 2019 04:05:51 +0200
Time b rfc2822 form : Fri, 10 Oct 1000 00:00:00 +0053
Time c rfc2822 form : Tue, 01 Dec 2020 00:00:00 +0100
Ruby Time-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": "\n07 Jan, 2020"
},
{
"code": null,
"e": 169,
"s": 28,
"text": "Time#rfc2822() : rfc2822() is a Time class method which returns the string which represents the time as date-time defined by RFC 2822Format:"
},
{
"code": null,
"e": 215,
"s": 169,
"text": "day-of-week, DD month-name CCYY hh:mm:ss zone"
},
{
"code": null,
"e": 238,
"s": 215,
"text": "Syntax: Time.rfc2822()"
},
{
"code": null,
"e": 261,
"s": 238,
"text": "Parameter: Time values"
},
{
"code": null,
"e": 339,
"s": 261,
"text": "Return: the string which represents the time as date-time defined by RFC 2822"
},
{
"code": null,
"e": 352,
"s": 339,
"text": "Example #1 :"
},
{
"code": "# Ruby code for Time.rfc2822() method # loading libraryrequire 'time' # declaring time a = Time.new(2019) # declaring timeb = Time.new(2019, 10) # declaring timec = Time.new(2019, 12, 31) # Time puts \"Time a : #{a}\\n\\n\"puts \"Time b : #{b}\\n\\n\"puts \"Time c : #{c}\\n\\n\\n\\n\" # rfc2822 form puts \"Time a rfc2822 form : #{a.rfc2822}\\n\\n\"puts \"Time b rfc2822 form : #{b.rfc2822}\\n\\n\"puts \"Time c rfc2822 form : #{c.rfc2822}\\n\\n\"",
"e": 783,
"s": 352,
"text": null
},
{
"code": null,
"e": 792,
"s": 783,
"text": "Output :"
},
{
"code": null,
"e": 987,
"s": 792,
"text": "Time a : 2019-01-01 00:00:00 +0100\n\nTime b : 2019-10-01 00:00:00 +0200\n\nTime c : 2019-12-31 00:00:00 +0100\n\n\n\nTime a rfc2822 form : 3600\n\nTime b rfc2822 form : 7200\n\nTime c rfc2822 form : 3600\n\n"
},
{
"code": null,
"e": 1000,
"s": 987,
"text": "Example #2 :"
},
{
"code": "# Ruby code for Time.rfc2822() method # loading libraryrequire 'time' # declaring time a = Time.now # declaring timeb = Time.new(1000, 10, 10) # declaring timec = Time.new(2020, 12) # Time puts \"Time a : #{a}\\n\\n\"puts \"Time b : #{b}\\n\\n\"puts \"Time c : #{c}\\n\\n\\n\\n\" # rfc2822 form puts \"Time a rfc2822 form : #{a.rfc2822}\\n\\n\"puts \"Time b rfc2822 form : #{b.rfc2822}\\n\\n\"puts \"Time c rfc2822 form : #{c.rfc2822}\\n\\n\"",
"e": 1425,
"s": 1000,
"text": null
},
{
"code": null,
"e": 1434,
"s": 1425,
"text": "Output :"
},
{
"code": null,
"e": 1710,
"s": 1434,
"text": "Time a : 2019-08-27 04:05:51 +0200\n\nTime b : 1000-10-10 00:00:00 +0053\n\nTime c : 2020-12-01 00:00:00 +0100\n\n\n\nTime a rfc2822 form : Tue, 27 Aug 2019 04:05:51 +0200\n\nTime b rfc2822 form : Fri, 10 Oct 1000 00:00:00 +0053\n\nTime c rfc2822 form : Tue, 01 Dec 2020 00:00:00 +0100\n\n"
},
{
"code": null,
"e": 1726,
"s": 1710,
"text": "Ruby Time-class"
},
{
"code": null,
"e": 1739,
"s": 1726,
"text": "Ruby-Methods"
},
{
"code": null,
"e": 1744,
"s": 1739,
"text": "Ruby"
},
{
"code": null,
"e": 1842,
"s": 1744,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1888,
"s": 1842,
"text": "How to Make a Custom Array of Hashes in Ruby?"
},
{
"code": null,
"e": 1931,
"s": 1888,
"text": "Ruby | Enumerator each_with_index function"
},
{
"code": null,
"e": 1975,
"s": 1931,
"text": "Ruby | unless Statement and unless Modifier"
},
{
"code": null,
"e": 2002,
"s": 1975,
"text": "Ruby on Rails Introduction"
},
{
"code": null,
"e": 2030,
"s": 2002,
"text": "Ruby | String concat Method"
},
{
"code": null,
"e": 2072,
"s": 2030,
"text": "Ruby | Array class find_index() operation"
},
{
"code": null,
"e": 2091,
"s": 2072,
"text": "Ruby For Beginners"
},
{
"code": null,
"e": 2121,
"s": 2091,
"text": "Ruby | Array shift() function"
}
] |
Functions in LISP
|
06 Oct, 2021
A function is a set of statements that takes some input, performs some tasks, and produces the result. Through functions, we can split up a huge task into many smaller functions. They also help in avoiding the repetition of code as we can call the same function for different inputs.
Functions in LISP are defined using the DEFUN macro. The basic syntax looks like this :
(defun function-name (parameters)
"Documentation string"
body-of-function
)
Name of Function: You can use any kind of symbol as a function name, but usually function names includes only characters and hyphens. In LISP instead of using underscore in naming, hyphens are considered as naming conventions. For example, we write calc-average instead of calc_average or calcAverage.
Parameters: These are the variables that are used to retain the arguments that are passed to the function when it is called. These parameters are optional, if a function doesn’t have any parameters, then that list is empty written as ( )
Documentation String: It is a string literal that is used to describes what a particular function is intended to do.
Body of function: The function body consists of LISP expressions which are evaluated in order when the function is called. Usually, the value of the last expression is returned as the value of the function, but through the help of RETURN-FORM which is a special operator, we can return the value of the function from anywhere in it.
1. Let’s create a function named hello-world that doesn’t take any parameters and returns a hello world string.
Lisp
(defun hello-world () (format t "Hello, World!"))(hello-world)
Output:
Hello, World!
2. Function to add two integers
Here we have created a function named add-two-number which takes two arguments n1 and n2. A Documentation string is used to describe the work done by this function and whatever the value is return by calling the + eventually becomes the return value of add-two-number.
Lisp
(defun add-two-number (n1 n2) "Adds two numbers" (+ n1 n2))(write(add-two-number 10 20))
Output:
30
3. Now let’s create a simple function that takes an optional string argument and return the Welcome string :
In the function welcome-to-gfg, we have one optional parameter name. To define any optional parameter add the symbol: &optional before the name of the parameter which is optional.We have set its default value to Sandeep, So if the user calls the welcome-to-gfg function without any arguments it prints “Welcome “Sandeep” to Geeks for geeks!” or if any argument is passed while calling the function it will return the string which contains the argument value passed while calling the function.(terpri) is used to print a new line
Lisp
(defun welcome-to-gfg (&optional (name "Sandeep")) (format t "Welcome ~S to Geeks for geeks!" name))(welcome-to-gfg)(terpri)(welcome-to-gfg "UserName")
Output:
Welcome "Sandeep" to Geeks for geeks!
Welcome "UserName" to Geeks for geeks!
LISP-Basics
LISP-Functions
Picked
LISP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Property Lists in LISP
Arrays in LISP
Numbers in LISP
Do Construct in LISP
Naming Conventions in LISP
File Handling in LISP
Basic Syntax in LISP
Packages in LISP
Symbols in LISP
Vectors in LISP
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n06 Oct, 2021"
},
{
"code": null,
"e": 338,
"s": 54,
"text": "A function is a set of statements that takes some input, performs some tasks, and produces the result. Through functions, we can split up a huge task into many smaller functions. They also help in avoiding the repetition of code as we can call the same function for different inputs."
},
{
"code": null,
"e": 427,
"s": 338,
"text": "Functions in LISP are defined using the DEFUN macro. The basic syntax looks like this : "
},
{
"code": null,
"e": 507,
"s": 427,
"text": "(defun function-name (parameters)\n \"Documentation string\"\n body-of-function\n)"
},
{
"code": null,
"e": 809,
"s": 507,
"text": "Name of Function: You can use any kind of symbol as a function name, but usually function names includes only characters and hyphens. In LISP instead of using underscore in naming, hyphens are considered as naming conventions. For example, we write calc-average instead of calc_average or calcAverage."
},
{
"code": null,
"e": 1048,
"s": 809,
"text": "Parameters: These are the variables that are used to retain the arguments that are passed to the function when it is called. These parameters are optional, if a function doesn’t have any parameters, then that list is empty written as ( ) "
},
{
"code": null,
"e": 1165,
"s": 1048,
"text": "Documentation String: It is a string literal that is used to describes what a particular function is intended to do."
},
{
"code": null,
"e": 1498,
"s": 1165,
"text": "Body of function: The function body consists of LISP expressions which are evaluated in order when the function is called. Usually, the value of the last expression is returned as the value of the function, but through the help of RETURN-FORM which is a special operator, we can return the value of the function from anywhere in it."
},
{
"code": null,
"e": 1610,
"s": 1498,
"text": "1. Let’s create a function named hello-world that doesn’t take any parameters and returns a hello world string."
},
{
"code": null,
"e": 1615,
"s": 1610,
"text": "Lisp"
},
{
"code": "(defun hello-world () (format t \"Hello, World!\"))(hello-world)",
"e": 1680,
"s": 1615,
"text": null
},
{
"code": null,
"e": 1688,
"s": 1680,
"text": "Output:"
},
{
"code": null,
"e": 1702,
"s": 1688,
"text": "Hello, World!"
},
{
"code": null,
"e": 1734,
"s": 1702,
"text": "2. Function to add two integers"
},
{
"code": null,
"e": 2003,
"s": 1734,
"text": "Here we have created a function named add-two-number which takes two arguments n1 and n2. A Documentation string is used to describe the work done by this function and whatever the value is return by calling the + eventually becomes the return value of add-two-number."
},
{
"code": null,
"e": 2008,
"s": 2003,
"text": "Lisp"
},
{
"code": "(defun add-two-number (n1 n2) \"Adds two numbers\" (+ n1 n2))(write(add-two-number 10 20))",
"e": 2099,
"s": 2008,
"text": null
},
{
"code": null,
"e": 2107,
"s": 2099,
"text": "Output:"
},
{
"code": null,
"e": 2110,
"s": 2107,
"text": "30"
},
{
"code": null,
"e": 2220,
"s": 2110,
"text": "3. Now let’s create a simple function that takes an optional string argument and return the Welcome string : "
},
{
"code": null,
"e": 2750,
"s": 2220,
"text": "In the function welcome-to-gfg, we have one optional parameter name. To define any optional parameter add the symbol: &optional before the name of the parameter which is optional.We have set its default value to Sandeep, So if the user calls the welcome-to-gfg function without any arguments it prints “Welcome “Sandeep” to Geeks for geeks!” or if any argument is passed while calling the function it will return the string which contains the argument value passed while calling the function.(terpri) is used to print a new line"
},
{
"code": null,
"e": 2755,
"s": 2750,
"text": "Lisp"
},
{
"code": "(defun welcome-to-gfg (&optional (name \"Sandeep\")) (format t \"Welcome ~S to Geeks for geeks!\" name))(welcome-to-gfg)(terpri)(welcome-to-gfg \"UserName\")",
"e": 2908,
"s": 2755,
"text": null
},
{
"code": null,
"e": 2917,
"s": 2908,
"text": "Output: "
},
{
"code": null,
"e": 2994,
"s": 2917,
"text": "Welcome \"Sandeep\" to Geeks for geeks!\nWelcome \"UserName\" to Geeks for geeks!"
},
{
"code": null,
"e": 3006,
"s": 2994,
"text": "LISP-Basics"
},
{
"code": null,
"e": 3021,
"s": 3006,
"text": "LISP-Functions"
},
{
"code": null,
"e": 3028,
"s": 3021,
"text": "Picked"
},
{
"code": null,
"e": 3033,
"s": 3028,
"text": "LISP"
},
{
"code": null,
"e": 3131,
"s": 3033,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3154,
"s": 3131,
"text": "Property Lists in LISP"
},
{
"code": null,
"e": 3169,
"s": 3154,
"text": "Arrays in LISP"
},
{
"code": null,
"e": 3185,
"s": 3169,
"text": "Numbers in LISP"
},
{
"code": null,
"e": 3206,
"s": 3185,
"text": "Do Construct in LISP"
},
{
"code": null,
"e": 3233,
"s": 3206,
"text": "Naming Conventions in LISP"
},
{
"code": null,
"e": 3255,
"s": 3233,
"text": "File Handling in LISP"
},
{
"code": null,
"e": 3276,
"s": 3255,
"text": "Basic Syntax in LISP"
},
{
"code": null,
"e": 3293,
"s": 3276,
"text": "Packages in LISP"
},
{
"code": null,
"e": 3309,
"s": 3293,
"text": "Symbols in LISP"
}
] |
Event handler in Angular 6+
|
26 Oct, 2020
Introduction:
In Angular 6, event handling is used to hear and capture all the events like clicks, mouse movements, keystrokes and etc. It is an important feature that is present in Angular and it is used in every project irrespective of its size.
Syntax:
<HTML element (event) > = function name()>
Explanation of Syntax:
HTML elements can be used like <button> tag, input tag and etc.
In events, we can use many events that are present like (click), (change) and etc.
We need to give a function name in strings and we need to write the implementation in the ts file.
According to the above example declare an event handler with any of the key events in the HTML file.
In ts file write the implementation of the function according to the requirement.
Below two examples where we used different events to use the concept.
The one is (change) event and the second one is (click).
Example 1: Using change:
app.component.html:
<input (change)="displayValue($event)"><p> Entered Data is : {{data}}</p>
app.component.ts:
import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { data:String = ''; displayValue(event){ this.data = event.target.value; } }
app.module.ts:
import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { FormsModule } from '@angular/forms'; import { AppComponent } from './app.component'; @NgModule({ imports: [ BrowserModule, FormsModule ], declarations: [ AppComponent ], bootstrap: [ AppComponent ], providers: []})export class AppModule { }
Output:
Example 2: Using onclick:
app.component.html:
<div> <button (click)="handleClick()"> Tap Here to Display and Hide the Company name </button></div><br><div *ngIf="toDisplay" class="data"> <div class="centered"> {{name}} </div></div>
app.component.ts:
import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['app.component.scss']})export class AppComponent { name: string = ''; toDisplay =false; handleClick() { this.toDisplay = !this.toDisplay this.name = 'GeeksForGeeks' } }
app.module.ts:
import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { FormsModule } from '@angular/forms'; import { AppComponent } from './app.component'; @NgModule({ imports: [ BrowserModule, FormsModule ], declarations: [ AppComponent ], bootstrap: [ AppComponent ], providers: []})export class AppModule { }
Output:
Before clicking the icon:
After clicking the icon:
AngularJS-Basics
Picked
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Auth Guards in Angular 9/10/11
Routing in Angular 9/10
How to bundle an Angular app for production?
What is AOT and JIT Compiler in Angular ?
Angular PrimeNG Dropdown Component
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Oct, 2020"
},
{
"code": null,
"e": 42,
"s": 28,
"text": "Introduction:"
},
{
"code": null,
"e": 276,
"s": 42,
"text": "In Angular 6, event handling is used to hear and capture all the events like clicks, mouse movements, keystrokes and etc. It is an important feature that is present in Angular and it is used in every project irrespective of its size."
},
{
"code": null,
"e": 284,
"s": 276,
"text": "Syntax:"
},
{
"code": "<HTML element (event) > = function name()>",
"e": 328,
"s": 284,
"text": null
},
{
"code": null,
"e": 351,
"s": 328,
"text": "Explanation of Syntax:"
},
{
"code": null,
"e": 415,
"s": 351,
"text": "HTML elements can be used like <button> tag, input tag and etc."
},
{
"code": null,
"e": 498,
"s": 415,
"text": "In events, we can use many events that are present like (click), (change) and etc."
},
{
"code": null,
"e": 597,
"s": 498,
"text": "We need to give a function name in strings and we need to write the implementation in the ts file."
},
{
"code": null,
"e": 698,
"s": 597,
"text": "According to the above example declare an event handler with any of the key events in the HTML file."
},
{
"code": null,
"e": 780,
"s": 698,
"text": "In ts file write the implementation of the function according to the requirement."
},
{
"code": null,
"e": 850,
"s": 780,
"text": "Below two examples where we used different events to use the concept."
},
{
"code": null,
"e": 907,
"s": 850,
"text": "The one is (change) event and the second one is (click)."
},
{
"code": null,
"e": 932,
"s": 907,
"text": "Example 1: Using change:"
},
{
"code": null,
"e": 952,
"s": 932,
"text": "app.component.html:"
},
{
"code": "<input (change)=\"displayValue($event)\"><p> Entered Data is : {{data}}</p>",
"e": 1026,
"s": 952,
"text": null
},
{
"code": null,
"e": 1044,
"s": 1026,
"text": "app.component.ts:"
},
{
"code": "import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { data:String = ''; displayValue(event){ this.data = event.target.value; } }",
"e": 1351,
"s": 1044,
"text": null
},
{
"code": null,
"e": 1366,
"s": 1351,
"text": "app.module.ts:"
},
{
"code": "import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { FormsModule } from '@angular/forms'; import { AppComponent } from './app.component'; @NgModule({ imports: [ BrowserModule, FormsModule ], declarations: [ AppComponent ], bootstrap: [ AppComponent ], providers: []})export class AppModule { }",
"e": 1731,
"s": 1366,
"text": null
},
{
"code": null,
"e": 1739,
"s": 1731,
"text": "Output:"
},
{
"code": null,
"e": 1765,
"s": 1739,
"text": "Example 2: Using onclick:"
},
{
"code": null,
"e": 1785,
"s": 1765,
"text": "app.component.html:"
},
{
"code": "<div> <button (click)=\"handleClick()\"> Tap Here to Display and Hide the Company name </button></div><br><div *ngIf=\"toDisplay\" class=\"data\"> <div class=\"centered\"> {{name}} </div></div>",
"e": 1981,
"s": 1785,
"text": null
},
{
"code": null,
"e": 1999,
"s": 1981,
"text": "app.component.ts:"
},
{
"code": "import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['app.component.scss']})export class AppComponent { name: string = ''; toDisplay =false; handleClick() { this.toDisplay = !this.toDisplay this.name = 'GeeksForGeeks' } }",
"e": 2320,
"s": 1999,
"text": null
},
{
"code": null,
"e": 2335,
"s": 2320,
"text": "app.module.ts:"
},
{
"code": "import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { FormsModule } from '@angular/forms'; import { AppComponent } from './app.component'; @NgModule({ imports: [ BrowserModule, FormsModule ], declarations: [ AppComponent ], bootstrap: [ AppComponent ], providers: []})export class AppModule { }",
"e": 2700,
"s": 2335,
"text": null
},
{
"code": null,
"e": 2708,
"s": 2700,
"text": "Output:"
},
{
"code": null,
"e": 2734,
"s": 2708,
"text": "Before clicking the icon:"
},
{
"code": null,
"e": 2759,
"s": 2734,
"text": "After clicking the icon:"
},
{
"code": null,
"e": 2776,
"s": 2759,
"text": "AngularJS-Basics"
},
{
"code": null,
"e": 2783,
"s": 2776,
"text": "Picked"
},
{
"code": null,
"e": 2793,
"s": 2783,
"text": "AngularJS"
},
{
"code": null,
"e": 2810,
"s": 2793,
"text": "Web Technologies"
},
{
"code": null,
"e": 2908,
"s": 2810,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2939,
"s": 2908,
"text": "Auth Guards in Angular 9/10/11"
},
{
"code": null,
"e": 2963,
"s": 2939,
"text": "Routing in Angular 9/10"
},
{
"code": null,
"e": 3008,
"s": 2963,
"text": "How to bundle an Angular app for production?"
},
{
"code": null,
"e": 3050,
"s": 3008,
"text": "What is AOT and JIT Compiler in Angular ?"
},
{
"code": null,
"e": 3085,
"s": 3050,
"text": "Angular PrimeNG Dropdown Component"
},
{
"code": null,
"e": 3118,
"s": 3085,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 3180,
"s": 3118,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3241,
"s": 3180,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3291,
"s": 3241,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Create a Pivot Table as a DataFrame – Python Pandas
|
To create a Pivot Table, use the pandas.pivot_table() to create a spreadsheet-style pivot table as a DataFrame.
At first, import the required library −
import pandas as pd
Create a DataFrame with Team records −
dataFrame = pd.DataFrame({'Team ID': {0: 5, 1: 9, 2: 6, 3: 11, 4: 2, 5: 7 },'Team Name': {0: 'India', 1: 'Australia', 2: 'Bangladesh', 3: 'South Africa', 4: 'Sri Lanka', 5: 'England'},'Team Points': {0: 95, 1: 93, 2: 42, 3: 60, 4: 80, 5: 55},'Team Rank': {0: 'One', 1: 'Two', 2: 'Six', 3: 'Four', 4: 'Three', 5: 'Five'}})
Create a Pivot Table: with a single column −
pd.pivot_table(dataFrame, index = ["Team ID"])
Following is the code −
import pandas as pd
# create DataFrame with Team records
dataFrame = pd.DataFrame({'Team ID': {0: 5, 1: 9, 2: 6, 3: 11, 4: 2, 5: 7 },'Team Name': {0: 'India', 1: 'Australia', 2: 'Bangladesh', 3: 'South Africa', 4: 'Sri Lanka', 5: 'England'},'Team Points': {0: 95, 1: 93, 2: 42, 3: 60, 4: 80, 5: 55},'Team Rank': {0: 'One', 1: 'Two', 2: 'Six', 3: 'Four', 4: 'Three', 5: 'Five'}})
print"DataFrame...\n",dataFrame
print"\n... Pivot ..."
print(pd.pivot_table(dataFrame, index = ["Team ID"]))
This will produce the following output −
DataFrame...
Team ID Team Name Team Points Team Rank
0 5 India 95 One
1 9 Australia 93 Two
2 6 Bangladesh 42 Six
3 11 South Africa 60 Four
4 2 Sri Lanka 80 Three
5 7 England 55 Five
... Pivot ...
Team Points
Team ID
2 80
5 95
6 42
7 55
9 93
11 60
|
[
{
"code": null,
"e": 1174,
"s": 1062,
"text": "To create a Pivot Table, use the pandas.pivot_table() to create a spreadsheet-style pivot table as a DataFrame."
},
{
"code": null,
"e": 1214,
"s": 1174,
"text": "At first, import the required library −"
},
{
"code": null,
"e": 1234,
"s": 1214,
"text": "import pandas as pd"
},
{
"code": null,
"e": 1273,
"s": 1234,
"text": "Create a DataFrame with Team records −"
},
{
"code": null,
"e": 1595,
"s": 1273,
"text": "dataFrame = pd.DataFrame({'Team ID': {0: 5, 1: 9, 2: 6, 3: 11, 4: 2, 5: 7 },'Team Name': {0: 'India', 1: 'Australia', 2: 'Bangladesh', 3: 'South Africa', 4: 'Sri Lanka', 5: 'England'},'Team Points': {0: 95, 1: 93, 2: 42, 3: 60, 4: 80, 5: 55},'Team Rank': {0: 'One', 1: 'Two', 2: 'Six', 3: 'Four', 4: 'Three', 5: 'Five'}})"
},
{
"code": null,
"e": 1640,
"s": 1595,
"text": "Create a Pivot Table: with a single column −"
},
{
"code": null,
"e": 1688,
"s": 1640,
"text": "pd.pivot_table(dataFrame, index = [\"Team ID\"])\n"
},
{
"code": null,
"e": 1712,
"s": 1688,
"text": "Following is the code −"
},
{
"code": null,
"e": 2203,
"s": 1712,
"text": "import pandas as pd\n\n# create DataFrame with Team records\ndataFrame = pd.DataFrame({'Team ID': {0: 5, 1: 9, 2: 6, 3: 11, 4: 2, 5: 7 },'Team Name': {0: 'India', 1: 'Australia', 2: 'Bangladesh', 3: 'South Africa', 4: 'Sri Lanka', 5: 'England'},'Team Points': {0: 95, 1: 93, 2: 42, 3: 60, 4: 80, 5: 55},'Team Rank': {0: 'One', 1: 'Two', 2: 'Six', 3: 'Four', 4: 'Three', 5: 'Five'}})\n\nprint\"DataFrame...\\n\",dataFrame\n\nprint\"\\n... Pivot ...\"\nprint(pd.pivot_table(dataFrame, index = [\"Team ID\"]))"
},
{
"code": null,
"e": 2244,
"s": 2203,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2791,
"s": 2244,
"text": "DataFrame...\n Team ID Team Name Team Points Team Rank\n0 5 India 95 One\n1 9 Australia 93 Two\n2 6 Bangladesh 42 Six\n3 11 South Africa 60 Four\n4 2 Sri Lanka 80 Three\n5 7 England 55 Five\n\n... Pivot ...\n Team Points\nTeam ID\n2 80\n5 95\n6 42\n7 55\n9 93\n11 60"
}
] |
How to check all values of an array are equal or not in JavaScript ? - GeeksforGeeks
|
19 Jun, 2019
Given a javaScript array and the task is to print true if all the values of array are same using javaScript.
Approach 1:
First get the array of elements.
Pass it to an arrow function, which calls every() method on each array element and return true if each element matches with the first element of the array.
Example 1: This example uses array.every() method to print the desired response.
<!DOCTYPE HTML> <html> <head> <title> Check if all values of array are equal using JavaScript functions </title> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;"> </p> <button onclick = "gfg_Run();"> click here </button> <pre id = "GFG_DOWN" style = "color:green; font-size: 20px; font-weight: bold;"> </pre> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var arr = [1, 1, 1, 1]; el_up.innerHTML = "Click on button to check if all values are" + " equal<br><br>" + arr; const allEqual = arr => arr.every( v => v === arr[0] ); function gfg_Run() { el_down.innerHTML = allEqual(arr); } </script> </body> </html>
Output:
Before clicking on the button:
After clicking on the button:
Approach 2:
First get the array of elements.
Pass it to a function, which calls reduce() method on array element.
Return true if each element matches with the first element of the array.
Example: This example uses array.reduce() method to print the false for the given array.
<!DOCTYPE HTML> <html> <head> <title> Check if all values of array are equal using JavaScript functions </title> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;"> </p> <button onclick = "gfg_Run();"> click here </button> <pre id = "GFG_DOWN" style = "color:green; font-size: 20px; font-weight: bold;"> </pre> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var arr = ["GFG", "GFG", "GFG", "GfG"]; el_up.innerHTML = "Click on button to check if all" + " values are equal<br><br>" + arr; function allEqual(arr) { if(!arr.length) return true; return arr.reduce(function(a, b) {return (a === b)?a:(!b);}) === arr[0]; } function gfg_Run() { el_down.innerHTML = allEqual(arr); } </script> </body> </html>
Output:
Before clicking on the button:
After clicking on the button:
javascript-array
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Convert a string to an integer in JavaScript
How to append HTML code to a div using JavaScript ?
Set the value of an input field in JavaScript
Installation of Node.js on Linux
Roadmap to Become a Web Developer in 2022
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 25384,
"s": 25356,
"text": "\n19 Jun, 2019"
},
{
"code": null,
"e": 25493,
"s": 25384,
"text": "Given a javaScript array and the task is to print true if all the values of array are same using javaScript."
},
{
"code": null,
"e": 25505,
"s": 25493,
"text": "Approach 1:"
},
{
"code": null,
"e": 25538,
"s": 25505,
"text": "First get the array of elements."
},
{
"code": null,
"e": 25694,
"s": 25538,
"text": "Pass it to an arrow function, which calls every() method on each array element and return true if each element matches with the first element of the array."
},
{
"code": null,
"e": 25775,
"s": 25694,
"text": "Example 1: This example uses array.every() method to print the desired response."
},
{
"code": "<!DOCTYPE HTML> <html> <head> <title> Check if all values of array are equal using JavaScript functions </title> </head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 15px; font-weight: bold;\"> </p> <button onclick = \"gfg_Run();\"> click here </button> <pre id = \"GFG_DOWN\" style = \"color:green; font-size: 20px; font-weight: bold;\"> </pre> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var arr = [1, 1, 1, 1]; el_up.innerHTML = \"Click on button to check if all values are\" + \" equal<br><br>\" + arr; const allEqual = arr => arr.every( v => v === arr[0] ); function gfg_Run() { el_down.innerHTML = allEqual(arr); } </script> </body> </html>",
"e": 26985,
"s": 25775,
"text": null
},
{
"code": null,
"e": 26993,
"s": 26985,
"text": "Output:"
},
{
"code": null,
"e": 27024,
"s": 26993,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 27054,
"s": 27024,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 27066,
"s": 27054,
"text": "Approach 2:"
},
{
"code": null,
"e": 27099,
"s": 27066,
"text": "First get the array of elements."
},
{
"code": null,
"e": 27168,
"s": 27099,
"text": "Pass it to a function, which calls reduce() method on array element."
},
{
"code": null,
"e": 27241,
"s": 27168,
"text": "Return true if each element matches with the first element of the array."
},
{
"code": null,
"e": 27330,
"s": 27241,
"text": "Example: This example uses array.reduce() method to print the false for the given array."
},
{
"code": "<!DOCTYPE HTML> <html> <head> <title> Check if all values of array are equal using JavaScript functions </title> </head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 15px; font-weight: bold;\"> </p> <button onclick = \"gfg_Run();\"> click here </button> <pre id = \"GFG_DOWN\" style = \"color:green; font-size: 20px; font-weight: bold;\"> </pre> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var arr = [\"GFG\", \"GFG\", \"GFG\", \"GfG\"]; el_up.innerHTML = \"Click on button to check if all\" + \" values are equal<br><br>\" + arr; function allEqual(arr) { if(!arr.length) return true; return arr.reduce(function(a, b) {return (a === b)?a:(!b);}) === arr[0]; } function gfg_Run() { el_down.innerHTML = allEqual(arr); } </script> </body> </html> ",
"e": 28675,
"s": 27330,
"text": null
},
{
"code": null,
"e": 28683,
"s": 28675,
"text": "Output:"
},
{
"code": null,
"e": 28714,
"s": 28683,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 28744,
"s": 28714,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 28761,
"s": 28744,
"text": "javascript-array"
},
{
"code": null,
"e": 28772,
"s": 28761,
"text": "JavaScript"
},
{
"code": null,
"e": 28789,
"s": 28772,
"text": "Web Technologies"
},
{
"code": null,
"e": 28816,
"s": 28789,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 28914,
"s": 28816,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28923,
"s": 28914,
"text": "Comments"
},
{
"code": null,
"e": 28936,
"s": 28923,
"text": "Old Comments"
},
{
"code": null,
"e": 28997,
"s": 28936,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 29069,
"s": 28997,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 29114,
"s": 29069,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29166,
"s": 29114,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 29212,
"s": 29166,
"text": "Set the value of an input field in JavaScript"
},
{
"code": null,
"e": 29245,
"s": 29212,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29287,
"s": 29245,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 29330,
"s": 29287,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 29392,
"s": 29330,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
] |
Mastering Time Series Analysis in Python | by Sadrach Pierre, Ph.D. | Towards Data Science
|
Across industries, organizations commonly use time series data, which means any information collected over a regular interval of time, in their operations. Examples include daily stock prices, energy consumption rates, social media engagement metrics and retail demand, among others. Analyze time series data yields insights like trends, seasonal patterns and forecasts into future events that can help generate profits. For example, by understanding the seasonal trends in demand for retail products, companies can plan promotions to maximize sales throughout the year.
When analyzing time series data, you should undertake a number of steps. First, you need to check for stationarity and autocorrelation. Stationarity is a way to measure if the data has structural patterns like seasonal trends. Autocorrelation occurs when future values in a time series linearly depend on past values. You need to check for both of these in time series data because they’re assumptions that are made by many widely used methods in time series analysis. For example, the autoregressive integrated moving average (ARIMA) method for forecasting time series assumes stationarity. Further, linear regression for time series forecasting assumes that the data has no autocorrelation.
During a time series analysis, you also need to perform trend decomposition and forecast future values. Decomposition allows you to visualize trends in your data, which is a great way to clearly explain their behavior.
Finally, forecasting allows you to anticipate future events that can aid in decision making. You can use many different techniques for time series forecasting, but here, we will discuss autoregressive integrated moving average (ARIMA).
We will be working with publicly available airline passenger time series data, which can be found here.
Reading and Displaying Data
To start, let’s import the Pandas library and read the airline passenger data into a data frame:
import pandas as pddf = pd.read_csv(“AirPassengers.csv”)
Now, let’s display the first five rows of data using the data frame head() method:
print(df.head())
We can see that the data contains a column labeled “Month” that contains dates. In that column, the dates are formatted as year–month. We also see that the data starts in the year 1949.
The second column is labeled “#Passengers,” and it contains the number of passengers for the year–month. Let’s take a look at the last five records the data using the tail() method:
print(df.tail())
We see that the data ends in 1960. The next thing we will want to do is convert the month column into a datetime object. This will allow it to programmatically pull time values like the year or month for each record. To do this, we use the Pandas to_datetime() method:
df[‘Month’] = pd.to_datetime(df[‘Month’], format=’%Y-%m’)print(df.head())
Note that this process automatically inserts the first day of each month, which is basically a dummy value since we have no daily passenger data.
The next thing we can do is convert the month column to an index. This will allow us to more easily work with some of the packages we will be covering later:
df.index = df[‘Month’]del df[‘Month’]print(df.head())
Next, let’s generate a time series plot using Seaborn and Matplotlib. This will allow us to visualize the time series data.
First, let’s import Matplotlib and Seaborn:
import matplotlib.pyplot as pltimport seaborn as sns
Next, let’s generate a line plot using Seaborn:
sns.lineplot(df)
And label the y-axis with Matplotlib:
plt.ylabel(“Number of Passengers”)
Stationarity is a key part of time series analysis. Simply put, stationarity means that the manner in which time series data changes is constant. A stationary time series will not have any trends or seasonal patterns. You should check for stationarity because it not only makes modeling time series easier, but it is an underlying assumption in many time series methods. Specifically, stationarity is assumed for a wide variety of time series forecasting methods including autoregressive moving average (ARMA), ARIMA, and Seasonal ARIMA (SARIMA).
We will use the Dickey Fuller test to check for stationarity in our data. This test will generate critical values and a p-value, which will allow us to accept or reject the null hypothesis that there is no stationarity. If we reject the null hypothesis, we accept the alternative, which states that there is stationarity.
These values allow us to test the degree to which present values change with past values. If there is no stationarity in the data set, a change in present values will not cause a significant change in past values.
Let’s test for stationarity in our airline passenger data. To start, let’s calculate a seven month rolling mean:
rolling_mean = df.rolling(7).mean()rolling_std = df.rolling(7).std()
Next, let’s overlay our time series with the seven month rolling mean and seven month rolling standard deviation. First, let’s make a Matplotlib plot of our time series:
plt.plot(df, color=”blue”,label=”Original Passenger Data”)
Then the rolling mean:
plt.plot(rolling_mean, color=”red”, label=”Rolling Mean Passenger Number”)
And finally the rolling standard deviation:
plt.plot(rolling_std, color=”black”, label = “Rolling Standard Deviation in Passenger Number”)
Let’s then add a title
plt.title(“Passenger Time Series, Rolling Mean, Standard Deviation”)
And a legend:
plt.legend(loc=”best”)
Next, let’s import the augmented Dickey-Fuller test from the statsmodels package. The documentation for the test can be found here.
from statsmodels.tsa.stattools import adfuller
Next, let’s pass our data frame into the adfuller method. Here, we specify the autolag parameter as “AIC”, which means that the lag is chosen to minimize the information criterion:
adft = adfuller(df,autolag=”AIC”)
Next, let’s store our results in a data frame display it:
output_df = pd.DataFrame({“Values”:[adft[0],adft[1],adft[2],adft[3], adft[4][‘1%’], adft[4][‘5%’], adft[4][‘10%’]] , “Metric”:[“Test Statistics”,”p-value”,”No. of lags used”,”Number of observations used”,“critical value (1%)”, “critical value (5%)”, “critical value (10%)”]})print(output_df)
We can see that our data is not stationary from the fact that our p-value is greater than 5 percent and the test statistic is greater than the critical value. We can also draw these conclusions from inspecting the data, as we see a clear, increasing trend in the number of passengers.
Autocorrelation
Checking for autocorrelation in time series data is another important part of the analytic process. This is a measure of how correlated time series data is at a given point in time with past values, which has huge implications across many industries. For example, if our passenger data has strong autocorrelation, we can assume that high passenger numbers today suggest a strong likelihood that they will be high tomorrow as well.
The Pandas data frame has an autocorrelation method that we can use to calculate the autocorrelation in our passenger data. Let’s do this for a one month lag:
autocorrelation_lag1 = df[‘#Passengers’].autocorr(lag=1)print(“One Month Lag: “, autocorrelation_lag1)
Now, let’s try three, six and nine months:
autocorrelation_lag3 = df[‘#Passengers’].autocorr(lag=3)print(“Three Month Lag: “, autocorrelation_lag3)autocorrelation_lag6 = df[‘#Passengers’].autocorr(lag=6)print(“Six Month Lag: “, autocorrelation_lag6)autocorrelation_lag9 = df[‘#Passengers’].autocorr(lag=9)print(“Nine Month Lag: “, autocorrelation_lag9)
We see that, even with a nine month lag, the data is highly autocorrelated. This is further illustration of the short and long term trends in the data.
Decomposition
Trend decomposition is another useful way to visualize the trends in time series data. To proceed, let’s import seasonal_decompose from the statsmodels package:
from statsmodels.tsa.seasonal import seasonal_decompose
Next, let’s pass our data frame into the seasonal_decompose method and plot the result:
decompose = seasonal_decompose(df[‘#Passengers’],model=’additive’, period=7)decompose.plot()plt.show()
From this plot, we can clearly see the increasing trend in number of passengers and the seasonality patterns in the rise and fall in values each year.
Time series forecasting allows us to predict future values in a time series given current and past data. Here, we will use the ARIMA method to forecast the number of passengers. ARIMA allows us to forecast future values in terms of a linear combination of past values. We will use the auto_arima package, which will allow us to forgo the time consuming process of hyperparameter tuning.
First, let’s split our data for training and testing and visualize the split:
df[‘Date’] = df.indextrain = df[df[‘Date’] < pd.to_datetime(“1960–08”, format=’%Y-%m’)]train[‘train’] = train[‘#Passengers’]del train[‘Date’]del train[‘#Passengers’]test = df[df[‘Date’] >= pd.to_datetime(“1960–08”, format=’%Y-%m’)]del test[‘Date’]test[‘test’] = test[‘#Passengers’]del test[‘#Passengers’]plt.plot(train, color = “black”)plt.plot(test, color = “red”)plt.title(“Train/Test split for Passenger Data”)plt.ylabel(“Passenger Number”)plt.xlabel(‘Year-Month’)sns.set()plt.show()
The black line corresponds to our training data and the red line corresponds to our test data.
Let’s import auto_arima from the pdmarima package, train our model and generate predictions:
from pmdarima.arima import auto_arimamodel = auto_arima(train, trace=True, error_action=’ignore’, suppress_warnings=True)model.fit(train)forecast = model.predict(n_periods=len(test))forecast = pd.DataFrame(forecast,index = test.index,columns=[‘Prediction’])
Below is a truncated sample of the output:
Now, let’s display the output of our model:
Our predictions are shown in green and the actual values are shown in orange.
Finally, let’s calculate root mean squared error (RMSE):
from math import sqrtfrom sklearn.metrics import mean_squared_errorrms = sqrt(mean_squared_error(test,forecast))print(“RMSE: “, rms)
Time series data analysis is a task that almost every data scientist will face in their career. Having a good understanding of the tools and methods for analysis can enable data scientists to uncover trends, anticipate events and consequently inform decision making. Understanding the seasonality patterns through stationarity, autocorrelation and trend decomposition can guide promotion planning throughout the year which can improve profits for companies. Finally, time series forecasting is a powerful way to anticipate future events in your time series data which can also significantly impact decision making. These types of analyses are invaluable to any data scientist or data science team that looks to bring value to their company with time series data. The code from this post is available on GitHub.
If you are interested learning about the basics of python programming, data manipulation with Pandas, and machine learning in python check out Python for Data Science and Machine Learning: Python Programming, Pandas and Scikit-learn Tutorials for Beginners. I hope you found this post useful/interesting.
This post was originally published on the BuiltIn blog. The original piece can be found here.
|
[
{
"code": null,
"e": 742,
"s": 171,
"text": "Across industries, organizations commonly use time series data, which means any information collected over a regular interval of time, in their operations. Examples include daily stock prices, energy consumption rates, social media engagement metrics and retail demand, among others. Analyze time series data yields insights like trends, seasonal patterns and forecasts into future events that can help generate profits. For example, by understanding the seasonal trends in demand for retail products, companies can plan promotions to maximize sales throughout the year."
},
{
"code": null,
"e": 1435,
"s": 742,
"text": "When analyzing time series data, you should undertake a number of steps. First, you need to check for stationarity and autocorrelation. Stationarity is a way to measure if the data has structural patterns like seasonal trends. Autocorrelation occurs when future values in a time series linearly depend on past values. You need to check for both of these in time series data because they’re assumptions that are made by many widely used methods in time series analysis. For example, the autoregressive integrated moving average (ARIMA) method for forecasting time series assumes stationarity. Further, linear regression for time series forecasting assumes that the data has no autocorrelation."
},
{
"code": null,
"e": 1654,
"s": 1435,
"text": "During a time series analysis, you also need to perform trend decomposition and forecast future values. Decomposition allows you to visualize trends in your data, which is a great way to clearly explain their behavior."
},
{
"code": null,
"e": 1890,
"s": 1654,
"text": "Finally, forecasting allows you to anticipate future events that can aid in decision making. You can use many different techniques for time series forecasting, but here, we will discuss autoregressive integrated moving average (ARIMA)."
},
{
"code": null,
"e": 1994,
"s": 1890,
"text": "We will be working with publicly available airline passenger time series data, which can be found here."
},
{
"code": null,
"e": 2022,
"s": 1994,
"text": "Reading and Displaying Data"
},
{
"code": null,
"e": 2119,
"s": 2022,
"text": "To start, let’s import the Pandas library and read the airline passenger data into a data frame:"
},
{
"code": null,
"e": 2176,
"s": 2119,
"text": "import pandas as pddf = pd.read_csv(“AirPassengers.csv”)"
},
{
"code": null,
"e": 2259,
"s": 2176,
"text": "Now, let’s display the first five rows of data using the data frame head() method:"
},
{
"code": null,
"e": 2276,
"s": 2259,
"text": "print(df.head())"
},
{
"code": null,
"e": 2462,
"s": 2276,
"text": "We can see that the data contains a column labeled “Month” that contains dates. In that column, the dates are formatted as year–month. We also see that the data starts in the year 1949."
},
{
"code": null,
"e": 2644,
"s": 2462,
"text": "The second column is labeled “#Passengers,” and it contains the number of passengers for the year–month. Let’s take a look at the last five records the data using the tail() method:"
},
{
"code": null,
"e": 2661,
"s": 2644,
"text": "print(df.tail())"
},
{
"code": null,
"e": 2930,
"s": 2661,
"text": "We see that the data ends in 1960. The next thing we will want to do is convert the month column into a datetime object. This will allow it to programmatically pull time values like the year or month for each record. To do this, we use the Pandas to_datetime() method:"
},
{
"code": null,
"e": 3004,
"s": 2930,
"text": "df[‘Month’] = pd.to_datetime(df[‘Month’], format=’%Y-%m’)print(df.head())"
},
{
"code": null,
"e": 3150,
"s": 3004,
"text": "Note that this process automatically inserts the first day of each month, which is basically a dummy value since we have no daily passenger data."
},
{
"code": null,
"e": 3308,
"s": 3150,
"text": "The next thing we can do is convert the month column to an index. This will allow us to more easily work with some of the packages we will be covering later:"
},
{
"code": null,
"e": 3362,
"s": 3308,
"text": "df.index = df[‘Month’]del df[‘Month’]print(df.head())"
},
{
"code": null,
"e": 3486,
"s": 3362,
"text": "Next, let’s generate a time series plot using Seaborn and Matplotlib. This will allow us to visualize the time series data."
},
{
"code": null,
"e": 3530,
"s": 3486,
"text": "First, let’s import Matplotlib and Seaborn:"
},
{
"code": null,
"e": 3583,
"s": 3530,
"text": "import matplotlib.pyplot as pltimport seaborn as sns"
},
{
"code": null,
"e": 3631,
"s": 3583,
"text": "Next, let’s generate a line plot using Seaborn:"
},
{
"code": null,
"e": 3648,
"s": 3631,
"text": "sns.lineplot(df)"
},
{
"code": null,
"e": 3686,
"s": 3648,
"text": "And label the y-axis with Matplotlib:"
},
{
"code": null,
"e": 3721,
"s": 3686,
"text": "plt.ylabel(“Number of Passengers”)"
},
{
"code": null,
"e": 4268,
"s": 3721,
"text": "Stationarity is a key part of time series analysis. Simply put, stationarity means that the manner in which time series data changes is constant. A stationary time series will not have any trends or seasonal patterns. You should check for stationarity because it not only makes modeling time series easier, but it is an underlying assumption in many time series methods. Specifically, stationarity is assumed for a wide variety of time series forecasting methods including autoregressive moving average (ARMA), ARIMA, and Seasonal ARIMA (SARIMA)."
},
{
"code": null,
"e": 4590,
"s": 4268,
"text": "We will use the Dickey Fuller test to check for stationarity in our data. This test will generate critical values and a p-value, which will allow us to accept or reject the null hypothesis that there is no stationarity. If we reject the null hypothesis, we accept the alternative, which states that there is stationarity."
},
{
"code": null,
"e": 4804,
"s": 4590,
"text": "These values allow us to test the degree to which present values change with past values. If there is no stationarity in the data set, a change in present values will not cause a significant change in past values."
},
{
"code": null,
"e": 4917,
"s": 4804,
"text": "Let’s test for stationarity in our airline passenger data. To start, let’s calculate a seven month rolling mean:"
},
{
"code": null,
"e": 4986,
"s": 4917,
"text": "rolling_mean = df.rolling(7).mean()rolling_std = df.rolling(7).std()"
},
{
"code": null,
"e": 5156,
"s": 4986,
"text": "Next, let’s overlay our time series with the seven month rolling mean and seven month rolling standard deviation. First, let’s make a Matplotlib plot of our time series:"
},
{
"code": null,
"e": 5215,
"s": 5156,
"text": "plt.plot(df, color=”blue”,label=”Original Passenger Data”)"
},
{
"code": null,
"e": 5238,
"s": 5215,
"text": "Then the rolling mean:"
},
{
"code": null,
"e": 5313,
"s": 5238,
"text": "plt.plot(rolling_mean, color=”red”, label=”Rolling Mean Passenger Number”)"
},
{
"code": null,
"e": 5357,
"s": 5313,
"text": "And finally the rolling standard deviation:"
},
{
"code": null,
"e": 5452,
"s": 5357,
"text": "plt.plot(rolling_std, color=”black”, label = “Rolling Standard Deviation in Passenger Number”)"
},
{
"code": null,
"e": 5475,
"s": 5452,
"text": "Let’s then add a title"
},
{
"code": null,
"e": 5544,
"s": 5475,
"text": "plt.title(“Passenger Time Series, Rolling Mean, Standard Deviation”)"
},
{
"code": null,
"e": 5558,
"s": 5544,
"text": "And a legend:"
},
{
"code": null,
"e": 5581,
"s": 5558,
"text": "plt.legend(loc=”best”)"
},
{
"code": null,
"e": 5713,
"s": 5581,
"text": "Next, let’s import the augmented Dickey-Fuller test from the statsmodels package. The documentation for the test can be found here."
},
{
"code": null,
"e": 5760,
"s": 5713,
"text": "from statsmodels.tsa.stattools import adfuller"
},
{
"code": null,
"e": 5941,
"s": 5760,
"text": "Next, let’s pass our data frame into the adfuller method. Here, we specify the autolag parameter as “AIC”, which means that the lag is chosen to minimize the information criterion:"
},
{
"code": null,
"e": 5975,
"s": 5941,
"text": "adft = adfuller(df,autolag=”AIC”)"
},
{
"code": null,
"e": 6033,
"s": 5975,
"text": "Next, let’s store our results in a data frame display it:"
},
{
"code": null,
"e": 6325,
"s": 6033,
"text": "output_df = pd.DataFrame({“Values”:[adft[0],adft[1],adft[2],adft[3], adft[4][‘1%’], adft[4][‘5%’], adft[4][‘10%’]] , “Metric”:[“Test Statistics”,”p-value”,”No. of lags used”,”Number of observations used”,“critical value (1%)”, “critical value (5%)”, “critical value (10%)”]})print(output_df)"
},
{
"code": null,
"e": 6610,
"s": 6325,
"text": "We can see that our data is not stationary from the fact that our p-value is greater than 5 percent and the test statistic is greater than the critical value. We can also draw these conclusions from inspecting the data, as we see a clear, increasing trend in the number of passengers."
},
{
"code": null,
"e": 6626,
"s": 6610,
"text": "Autocorrelation"
},
{
"code": null,
"e": 7057,
"s": 6626,
"text": "Checking for autocorrelation in time series data is another important part of the analytic process. This is a measure of how correlated time series data is at a given point in time with past values, which has huge implications across many industries. For example, if our passenger data has strong autocorrelation, we can assume that high passenger numbers today suggest a strong likelihood that they will be high tomorrow as well."
},
{
"code": null,
"e": 7216,
"s": 7057,
"text": "The Pandas data frame has an autocorrelation method that we can use to calculate the autocorrelation in our passenger data. Let’s do this for a one month lag:"
},
{
"code": null,
"e": 7319,
"s": 7216,
"text": "autocorrelation_lag1 = df[‘#Passengers’].autocorr(lag=1)print(“One Month Lag: “, autocorrelation_lag1)"
},
{
"code": null,
"e": 7362,
"s": 7319,
"text": "Now, let’s try three, six and nine months:"
},
{
"code": null,
"e": 7672,
"s": 7362,
"text": "autocorrelation_lag3 = df[‘#Passengers’].autocorr(lag=3)print(“Three Month Lag: “, autocorrelation_lag3)autocorrelation_lag6 = df[‘#Passengers’].autocorr(lag=6)print(“Six Month Lag: “, autocorrelation_lag6)autocorrelation_lag9 = df[‘#Passengers’].autocorr(lag=9)print(“Nine Month Lag: “, autocorrelation_lag9)"
},
{
"code": null,
"e": 7824,
"s": 7672,
"text": "We see that, even with a nine month lag, the data is highly autocorrelated. This is further illustration of the short and long term trends in the data."
},
{
"code": null,
"e": 7838,
"s": 7824,
"text": "Decomposition"
},
{
"code": null,
"e": 7999,
"s": 7838,
"text": "Trend decomposition is another useful way to visualize the trends in time series data. To proceed, let’s import seasonal_decompose from the statsmodels package:"
},
{
"code": null,
"e": 8055,
"s": 7999,
"text": "from statsmodels.tsa.seasonal import seasonal_decompose"
},
{
"code": null,
"e": 8143,
"s": 8055,
"text": "Next, let’s pass our data frame into the seasonal_decompose method and plot the result:"
},
{
"code": null,
"e": 8246,
"s": 8143,
"text": "decompose = seasonal_decompose(df[‘#Passengers’],model=’additive’, period=7)decompose.plot()plt.show()"
},
{
"code": null,
"e": 8397,
"s": 8246,
"text": "From this plot, we can clearly see the increasing trend in number of passengers and the seasonality patterns in the rise and fall in values each year."
},
{
"code": null,
"e": 8784,
"s": 8397,
"text": "Time series forecasting allows us to predict future values in a time series given current and past data. Here, we will use the ARIMA method to forecast the number of passengers. ARIMA allows us to forecast future values in terms of a linear combination of past values. We will use the auto_arima package, which will allow us to forgo the time consuming process of hyperparameter tuning."
},
{
"code": null,
"e": 8862,
"s": 8784,
"text": "First, let’s split our data for training and testing and visualize the split:"
},
{
"code": null,
"e": 9349,
"s": 8862,
"text": "df[‘Date’] = df.indextrain = df[df[‘Date’] < pd.to_datetime(“1960–08”, format=’%Y-%m’)]train[‘train’] = train[‘#Passengers’]del train[‘Date’]del train[‘#Passengers’]test = df[df[‘Date’] >= pd.to_datetime(“1960–08”, format=’%Y-%m’)]del test[‘Date’]test[‘test’] = test[‘#Passengers’]del test[‘#Passengers’]plt.plot(train, color = “black”)plt.plot(test, color = “red”)plt.title(“Train/Test split for Passenger Data”)plt.ylabel(“Passenger Number”)plt.xlabel(‘Year-Month’)sns.set()plt.show()"
},
{
"code": null,
"e": 9444,
"s": 9349,
"text": "The black line corresponds to our training data and the red line corresponds to our test data."
},
{
"code": null,
"e": 9537,
"s": 9444,
"text": "Let’s import auto_arima from the pdmarima package, train our model and generate predictions:"
},
{
"code": null,
"e": 9795,
"s": 9537,
"text": "from pmdarima.arima import auto_arimamodel = auto_arima(train, trace=True, error_action=’ignore’, suppress_warnings=True)model.fit(train)forecast = model.predict(n_periods=len(test))forecast = pd.DataFrame(forecast,index = test.index,columns=[‘Prediction’])"
},
{
"code": null,
"e": 9838,
"s": 9795,
"text": "Below is a truncated sample of the output:"
},
{
"code": null,
"e": 9882,
"s": 9838,
"text": "Now, let’s display the output of our model:"
},
{
"code": null,
"e": 9960,
"s": 9882,
"text": "Our predictions are shown in green and the actual values are shown in orange."
},
{
"code": null,
"e": 10017,
"s": 9960,
"text": "Finally, let’s calculate root mean squared error (RMSE):"
},
{
"code": null,
"e": 10150,
"s": 10017,
"text": "from math import sqrtfrom sklearn.metrics import mean_squared_errorrms = sqrt(mean_squared_error(test,forecast))print(“RMSE: “, rms)"
},
{
"code": null,
"e": 10961,
"s": 10150,
"text": "Time series data analysis is a task that almost every data scientist will face in their career. Having a good understanding of the tools and methods for analysis can enable data scientists to uncover trends, anticipate events and consequently inform decision making. Understanding the seasonality patterns through stationarity, autocorrelation and trend decomposition can guide promotion planning throughout the year which can improve profits for companies. Finally, time series forecasting is a powerful way to anticipate future events in your time series data which can also significantly impact decision making. These types of analyses are invaluable to any data scientist or data science team that looks to bring value to their company with time series data. The code from this post is available on GitHub."
},
{
"code": null,
"e": 11266,
"s": 10961,
"text": "If you are interested learning about the basics of python programming, data manipulation with Pandas, and machine learning in python check out Python for Data Science and Machine Learning: Python Programming, Pandas and Scikit-learn Tutorials for Beginners. I hope you found this post useful/interesting."
}
] |
Difference between String buffer and String builder in Java
|
String buffer and StringBuilder both are mutable classes which can be used to do operation on string objects such as reverse of string, concating string and etc. We can modify string without creating a new object of the string. A string buffer is thread-safe whereas string builder is not thread-safe. Therefore, it is faster than a string buffer. Also, a string concat + operator internally uses StringBuffer or StringBuilder class. Below are the differences.
public class StringBuilderExample{
public static void main(String[] args){
StringBuilder builder=new StringBuilder("Hi");
builder.append("Java 8");
System.out.println("StringBuilderExample" +builder);
}
}
public class StringBufferExample{
public static void main(String[] args){
StringBuffer buffer=new StringBuffer("Hi");
buffer.append("Java 8");
System.out.println("StringBufferExample" +buffer);
}
}
|
[
{
"code": null,
"e": 1524,
"s": 1062,
"text": "String buffer and StringBuilder both are mutable classes which can be used to do operation on string objects such as reverse of string, concating string and etc. We can modify string without creating a new object of the string. A string buffer is thread-safe whereas string builder is not thread-safe. Therefore, it is faster than a string buffer. Also, a string concat + operator internally uses StringBuffer or StringBuilder class. Below are the differences."
},
{
"code": null,
"e": 1753,
"s": 1524,
"text": "public class StringBuilderExample{\n public static void main(String[] args){\n StringBuilder builder=new StringBuilder(\"Hi\");\n builder.append(\"Java 8\");\n System.out.println(\"StringBuilderExample\" +builder);\n }\n}"
},
{
"code": null,
"e": 1975,
"s": 1753,
"text": "public class StringBufferExample{\n public static void main(String[] args){\n StringBuffer buffer=new StringBuffer(\"Hi\");\n buffer.append(\"Java 8\");\n System.out.println(\"StringBufferExample\" +buffer);\n }\n}"
}
] |
Random Forest In R. A tutorial on how to implement the... | by Cory Maklin | Towards Data Science
|
There are laws which demand that the decisions made by models used in issuing loans or insurance be explainable. The latter is known as model interpretability and is one of the reasons why we see random forest models being used over other models like neural networks.
The random forest algorithm works by aggregating the predictions made by multiple decision trees of varying depth. Every decision tree in the forest is trained on a subset of the dataset called the bootstrapped dataset.
The portion of samples that were left out during the construction of each decision tree in the forest are referred to as the Out-Of-Bag (OOB) dataset. As we’ll see later, the model will automatically evaluate its own performance by running each of the samples in the OOB dataset through the forest.
Recall how when deciding on the criteria with which to split a decision tree, we measured the impurity produced by each feature using the Gini index or entropy. In random forest, however, we randomly select a predefined number of feature as candidates. The latter will result in a larger variance between the trees which would otherwise contain the same features (i.e those which are highly correlated with the target label).
When the random forest is used for classification and is presented with a new sample, the final prediction is made by taking the majority of the predictions made by each individual decision tree in the forest. In the event, it is used for regression and it is presented with a new sample, the final prediction is made by taking the average of the predictions made by each individual decision tree in the forest.
In the proceeding tutorial, we’ll use the caTools package to split our data into training and tests sets as well as the random forest classifier provided by the randomForest package.
library(randomForest)require(caTools)
We’ll be be working with one of the available datasets from the UCI Machine Learning Repository. If you’d like to follow along, the data can be found here.
Our goal will be to predict whether a person has heart disease given
data <- read.csv( "processed.cleveland.data", header=FALSE)
The csv file contains 303 rows and 14 columns.
dim(data)
According to the documentation, the mapping of columns and features is as follows.
age: age in yearssex: sex (1 = male; 0 =female)cp: chest pain type (1 = typical angina; 2 = atypical angina; 3 = non-anginal pain; 4 = asymptomatic)trestbps: resting blood pressure (in mm Hg on admission to the hopsital)choi: serum cholestoral in mg/dlfbs: fasting blood sugar > 120 mg/dl (1 = true; = 0 false)restecg: resting electrocardiographic results (1 = normal; 2 = having ST-T wave abnormality; 2 = showing probable or definite left ventricular hypertrophy)thalach: maximum heart rate achievedexang: exercise induced angina (1 = yes; 0 = no)oldpeak: ST depression induced by exercise relative to restslope: the slope of the peak exercise ST segment (1 = upsloping; 2 = flat; 3 = downsloping)ca: number of major vessels (0–3) colored by flourosopythai: (3 = normal; 6 = fixed defect; 7 = reversable defect)num: diagnosis of heart disease. It is an integer valued from 0 (no presence) to 4.
age: age in years
sex: sex (1 = male; 0 =female)
cp: chest pain type (1 = typical angina; 2 = atypical angina; 3 = non-anginal pain; 4 = asymptomatic)
trestbps: resting blood pressure (in mm Hg on admission to the hopsital)
choi: serum cholestoral in mg/dl
fbs: fasting blood sugar > 120 mg/dl (1 = true; = 0 false)
restecg: resting electrocardiographic results (1 = normal; 2 = having ST-T wave abnormality; 2 = showing probable or definite left ventricular hypertrophy)
thalach: maximum heart rate achieved
exang: exercise induced angina (1 = yes; 0 = no)
oldpeak: ST depression induced by exercise relative to rest
slope: the slope of the peak exercise ST segment (1 = upsloping; 2 = flat; 3 = downsloping)
ca: number of major vessels (0–3) colored by flourosopy
thai: (3 = normal; 6 = fixed defect; 7 = reversable defect)
num: diagnosis of heart disease. It is an integer valued from 0 (no presence) to 4.
Given that the csv file does not contain the header, we must specify the column names manually.
names(data) <- c("age", "sex", "cp", "trestbps", "choi", "fbs", "restecg", "thalach", "exang", "oldpeak", "slope", "ca", "thai", "num")
Often times, when we’re working with large datasets, we want to get a sense of our data. As opposed to loading everything in RAM, we can use the head function to view the first few rows.
head(data)
To simplify the problem, we’re only going to attempt to distinguish the presence of heart disease (values 1,2,3,4) from absence of heart disease (value 0). Therefore, we replace all labels greater than 1 by 1.
data$num[data$num > 1] <- 1
R provides a useful function called summary for viewing metrics related to our data. If we take a closer look, we’ll notice that it provides the mean for what should be categorical variables.
summary(data)
This implies that there is an issue with the column types. We can view the type of each column by running the following command.
sapply(data, class)
In R, a categorical variable (a variable that takes on a finite amount of values) is a factor. As we can see, sex is incorrectly treated as a number when in reality it can only be 1 if male and 0 if female. We can use the transform method to change the in built type of each feature.
data <- transform( data, age=as.integer(age), sex=as.factor(sex), cp=as.factor(cp), trestbps=as.integer(trestbps), choi=as.integer(choi), fbs=as.factor(fbs), restecg=as.factor(restecg), thalach=as.integer(thalach), exang=as.factor(exang), oldpeak=as.numeric(oldpeak), slope=as.factor(slope), ca=as.factor(ca), thai=as.factor(thai), num=as.factor(num))sapply(data, class)
If we, again, print a summary of our data, we get the following.
summary(data)
Now, the categorical variables are expressed as the counts for each respective class. The ca and thai of certain samples are ? indicating missing values. R expects missing values to be written as NA. After replacing them, we can use the colSums function to view the missing value counts of each column.
data[ data == "?"] <- NAcolSums(is.na(data))
According to the notes from above, thai and ca are both factors.
thai: (3 = normal; 6 = fixed defect; 7 = reversable defect)
ca: number of major vessels (0–3) colored by flourosopy
I don’t claim to be a domain expert, so we’re just going to replace the missing values for thai with what is considered normal. Next, we’re going to drop the rows where ca is missing.
data$thai[which(is.na(data$thai))] <- as.factor("3.0")data <- data[!(data$ca %in% c(NA)),]colSums(is.na(data))
If we run summary again, we’ll see that it still views ? as a potential class.
summary(data)
To get around this issue, we cast the columns to factors.
data$ca <- factor(data$ca)data$thai <- factor(data$thai)summary(data)
We’re going to set a portion of our data aside for testing.
sample = sample.split(data$num, SplitRatio = .75)train = subset(data, sample == TRUE)test = subset(data, sample == FALSE)dim(train)dim(test)
Next, we initialize an instance of the randomForest class. Unlike scikit-learn, we don’t need to explicily call the fit method to train our model.
rf <- randomForest( num ~ ., data=train)
By default, the number of decision trees in the forest is 500 and the number of features used as potential candidates for each split is 3. The model will automatically attempt to classify each of the samples in the Out-Of-Bag dataset and display a confusion matrix with the results.
Now, we use our model to predict whether the people in our testing set have heart disease.
pred = predict(rf, newdata=test[-14])
Since this is a classification problem, we use a confusion matrix to evaluate the performance of our model. Recall that values on the diagonal correspond to true positives and true negatives (correct predictions) whereas the others correspond to false positives and false negatives.
cm = table(test[,14], pred)
|
[
{
"code": null,
"e": 440,
"s": 172,
"text": "There are laws which demand that the decisions made by models used in issuing loans or insurance be explainable. The latter is known as model interpretability and is one of the reasons why we see random forest models being used over other models like neural networks."
},
{
"code": null,
"e": 660,
"s": 440,
"text": "The random forest algorithm works by aggregating the predictions made by multiple decision trees of varying depth. Every decision tree in the forest is trained on a subset of the dataset called the bootstrapped dataset."
},
{
"code": null,
"e": 959,
"s": 660,
"text": "The portion of samples that were left out during the construction of each decision tree in the forest are referred to as the Out-Of-Bag (OOB) dataset. As we’ll see later, the model will automatically evaluate its own performance by running each of the samples in the OOB dataset through the forest."
},
{
"code": null,
"e": 1385,
"s": 959,
"text": "Recall how when deciding on the criteria with which to split a decision tree, we measured the impurity produced by each feature using the Gini index or entropy. In random forest, however, we randomly select a predefined number of feature as candidates. The latter will result in a larger variance between the trees which would otherwise contain the same features (i.e those which are highly correlated with the target label)."
},
{
"code": null,
"e": 1797,
"s": 1385,
"text": "When the random forest is used for classification and is presented with a new sample, the final prediction is made by taking the majority of the predictions made by each individual decision tree in the forest. In the event, it is used for regression and it is presented with a new sample, the final prediction is made by taking the average of the predictions made by each individual decision tree in the forest."
},
{
"code": null,
"e": 1980,
"s": 1797,
"text": "In the proceeding tutorial, we’ll use the caTools package to split our data into training and tests sets as well as the random forest classifier provided by the randomForest package."
},
{
"code": null,
"e": 2018,
"s": 1980,
"text": "library(randomForest)require(caTools)"
},
{
"code": null,
"e": 2174,
"s": 2018,
"text": "We’ll be be working with one of the available datasets from the UCI Machine Learning Repository. If you’d like to follow along, the data can be found here."
},
{
"code": null,
"e": 2243,
"s": 2174,
"text": "Our goal will be to predict whether a person has heart disease given"
},
{
"code": null,
"e": 2305,
"s": 2243,
"text": "data <- read.csv( \"processed.cleveland.data\", header=FALSE)"
},
{
"code": null,
"e": 2352,
"s": 2305,
"text": "The csv file contains 303 rows and 14 columns."
},
{
"code": null,
"e": 2362,
"s": 2352,
"text": "dim(data)"
},
{
"code": null,
"e": 2445,
"s": 2362,
"text": "According to the documentation, the mapping of columns and features is as follows."
},
{
"code": null,
"e": 3342,
"s": 2445,
"text": "age: age in yearssex: sex (1 = male; 0 =female)cp: chest pain type (1 = typical angina; 2 = atypical angina; 3 = non-anginal pain; 4 = asymptomatic)trestbps: resting blood pressure (in mm Hg on admission to the hopsital)choi: serum cholestoral in mg/dlfbs: fasting blood sugar > 120 mg/dl (1 = true; = 0 false)restecg: resting electrocardiographic results (1 = normal; 2 = having ST-T wave abnormality; 2 = showing probable or definite left ventricular hypertrophy)thalach: maximum heart rate achievedexang: exercise induced angina (1 = yes; 0 = no)oldpeak: ST depression induced by exercise relative to restslope: the slope of the peak exercise ST segment (1 = upsloping; 2 = flat; 3 = downsloping)ca: number of major vessels (0–3) colored by flourosopythai: (3 = normal; 6 = fixed defect; 7 = reversable defect)num: diagnosis of heart disease. It is an integer valued from 0 (no presence) to 4."
},
{
"code": null,
"e": 3360,
"s": 3342,
"text": "age: age in years"
},
{
"code": null,
"e": 3391,
"s": 3360,
"text": "sex: sex (1 = male; 0 =female)"
},
{
"code": null,
"e": 3493,
"s": 3391,
"text": "cp: chest pain type (1 = typical angina; 2 = atypical angina; 3 = non-anginal pain; 4 = asymptomatic)"
},
{
"code": null,
"e": 3566,
"s": 3493,
"text": "trestbps: resting blood pressure (in mm Hg on admission to the hopsital)"
},
{
"code": null,
"e": 3599,
"s": 3566,
"text": "choi: serum cholestoral in mg/dl"
},
{
"code": null,
"e": 3658,
"s": 3599,
"text": "fbs: fasting blood sugar > 120 mg/dl (1 = true; = 0 false)"
},
{
"code": null,
"e": 3814,
"s": 3658,
"text": "restecg: resting electrocardiographic results (1 = normal; 2 = having ST-T wave abnormality; 2 = showing probable or definite left ventricular hypertrophy)"
},
{
"code": null,
"e": 3851,
"s": 3814,
"text": "thalach: maximum heart rate achieved"
},
{
"code": null,
"e": 3900,
"s": 3851,
"text": "exang: exercise induced angina (1 = yes; 0 = no)"
},
{
"code": null,
"e": 3960,
"s": 3900,
"text": "oldpeak: ST depression induced by exercise relative to rest"
},
{
"code": null,
"e": 4052,
"s": 3960,
"text": "slope: the slope of the peak exercise ST segment (1 = upsloping; 2 = flat; 3 = downsloping)"
},
{
"code": null,
"e": 4108,
"s": 4052,
"text": "ca: number of major vessels (0–3) colored by flourosopy"
},
{
"code": null,
"e": 4168,
"s": 4108,
"text": "thai: (3 = normal; 6 = fixed defect; 7 = reversable defect)"
},
{
"code": null,
"e": 4252,
"s": 4168,
"text": "num: diagnosis of heart disease. It is an integer valued from 0 (no presence) to 4."
},
{
"code": null,
"e": 4348,
"s": 4252,
"text": "Given that the csv file does not contain the header, we must specify the column names manually."
},
{
"code": null,
"e": 4484,
"s": 4348,
"text": "names(data) <- c(\"age\", \"sex\", \"cp\", \"trestbps\", \"choi\", \"fbs\", \"restecg\", \"thalach\", \"exang\", \"oldpeak\", \"slope\", \"ca\", \"thai\", \"num\")"
},
{
"code": null,
"e": 4671,
"s": 4484,
"text": "Often times, when we’re working with large datasets, we want to get a sense of our data. As opposed to loading everything in RAM, we can use the head function to view the first few rows."
},
{
"code": null,
"e": 4682,
"s": 4671,
"text": "head(data)"
},
{
"code": null,
"e": 4892,
"s": 4682,
"text": "To simplify the problem, we’re only going to attempt to distinguish the presence of heart disease (values 1,2,3,4) from absence of heart disease (value 0). Therefore, we replace all labels greater than 1 by 1."
},
{
"code": null,
"e": 4920,
"s": 4892,
"text": "data$num[data$num > 1] <- 1"
},
{
"code": null,
"e": 5112,
"s": 4920,
"text": "R provides a useful function called summary for viewing metrics related to our data. If we take a closer look, we’ll notice that it provides the mean for what should be categorical variables."
},
{
"code": null,
"e": 5126,
"s": 5112,
"text": "summary(data)"
},
{
"code": null,
"e": 5255,
"s": 5126,
"text": "This implies that there is an issue with the column types. We can view the type of each column by running the following command."
},
{
"code": null,
"e": 5275,
"s": 5255,
"text": "sapply(data, class)"
},
{
"code": null,
"e": 5559,
"s": 5275,
"text": "In R, a categorical variable (a variable that takes on a finite amount of values) is a factor. As we can see, sex is incorrectly treated as a number when in reality it can only be 1 if male and 0 if female. We can use the transform method to change the in built type of each feature."
},
{
"code": null,
"e": 5945,
"s": 5559,
"text": "data <- transform( data, age=as.integer(age), sex=as.factor(sex), cp=as.factor(cp), trestbps=as.integer(trestbps), choi=as.integer(choi), fbs=as.factor(fbs), restecg=as.factor(restecg), thalach=as.integer(thalach), exang=as.factor(exang), oldpeak=as.numeric(oldpeak), slope=as.factor(slope), ca=as.factor(ca), thai=as.factor(thai), num=as.factor(num))sapply(data, class)"
},
{
"code": null,
"e": 6010,
"s": 5945,
"text": "If we, again, print a summary of our data, we get the following."
},
{
"code": null,
"e": 6024,
"s": 6010,
"text": "summary(data)"
},
{
"code": null,
"e": 6327,
"s": 6024,
"text": "Now, the categorical variables are expressed as the counts for each respective class. The ca and thai of certain samples are ? indicating missing values. R expects missing values to be written as NA. After replacing them, we can use the colSums function to view the missing value counts of each column."
},
{
"code": null,
"e": 6372,
"s": 6327,
"text": "data[ data == \"?\"] <- NAcolSums(is.na(data))"
},
{
"code": null,
"e": 6437,
"s": 6372,
"text": "According to the notes from above, thai and ca are both factors."
},
{
"code": null,
"e": 6497,
"s": 6437,
"text": "thai: (3 = normal; 6 = fixed defect; 7 = reversable defect)"
},
{
"code": null,
"e": 6553,
"s": 6497,
"text": "ca: number of major vessels (0–3) colored by flourosopy"
},
{
"code": null,
"e": 6737,
"s": 6553,
"text": "I don’t claim to be a domain expert, so we’re just going to replace the missing values for thai with what is considered normal. Next, we’re going to drop the rows where ca is missing."
},
{
"code": null,
"e": 6848,
"s": 6737,
"text": "data$thai[which(is.na(data$thai))] <- as.factor(\"3.0\")data <- data[!(data$ca %in% c(NA)),]colSums(is.na(data))"
},
{
"code": null,
"e": 6927,
"s": 6848,
"text": "If we run summary again, we’ll see that it still views ? as a potential class."
},
{
"code": null,
"e": 6941,
"s": 6927,
"text": "summary(data)"
},
{
"code": null,
"e": 6999,
"s": 6941,
"text": "To get around this issue, we cast the columns to factors."
},
{
"code": null,
"e": 7069,
"s": 6999,
"text": "data$ca <- factor(data$ca)data$thai <- factor(data$thai)summary(data)"
},
{
"code": null,
"e": 7129,
"s": 7069,
"text": "We’re going to set a portion of our data aside for testing."
},
{
"code": null,
"e": 7271,
"s": 7129,
"text": "sample = sample.split(data$num, SplitRatio = .75)train = subset(data, sample == TRUE)test = subset(data, sample == FALSE)dim(train)dim(test)"
},
{
"code": null,
"e": 7418,
"s": 7271,
"text": "Next, we initialize an instance of the randomForest class. Unlike scikit-learn, we don’t need to explicily call the fit method to train our model."
},
{
"code": null,
"e": 7461,
"s": 7418,
"text": "rf <- randomForest( num ~ ., data=train)"
},
{
"code": null,
"e": 7744,
"s": 7461,
"text": "By default, the number of decision trees in the forest is 500 and the number of features used as potential candidates for each split is 3. The model will automatically attempt to classify each of the samples in the Out-Of-Bag dataset and display a confusion matrix with the results."
},
{
"code": null,
"e": 7835,
"s": 7744,
"text": "Now, we use our model to predict whether the people in our testing set have heart disease."
},
{
"code": null,
"e": 7873,
"s": 7835,
"text": "pred = predict(rf, newdata=test[-14])"
},
{
"code": null,
"e": 8156,
"s": 7873,
"text": "Since this is a classification problem, we use a confusion matrix to evaluate the performance of our model. Recall that values on the diagonal correspond to true positives and true negatives (correct predictions) whereas the others correspond to false positives and false negatives."
}
] |
How to create a navigation bar with left-aligned and right-aligned links with CSS?
|
Following is the code to create a navigation bar with left-aligned and right-aligned links −
Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
body{
margin:0px;
margin-top:60px;
padding: 0px;
}
nav{
display: flex;
position: fixed;
top:0;
width: 100%;
background-color: rgb(251, 255, 196);
overflow: auto;
height: auto;
}
.left-links{
flex:1 1 200px;
}
.links {
display: inline-block;
text-align: center;
padding: 14px;
color: rgb(0, 0, 0);
text-decoration: none;
font-size: 17px;
font-weight: bolder;
}
.links:hover {
border-bottom: 2px solid purple;
}
.selected{
border-bottom: 2px solid purple;
}
</style>
</head>
<body>
<nav>
<div class="left-links">
<a class="links selected" href="#">Home</a>
<a class="links" href="#"> Login</a>
<a class="links" href="#"> Register</a>
</div>
<div class="right-links">
<a class="links" href="#"> Contact Us</a>
<a class="links" href="#">More Info</a>
</div>
</nav>
<h1>Hover on the above links</h1>
</body>
</html>
The above code will produce the following output −
|
[
{
"code": null,
"e": 1155,
"s": 1062,
"text": "Following is the code to create a navigation bar with left-aligned and right-aligned links −"
},
{
"code": null,
"e": 1166,
"s": 1155,
"text": " Live Demo"
},
{
"code": null,
"e": 2203,
"s": 1166,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n<title>Document</title>\n<style>\nbody{\n margin:0px;\n margin-top:60px;\n padding: 0px;\n}\nnav{\n display: flex;\n position: fixed;\n top:0;\n width: 100%;\n background-color: rgb(251, 255, 196);\n overflow: auto;\n height: auto;\n}\n.left-links{\n flex:1 1 200px;\n}\n.links {\n display: inline-block;\n text-align: center;\n padding: 14px;\n color: rgb(0, 0, 0);\n text-decoration: none;\n font-size: 17px;\n font-weight: bolder;\n}\n.links:hover {\n border-bottom: 2px solid purple;\n}\n.selected{\n border-bottom: 2px solid purple;\n}\n</style>\n</head>\n<body>\n<nav>\n<div class=\"left-links\">\n<a class=\"links selected\" href=\"#\">Home</a>\n<a class=\"links\" href=\"#\"> Login</a>\n<a class=\"links\" href=\"#\"> Register</a>\n</div>\n<div class=\"right-links\">\n<a class=\"links\" href=\"#\"> Contact Us</a>\n<a class=\"links\" href=\"#\">More Info</a>\n</div>\n</nav>\n<h1>Hover on the above links</h1>\n</body>\n</html>"
},
{
"code": null,
"e": 2254,
"s": 2203,
"text": "The above code will produce the following output −"
}
] |
Left Shift and Right Shift Operators in C/C++ - GeeksforGeeks
|
30 Nov, 2021
Left Shift :
Denoted as : <<
Eg: N<<i (N: first operand, i: second operand)
Takes two numbers, left shifts the bits of the first operand, the second operand decides the number of places to shift. Or in other words left shifting an integer “x” with an integer “y” denoted as ‘(x<<y)’ is equivalent to multiplying x with 2^y (2 raised to power y).
eg: lets take N=22; which is 00010110 in Binary Form.
Now, if “N is left-shifted by 2” i.e N=N<<2 then N will become N=N*(2^2). Thus, N=22*(2^2)=88 which can be wriiten as 01011000.
C
C++
/* C++ Program to demonstrate use of left shift operator */#include<stdio.h>int main(){ // a = 5(00000101), b = 9(00001001) unsigned char a = 5, b = 9; // The result is 00001010 printf("a<<1 = %d\n", a<<1); // The result is 00010010 printf("b<<1 = %d\n", b<<1); return 0;}
/* C++ Program to demonstrate use of left shift operator */#include <iostream>using namespace std; int main(){ // a = 5(00000101), b = 9(00001001) unsigned char a = 5, b = 9; // The result is 00001010 cout <<"a<<1 = "<< (a<<1) << endl; // The result is 00010010 cout <<"b<<1 = "<< (b<<1) << endl; return 0;} // This code is contributed by shivanisinghss2110
a<<1 = 10
b<<1 = 18
Right Shift :
Denoted as : >>
Eg: N>>i (N: first operand, i: second operand)
Takes two numbers, right shifts the bits of the first operand, the second operand decides the number of places to shift. In other words right shifting an integer “x” with an integer “y” denoted as ‘(x>>y)‘ is equivalent to dividing x with 2^y.
eg: lets take N=32; which is 100000 in Binary Form.
Now, if “N is right-shifted by 2” i.e N=N>>2 then N will become N=N/(2^2). Thus, N=32/(2^2)=8 which can be wriiten as 1000.
C++
C
/* C++ Program to demonstrate use of right shift operator */#include <iostream>using namespace std; int main(){ // a = 5(00000101), b = 9(00001001) unsigned char a = 5, b = 9; // The result is 00000010 cout <<"a>>1 = "<< (a >> 1)<< endl; // The result is 00000100 cout <<"b>>1 = "<< (b >> 1) << endl; return 0;} // This code is contributed by shivanisinghss2110
/* C++ Program to demonstrate use of right shift operator */#include <stdio.h> using namespace std;int main(){ // a = 5(00000101), b = 9(00001001) unsigned char a = 5, b = 9; // The result is 00000010 printf("a>>1 = %d\n", a >> 1); // The result is 00000100 printf("b>>1 = %d\n", b >> 1); return 0;}
a>>1 = 2
b>>1 = 4
Important Points :
The left shift and right shift operators should not be used for negative numbers. The result of is undefined behaviour if any of the operands is a negative number. For example results of both 1 >> -1 and 1 << -1 is undefined.
If the number is shifted more than the size of integer, the behaviour is undefined. For example, 1 << 33 is undefined if integers are stored using 32 bits. For bit shift of larger values 1ULL<<62 ULL is used for Unsigned Long Long which is defined using 64 bits which can store large values.
The left-shift by 1 and right-shift by 1 are equivalent to the product of first term and 2 to the power given element(1<<3 = 1*pow(2,3)) and division of first term and second term raised to power 2 (1>>3 = 1/pow(2,3)) respectively. As mentioned in point 1, it works only if numbers are positive.
C++
C
#include <iostream>using namespace std; int main(){ int x = 19; unsigned long long y = 19; cout <<"x << 1 = " << (x << 1) << endl; cout <<"x >> 1 = " << (x >> 1) << endl; // shift y by 61 bits left cout <<"y << 61 = " << (y << 61) << endl; return 0;} // this code is contributed by shivanisinghss2110
#include <stdio.h>int main(){ int x = 19; unsigned long long y = 19; printf("x << 1 = %d\n", x << 1); printf("x >> 1 = %d\n", x >> 1); // shift y by 61 bits left printf("y << 61 = %lld\n", y << 61); return 0;}
x << 1 = 38
x >> 1 = 9
y << 61 = 6917529027641081856
The left-shift of 1 by i is equivalent to 2 raised to power i. As mentioned in point 1, it works only if numbers are positive.
C++
C
#include <iostream>using namespace std; int main(){ int i = 3; cout <<"pow(2, "<< i << ") = " << (1 << i) << endl; i = 4; cout <<"pow(2, "<< i << ") = " << (1 << i) << endl; return 0;} // this code is contributed by shivanisinghss2110
#include<stdio.h>int main(){ int i = 3; printf("pow(2, %d) = %d\n", i, 1 << i); i = 4; printf("pow(2, %d) = %d\n", i, 1 << i); return 0;}
pow(2, 3) = 8
pow(2, 4) = 16
Interesting Facts about Bitwise Operators in C
VVNPraveenKumar
theWINTERSOLDIER
kunalcodr
sam_2200
tr_abhishek
shivanisinghss2110
cpp-operator
Bit Magic
C Language
C++
cpp-operator
Bit Magic
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Cyclic Redundancy Check and Modulo-2 Division
Little and Big Endian Mystery
Binary representation of a given number
Add two numbers without using arithmetic operators
Program to find whether a given number is power of 2
Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
Arrays in C/C++
std::sort() in C++ STL
Multidimensional Arrays in C / C++
rand() and srand() in C/C++
|
[
{
"code": null,
"e": 24509,
"s": 24481,
"text": "\n30 Nov, 2021"
},
{
"code": null,
"e": 24522,
"s": 24509,
"text": "Left Shift :"
},
{
"code": null,
"e": 24539,
"s": 24522,
"text": "Denoted as : << "
},
{
"code": null,
"e": 24586,
"s": 24539,
"text": "Eg: N<<i (N: first operand, i: second operand)"
},
{
"code": null,
"e": 24857,
"s": 24586,
"text": "Takes two numbers, left shifts the bits of the first operand, the second operand decides the number of places to shift. Or in other words left shifting an integer “x” with an integer “y” denoted as ‘(x<<y)’ is equivalent to multiplying x with 2^y (2 raised to power y). "
},
{
"code": null,
"e": 24911,
"s": 24857,
"text": "eg: lets take N=22; which is 00010110 in Binary Form."
},
{
"code": null,
"e": 25045,
"s": 24911,
"text": " Now, if “N is left-shifted by 2” i.e N=N<<2 then N will become N=N*(2^2). Thus, N=22*(2^2)=88 which can be wriiten as 01011000."
},
{
"code": null,
"e": 25047,
"s": 25045,
"text": "C"
},
{
"code": null,
"e": 25051,
"s": 25047,
"text": "C++"
},
{
"code": "/* C++ Program to demonstrate use of left shift operator */#include<stdio.h>int main(){ // a = 5(00000101), b = 9(00001001) unsigned char a = 5, b = 9; // The result is 00001010 printf(\"a<<1 = %d\\n\", a<<1); // The result is 00010010 printf(\"b<<1 = %d\\n\", b<<1); return 0;}",
"e": 25359,
"s": 25051,
"text": null
},
{
"code": "/* C++ Program to demonstrate use of left shift operator */#include <iostream>using namespace std; int main(){ // a = 5(00000101), b = 9(00001001) unsigned char a = 5, b = 9; // The result is 00001010 cout <<\"a<<1 = \"<< (a<<1) << endl; // The result is 00010010 cout <<\"b<<1 = \"<< (b<<1) << endl; return 0;} // This code is contributed by shivanisinghss2110",
"e": 25754,
"s": 25359,
"text": null
},
{
"code": null,
"e": 25774,
"s": 25754,
"text": "a<<1 = 10\nb<<1 = 18"
},
{
"code": null,
"e": 25788,
"s": 25774,
"text": "Right Shift :"
},
{
"code": null,
"e": 25804,
"s": 25788,
"text": "Denoted as : >>"
},
{
"code": null,
"e": 25851,
"s": 25804,
"text": "Eg: N>>i (N: first operand, i: second operand)"
},
{
"code": null,
"e": 26096,
"s": 25851,
"text": "Takes two numbers, right shifts the bits of the first operand, the second operand decides the number of places to shift. In other words right shifting an integer “x” with an integer “y” denoted as ‘(x>>y)‘ is equivalent to dividing x with 2^y. "
},
{
"code": null,
"e": 26148,
"s": 26096,
"text": "eg: lets take N=32; which is 100000 in Binary Form."
},
{
"code": null,
"e": 26278,
"s": 26148,
"text": " Now, if “N is right-shifted by 2” i.e N=N>>2 then N will become N=N/(2^2). Thus, N=32/(2^2)=8 which can be wriiten as 1000. "
},
{
"code": null,
"e": 26282,
"s": 26278,
"text": "C++"
},
{
"code": null,
"e": 26284,
"s": 26282,
"text": "C"
},
{
"code": "/* C++ Program to demonstrate use of right shift operator */#include <iostream>using namespace std; int main(){ // a = 5(00000101), b = 9(00001001) unsigned char a = 5, b = 9; // The result is 00000010 cout <<\"a>>1 = \"<< (a >> 1)<< endl; // The result is 00000100 cout <<\"b>>1 = \"<< (b >> 1) << endl; return 0;} // This code is contributed by shivanisinghss2110",
"e": 26677,
"s": 26284,
"text": null
},
{
"code": "/* C++ Program to demonstrate use of right shift operator */#include <stdio.h> using namespace std;int main(){ // a = 5(00000101), b = 9(00001001) unsigned char a = 5, b = 9; // The result is 00000010 printf(\"a>>1 = %d\\n\", a >> 1); // The result is 00000100 printf(\"b>>1 = %d\\n\", b >> 1); return 0;}",
"e": 27007,
"s": 26677,
"text": null
},
{
"code": null,
"e": 27025,
"s": 27007,
"text": "a>>1 = 2\nb>>1 = 4"
},
{
"code": null,
"e": 27045,
"s": 27025,
"text": "Important Points : "
},
{
"code": null,
"e": 27271,
"s": 27045,
"text": "The left shift and right shift operators should not be used for negative numbers. The result of is undefined behaviour if any of the operands is a negative number. For example results of both 1 >> -1 and 1 << -1 is undefined."
},
{
"code": null,
"e": 27564,
"s": 27271,
"text": "If the number is shifted more than the size of integer, the behaviour is undefined. For example, 1 << 33 is undefined if integers are stored using 32 bits. For bit shift of larger values 1ULL<<62 ULL is used for Unsigned Long Long which is defined using 64 bits which can store large values."
},
{
"code": null,
"e": 27860,
"s": 27564,
"text": "The left-shift by 1 and right-shift by 1 are equivalent to the product of first term and 2 to the power given element(1<<3 = 1*pow(2,3)) and division of first term and second term raised to power 2 (1>>3 = 1/pow(2,3)) respectively. As mentioned in point 1, it works only if numbers are positive."
},
{
"code": null,
"e": 27864,
"s": 27860,
"text": "C++"
},
{
"code": null,
"e": 27866,
"s": 27864,
"text": "C"
},
{
"code": "#include <iostream>using namespace std; int main(){ int x = 19; unsigned long long y = 19; cout <<\"x << 1 = \" << (x << 1) << endl; cout <<\"x >> 1 = \" << (x >> 1) << endl; // shift y by 61 bits left cout <<\"y << 61 = \" << (y << 61) << endl; return 0;} // this code is contributed by shivanisinghss2110",
"e": 28190,
"s": 27866,
"text": null
},
{
"code": "#include <stdio.h>int main(){ int x = 19; unsigned long long y = 19; printf(\"x << 1 = %d\\n\", x << 1); printf(\"x >> 1 = %d\\n\", x >> 1); // shift y by 61 bits left printf(\"y << 61 = %lld\\n\", y << 61); return 0;}",
"e": 28421,
"s": 28190,
"text": null
},
{
"code": null,
"e": 28474,
"s": 28421,
"text": "x << 1 = 38\nx >> 1 = 9\ny << 61 = 6917529027641081856"
},
{
"code": null,
"e": 28603,
"s": 28474,
"text": "The left-shift of 1 by i is equivalent to 2 raised to power i. As mentioned in point 1, it works only if numbers are positive. "
},
{
"code": null,
"e": 28607,
"s": 28603,
"text": "C++"
},
{
"code": null,
"e": 28609,
"s": 28607,
"text": "C"
},
{
"code": "#include <iostream>using namespace std; int main(){ int i = 3; cout <<\"pow(2, \"<< i << \") = \" << (1 << i) << endl; i = 4; cout <<\"pow(2, \"<< i << \") = \" << (1 << i) << endl; return 0;} // this code is contributed by shivanisinghss2110",
"e": 28861,
"s": 28609,
"text": null
},
{
"code": "#include<stdio.h>int main(){ int i = 3; printf(\"pow(2, %d) = %d\\n\", i, 1 << i); i = 4; printf(\"pow(2, %d) = %d\\n\", i, 1 << i); return 0;}",
"e": 29014,
"s": 28861,
"text": null
},
{
"code": null,
"e": 29043,
"s": 29014,
"text": "pow(2, 3) = 8\npow(2, 4) = 16"
},
{
"code": null,
"e": 29091,
"s": 29043,
"text": "Interesting Facts about Bitwise Operators in C "
},
{
"code": null,
"e": 29107,
"s": 29091,
"text": "VVNPraveenKumar"
},
{
"code": null,
"e": 29124,
"s": 29107,
"text": "theWINTERSOLDIER"
},
{
"code": null,
"e": 29134,
"s": 29124,
"text": "kunalcodr"
},
{
"code": null,
"e": 29143,
"s": 29134,
"text": "sam_2200"
},
{
"code": null,
"e": 29155,
"s": 29143,
"text": "tr_abhishek"
},
{
"code": null,
"e": 29174,
"s": 29155,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 29187,
"s": 29174,
"text": "cpp-operator"
},
{
"code": null,
"e": 29197,
"s": 29187,
"text": "Bit Magic"
},
{
"code": null,
"e": 29208,
"s": 29197,
"text": "C Language"
},
{
"code": null,
"e": 29212,
"s": 29208,
"text": "C++"
},
{
"code": null,
"e": 29225,
"s": 29212,
"text": "cpp-operator"
},
{
"code": null,
"e": 29235,
"s": 29225,
"text": "Bit Magic"
},
{
"code": null,
"e": 29239,
"s": 29235,
"text": "CPP"
},
{
"code": null,
"e": 29337,
"s": 29239,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29346,
"s": 29337,
"text": "Comments"
},
{
"code": null,
"e": 29359,
"s": 29346,
"text": "Old Comments"
},
{
"code": null,
"e": 29405,
"s": 29359,
"text": "Cyclic Redundancy Check and Modulo-2 Division"
},
{
"code": null,
"e": 29435,
"s": 29405,
"text": "Little and Big Endian Mystery"
},
{
"code": null,
"e": 29475,
"s": 29435,
"text": "Binary representation of a given number"
},
{
"code": null,
"e": 29526,
"s": 29475,
"text": "Add two numbers without using arithmetic operators"
},
{
"code": null,
"e": 29579,
"s": 29526,
"text": "Program to find whether a given number is power of 2"
},
{
"code": null,
"e": 29657,
"s": 29579,
"text": "Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()"
},
{
"code": null,
"e": 29673,
"s": 29657,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 29696,
"s": 29673,
"text": "std::sort() in C++ STL"
},
{
"code": null,
"e": 29731,
"s": 29696,
"text": "Multidimensional Arrays in C / C++"
}
] |
Rexx - Strings
|
Strings in Rexx are denoted by a sequence of characters. The following program is an example of strings −
/* Main program */
a = "This is a string"
say a
The output of the above program is as follows −
This is a string
Let’s discuss some methods which are available in Rexx for strings.
This method returns a certain number of characters from the left of the string.
This method returns a certain number of characters from the right of the string.
This method returns the number of characters in the string.
This method returns the characters in a reverse format.
This method compares 2 strings. Returns "0" if "string1" and "string2" are identical. Otherwise, it returns the position of the first character that does not match.
This method copies a string n number of times.
This method gets a sub string from a particular string.
This method returns the position of one string within another.
This method deletes a sub string from within a string.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2445,
"s": 2339,
"text": "Strings in Rexx are denoted by a sequence of characters. The following program is an example of strings −"
},
{
"code": null,
"e": 2495,
"s": 2445,
"text": "/* Main program */ \na = \"This is a string\" \nsay a"
},
{
"code": null,
"e": 2543,
"s": 2495,
"text": "The output of the above program is as follows −"
},
{
"code": null,
"e": 2562,
"s": 2543,
"text": "This is a string \n"
},
{
"code": null,
"e": 2630,
"s": 2562,
"text": "Let’s discuss some methods which are available in Rexx for strings."
},
{
"code": null,
"e": 2710,
"s": 2630,
"text": "This method returns a certain number of characters from the left of the string."
},
{
"code": null,
"e": 2791,
"s": 2710,
"text": "This method returns a certain number of characters from the right of the string."
},
{
"code": null,
"e": 2851,
"s": 2791,
"text": "This method returns the number of characters in the string."
},
{
"code": null,
"e": 2907,
"s": 2851,
"text": "This method returns the characters in a reverse format."
},
{
"code": null,
"e": 3072,
"s": 2907,
"text": "This method compares 2 strings. Returns \"0\" if \"string1\" and \"string2\" are identical. Otherwise, it returns the position of the first character that does not match."
},
{
"code": null,
"e": 3119,
"s": 3072,
"text": "This method copies a string n number of times."
},
{
"code": null,
"e": 3175,
"s": 3119,
"text": "This method gets a sub string from a particular string."
},
{
"code": null,
"e": 3238,
"s": 3175,
"text": "This method returns the position of one string within another."
},
{
"code": null,
"e": 3293,
"s": 3238,
"text": "This method deletes a sub string from within a string."
},
{
"code": null,
"e": 3300,
"s": 3293,
"text": " Print"
},
{
"code": null,
"e": 3311,
"s": 3300,
"text": " Add Notes"
}
] |
Guava - Table Interface
|
Table represents a special map where two keys can be specified in combined fashion to refer to a single value. It is similar to creating a map of maps.
Following is the declaration for com.google.common.collect.Table<R,C,V> interface −
@GwtCompatible
public interface Table<R,C,V>
Set<Table.Cell<R,C,V>> cellSet()
Returns a set of all row key/column key/value triplets.
void clear()
Removes all mappings from the table.
Map<R,V> column(C columnKey)
Returns a view of all mappings that have the given column key.
Set<C> columnKeySet()
Returns a set of column keys that have one or more values in the table.
Map<C,Map<R,V>> columnMap()
Returns a view that associates each column key with the corresponding map from row keys to values.
boolean contains(Object rowKey, Object columnKey)
Returns true if the table contains a mapping with the specified row and column keys.
boolean containsColumn(Object columnKey)
Returns true if the table contains a mapping with the specified column.
boolean containsRow(Object rowKey)
Returns true if the table contains a mapping with the specified row key.
boolean containsValue(Object value)
Returns true if the table contains a mapping with the specified value.
boolean equals(Object obj)
Compares the specified object with this table for equality.
V get(Object rowKey, Object columnKey)
Returns the value corresponding to the given row and column keys, or null if no such mapping exists.
int hashCode()
Returns the hash code for this table.
boolean isEmpty()
Returns true if the table contains no mappings.
V put(R rowKey, C columnKey, V value)
Associates the specified value with the specified keys.
void putAll(Table<? extends R,? extends C,? extends V> table)
Copies all mappings from the specified table to this table.
V remove(Object rowKey, Object columnKey)
Removes the mapping, if any, associated with the given keys.
Map<C,V> row(R rowKey)
Returns a view of all mappings that have the given row key.
Set<R> rowKeySet()
Returns a set of row keys that have one or more values in the table.
Map<R,Map<C,V>> rowMap()
Returns a view that associates each row key with the corresponding map from column keys to values.
int size()
Returns the number of row key / column key / value mappings in the table.
Collection<V> values()
Returns a collection of all values, which may contain duplicates.
Create the following java program using any editor of your choice in say C:/> Guava.
import java.util.Map;
import java.util.Set;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.Table;
public class GuavaTester {
public static void main(String args[]) {
//Table<R,C,V> == Map<R,Map<C,V>>
/*
* Company: IBM, Microsoft, TCS
* IBM -> {101:Mahesh, 102:Ramesh, 103:Suresh}
* Microsoft -> {101:Sohan, 102:Mohan, 103:Rohan }
* TCS -> {101:Ram, 102: Shyam, 103: Sunil }
*
* */
//create a table
Table<String, String, String> employeeTable = HashBasedTable.create();
//initialize the table with employee details
employeeTable.put("IBM", "101","Mahesh");
employeeTable.put("IBM", "102","Ramesh");
employeeTable.put("IBM", "103","Suresh");
employeeTable.put("Microsoft", "111","Sohan");
employeeTable.put("Microsoft", "112","Mohan");
employeeTable.put("Microsoft", "113","Rohan");
employeeTable.put("TCS", "121","Ram");
employeeTable.put("TCS", "122","Shyam");
employeeTable.put("TCS", "123","Sunil");
//get Map corresponding to IBM
Map<String,String> ibmEmployees = employeeTable.row("IBM");
System.out.println("List of IBM Employees");
for(Map.Entry<String, String> entry : ibmEmployees.entrySet()) {
System.out.println("Emp Id: " + entry.getKey() + ", Name: " + entry.getValue());
}
//get all the unique keys of the table
Set<String> employers = employeeTable.rowKeySet();
System.out.print("Employers: ");
for(String employer: employers) {
System.out.print(employer + " ");
}
System.out.println();
//get a Map corresponding to 102
Map<String,String> EmployerMap = employeeTable.column("102");
for(Map.Entry<String, String> entry : EmployerMap.entrySet()) {
System.out.println("Employer: " + entry.getKey() + ", Name: " + entry.getValue());
}
}
}
Compile the class using javac compiler as follows −
C:\Guava>javac GuavaTester.java
Now run the GuavaTester to see the result.
C:\Guava>java GuavaTester
See the result.
List of IBM Employees
Emp Id: 102, Name: Ramesh
Emp Id: 101, Name: Mahesh
Emp Id: 103, Name: Suresh
Employers: IBM TCS Microsoft
Employer: IBM, Name: Ramesh
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2037,
"s": 1885,
"text": "Table represents a special map where two keys can be specified in combined fashion to refer to a single value. It is similar to creating a map of maps."
},
{
"code": null,
"e": 2121,
"s": 2037,
"text": "Following is the declaration for com.google.common.collect.Table<R,C,V> interface −"
},
{
"code": null,
"e": 2166,
"s": 2121,
"text": "@GwtCompatible\npublic interface Table<R,C,V>"
},
{
"code": null,
"e": 2199,
"s": 2166,
"text": "Set<Table.Cell<R,C,V>> cellSet()"
},
{
"code": null,
"e": 2255,
"s": 2199,
"text": "Returns a set of all row key/column key/value triplets."
},
{
"code": null,
"e": 2268,
"s": 2255,
"text": "void clear()"
},
{
"code": null,
"e": 2305,
"s": 2268,
"text": "Removes all mappings from the table."
},
{
"code": null,
"e": 2334,
"s": 2305,
"text": "Map<R,V>\tcolumn(C columnKey)"
},
{
"code": null,
"e": 2397,
"s": 2334,
"text": "Returns a view of all mappings that have the given column key."
},
{
"code": null,
"e": 2419,
"s": 2397,
"text": "Set<C> columnKeySet()"
},
{
"code": null,
"e": 2491,
"s": 2419,
"text": "Returns a set of column keys that have one or more values in the table."
},
{
"code": null,
"e": 2519,
"s": 2491,
"text": "Map<C,Map<R,V>> columnMap()"
},
{
"code": null,
"e": 2618,
"s": 2519,
"text": "Returns a view that associates each column key with the corresponding map from row keys to values."
},
{
"code": null,
"e": 2668,
"s": 2618,
"text": "boolean contains(Object rowKey, Object columnKey)"
},
{
"code": null,
"e": 2753,
"s": 2668,
"text": "Returns true if the table contains a mapping with the specified row and column keys."
},
{
"code": null,
"e": 2794,
"s": 2753,
"text": "boolean containsColumn(Object columnKey)"
},
{
"code": null,
"e": 2866,
"s": 2794,
"text": "Returns true if the table contains a mapping with the specified column."
},
{
"code": null,
"e": 2901,
"s": 2866,
"text": "boolean containsRow(Object rowKey)"
},
{
"code": null,
"e": 2974,
"s": 2901,
"text": "Returns true if the table contains a mapping with the specified row key."
},
{
"code": null,
"e": 3010,
"s": 2974,
"text": "boolean containsValue(Object value)"
},
{
"code": null,
"e": 3081,
"s": 3010,
"text": "Returns true if the table contains a mapping with the specified value."
},
{
"code": null,
"e": 3108,
"s": 3081,
"text": "boolean equals(Object obj)"
},
{
"code": null,
"e": 3168,
"s": 3108,
"text": "Compares the specified object with this table for equality."
},
{
"code": null,
"e": 3207,
"s": 3168,
"text": "V get(Object rowKey, Object columnKey)"
},
{
"code": null,
"e": 3308,
"s": 3207,
"text": "Returns the value corresponding to the given row and column keys, or null if no such mapping exists."
},
{
"code": null,
"e": 3323,
"s": 3308,
"text": "int hashCode()"
},
{
"code": null,
"e": 3361,
"s": 3323,
"text": "Returns the hash code for this table."
},
{
"code": null,
"e": 3379,
"s": 3361,
"text": "boolean isEmpty()"
},
{
"code": null,
"e": 3427,
"s": 3379,
"text": "Returns true if the table contains no mappings."
},
{
"code": null,
"e": 3465,
"s": 3427,
"text": "V put(R rowKey, C columnKey, V value)"
},
{
"code": null,
"e": 3521,
"s": 3465,
"text": "Associates the specified value with the specified keys."
},
{
"code": null,
"e": 3583,
"s": 3521,
"text": "void putAll(Table<? extends R,? extends C,? extends V> table)"
},
{
"code": null,
"e": 3643,
"s": 3583,
"text": "Copies all mappings from the specified table to this table."
},
{
"code": null,
"e": 3685,
"s": 3643,
"text": "V remove(Object rowKey, Object columnKey)"
},
{
"code": null,
"e": 3746,
"s": 3685,
"text": "Removes the mapping, if any, associated with the given keys."
},
{
"code": null,
"e": 3769,
"s": 3746,
"text": "Map<C,V>\trow(R rowKey)"
},
{
"code": null,
"e": 3829,
"s": 3769,
"text": "Returns a view of all mappings that have the given row key."
},
{
"code": null,
"e": 3848,
"s": 3829,
"text": "Set<R> rowKeySet()"
},
{
"code": null,
"e": 3917,
"s": 3848,
"text": "Returns a set of row keys that have one or more values in the table."
},
{
"code": null,
"e": 3942,
"s": 3917,
"text": "Map<R,Map<C,V>> rowMap()"
},
{
"code": null,
"e": 4041,
"s": 3942,
"text": "Returns a view that associates each row key with the corresponding map from column keys to values."
},
{
"code": null,
"e": 4052,
"s": 4041,
"text": "int size()"
},
{
"code": null,
"e": 4126,
"s": 4052,
"text": "Returns the number of row key / column key / value mappings in the table."
},
{
"code": null,
"e": 4149,
"s": 4126,
"text": "Collection<V> values()"
},
{
"code": null,
"e": 4215,
"s": 4149,
"text": "Returns a collection of all values, which may contain duplicates."
},
{
"code": null,
"e": 4300,
"s": 4215,
"text": "Create the following java program using any editor of your choice in say C:/> Guava."
},
{
"code": null,
"e": 6292,
"s": 4300,
"text": "import java.util.Map;\nimport java.util.Set;\n\nimport com.google.common.collect.HashBasedTable;\nimport com.google.common.collect.Table;\n\npublic class GuavaTester {\n public static void main(String args[]) {\n \n //Table<R,C,V> == Map<R,Map<C,V>>\n /*\n * Company: IBM, Microsoft, TCS\n * IBM \t\t-> {101:Mahesh, 102:Ramesh, 103:Suresh}\n * Microsoft \t-> {101:Sohan, 102:Mohan, 103:Rohan } \n * TCS \t\t-> {101:Ram, 102: Shyam, 103: Sunil } \n * \n * */\n \n //create a table\n Table<String, String, String> employeeTable = HashBasedTable.create();\n\n //initialize the table with employee details\n employeeTable.put(\"IBM\", \"101\",\"Mahesh\");\n employeeTable.put(\"IBM\", \"102\",\"Ramesh\");\n employeeTable.put(\"IBM\", \"103\",\"Suresh\");\n\n employeeTable.put(\"Microsoft\", \"111\",\"Sohan\");\n employeeTable.put(\"Microsoft\", \"112\",\"Mohan\");\n employeeTable.put(\"Microsoft\", \"113\",\"Rohan\");\n\n employeeTable.put(\"TCS\", \"121\",\"Ram\");\n employeeTable.put(\"TCS\", \"122\",\"Shyam\");\n employeeTable.put(\"TCS\", \"123\",\"Sunil\");\n\n //get Map corresponding to IBM\n Map<String,String> ibmEmployees = employeeTable.row(\"IBM\");\n\n System.out.println(\"List of IBM Employees\");\n \n for(Map.Entry<String, String> entry : ibmEmployees.entrySet()) {\n System.out.println(\"Emp Id: \" + entry.getKey() + \", Name: \" + entry.getValue());\n }\n\n //get all the unique keys of the table\n Set<String> employers = employeeTable.rowKeySet();\n System.out.print(\"Employers: \");\n \n for(String employer: employers) {\n System.out.print(employer + \" \");\n }\n \n System.out.println();\n\n //get a Map corresponding to 102\n Map<String,String> EmployerMap = employeeTable.column(\"102\");\n \n for(Map.Entry<String, String> entry : EmployerMap.entrySet()) {\n System.out.println(\"Employer: \" + entry.getKey() + \", Name: \" + entry.getValue());\n }\t\t\n }\t\n}"
},
{
"code": null,
"e": 6344,
"s": 6292,
"text": "Compile the class using javac compiler as follows −"
},
{
"code": null,
"e": 6377,
"s": 6344,
"text": "C:\\Guava>javac GuavaTester.java\n"
},
{
"code": null,
"e": 6420,
"s": 6377,
"text": "Now run the GuavaTester to see the result."
},
{
"code": null,
"e": 6447,
"s": 6420,
"text": "C:\\Guava>java GuavaTester\n"
},
{
"code": null,
"e": 6463,
"s": 6447,
"text": "See the result."
},
{
"code": null,
"e": 6622,
"s": 6463,
"text": "List of IBM Employees\nEmp Id: 102, Name: Ramesh\nEmp Id: 101, Name: Mahesh\nEmp Id: 103, Name: Suresh\nEmployers: IBM TCS Microsoft \nEmployer: IBM, Name: Ramesh\n"
},
{
"code": null,
"e": 6629,
"s": 6622,
"text": " Print"
},
{
"code": null,
"e": 6640,
"s": 6629,
"text": " Add Notes"
}
] |
5 Steps in Pandas to Process Petrophysical Well Logs (part2) | by Ryan A. Mardani | Towards Data Science
|
In the previous work, we implemented 10 simple steps using pandas to process petrophysical well logs in LAS format. In this project, we will go deeper to use more advanced approaches to process well log data.
These 5 steps are:1) Function Definition2) Apply Function3) Lambda Function4) Cut Function5) Visualization
To avoid extra work that we already did on specific well data previously, we will use the output of that project. If you worked on a previous project you may write the DataFrame into csv file (use to_csv command ) to use here. Otherwise, you can access through my github account and download the csv format called 1050383876v2.csv. You may also download the full Jupiter notebook file from my account, here.
Let’s bring required libraries on the workbook first:
import numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport seaborn as sns%matplotlib inline
Then, read the csv data into df variable:
df = pd.read_csv('1050383876v2.csv')df.head()
Dataset seems clean. I also dropped the upper part where there were some NaN values, so the starting depth is 1000 meters.
Function in python is a group of statements that perform a specific task. A function can make the larger program more readable. It also can help us to prevent repetition. A function has a special structure as: 1- keyword def, 2- function name, 3- arguments that we pass values to a function, 4- a colon(:), 5- more statement in body, 6- Return statement which is optional.
There are several approaches to calculate porosity from petrophysical well logs. Here we will use the density method. Density tools measure rock medium bulk density(b) in wellbore conditions. Having knowledge of the fluid density (f) filling rock porosity and grain density(ma) can help us to calculate the percentage of void areas of the rocks. The equation is:
Starting with def keyword, density porosity(den) function can be defined with the following arguments (parameters): rb, rf, rm.
def den(rb, rf, rm): # rb = bulk density from well log readings # rf = fluid density # rm = matrix density or grain density of rocks return (rm-rb)*100/(rm-rf)
Simply, the function will return the density porosity as written in the last line of code. Here we prefer to have porosity in percentage(multiplied by 100). After defining the density porosity function, we can apply it to the dataset.
Using the apply function, a predefined function (here, density porosity) can be applied to each element of DataFrame either in column or row direction. If we leave it on default, it will on the column.
df['DNPOR'] = df['RHOB'].apply(den, rf=1, rm=2.71 )
As den function takes 3 values (rb, rf, rm), we can introduce the main one from the dataset (rb =df[‘RHOB’]) and use the apply function to define rf and rm constants manually. Here I assume that fluid content is water with a density of 1 and the dominant mineral is Calcite with a density of 2.71. The Density porosity is stored in a new column called DNPOR.
Lambda function is a simple 1-line function that does not have def or return keywords. In fact, they are implicit. To use this function, we need to type lambda followed by parameters. Then, the colon comes before the return argument.
Total porosity is defined as the average of Density and Neutron porosity.
Tot_por = lambda DN,CN: (DN+CN)/2
The function name is Tot_por. For lambda function, DN and CN are density and neutron parameters followed by a colon. The average of these two inputs will be returned by the function.
df['TPOR'] = Tot_por(df['CNPOR'], df["DNPOR"])df.head()
Calling the Tot_por function and introducing corresponding columns of DataFrame as input will create total porosity that will be stored in a new column called TPOR in the dataset.
When we need to segment and sort data values into specific bins, we can use the Cut function. Here we will use this function to define simple rock facies based on petrophysical properties, GR.
Facies classification is a huge topic in geoscience and various metrics can come to play but here, we look at it very simple. Based on GR reading in well logs, we can identify clean from shaly formations.
df['facies_gr'] = pd.cut(df['GR'], bins=[0,40,300], labels=['clean', 'shaly'] )
A new column is added to the dataset based on GR readings which are binned between 0 and40(clean), and between 40and 300(shaly).
Commonly, the matplotlib library is used in python for plotting. In this work, I prefer to use the seaborn library for its simplicity. I want to visualize a scatter plot of density porosity vs. neutron porosity with the legend color of facies that in the previous part we defined. This is simply accessible by one line of code while in matplotlib it requires for loop.
sns.lmplot(x='DNPOR', y='DT', hue='facies_gr', data=df)
In this work, I have tried to use more advanced steps in pandas to process petrophysical well log data. Functions are a convenient way of using programming to avoid repetition. Either python’s functions like apply and cut or self-defined functions(den & Tot_por in this work) can be useful to process well log data.
If you have any suggestions, I’m gladly open to see your comments!
|
[
{
"code": null,
"e": 381,
"s": 172,
"text": "In the previous work, we implemented 10 simple steps using pandas to process petrophysical well logs in LAS format. In this project, we will go deeper to use more advanced approaches to process well log data."
},
{
"code": null,
"e": 488,
"s": 381,
"text": "These 5 steps are:1) Function Definition2) Apply Function3) Lambda Function4) Cut Function5) Visualization"
},
{
"code": null,
"e": 896,
"s": 488,
"text": "To avoid extra work that we already did on specific well data previously, we will use the output of that project. If you worked on a previous project you may write the DataFrame into csv file (use to_csv command ) to use here. Otherwise, you can access through my github account and download the csv format called 1050383876v2.csv. You may also download the full Jupiter notebook file from my account, here."
},
{
"code": null,
"e": 950,
"s": 896,
"text": "Let’s bring required libraries on the workbook first:"
},
{
"code": null,
"e": 1058,
"s": 950,
"text": "import numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport seaborn as sns%matplotlib inline"
},
{
"code": null,
"e": 1100,
"s": 1058,
"text": "Then, read the csv data into df variable:"
},
{
"code": null,
"e": 1146,
"s": 1100,
"text": "df = pd.read_csv('1050383876v2.csv')df.head()"
},
{
"code": null,
"e": 1269,
"s": 1146,
"text": "Dataset seems clean. I also dropped the upper part where there were some NaN values, so the starting depth is 1000 meters."
},
{
"code": null,
"e": 1642,
"s": 1269,
"text": "Function in python is a group of statements that perform a specific task. A function can make the larger program more readable. It also can help us to prevent repetition. A function has a special structure as: 1- keyword def, 2- function name, 3- arguments that we pass values to a function, 4- a colon(:), 5- more statement in body, 6- Return statement which is optional."
},
{
"code": null,
"e": 2005,
"s": 1642,
"text": "There are several approaches to calculate porosity from petrophysical well logs. Here we will use the density method. Density tools measure rock medium bulk density(b) in wellbore conditions. Having knowledge of the fluid density (f) filling rock porosity and grain density(ma) can help us to calculate the percentage of void areas of the rocks. The equation is:"
},
{
"code": null,
"e": 2133,
"s": 2005,
"text": "Starting with def keyword, density porosity(den) function can be defined with the following arguments (parameters): rb, rf, rm."
},
{
"code": null,
"e": 2305,
"s": 2133,
"text": "def den(rb, rf, rm): # rb = bulk density from well log readings # rf = fluid density # rm = matrix density or grain density of rocks return (rm-rb)*100/(rm-rf)"
},
{
"code": null,
"e": 2540,
"s": 2305,
"text": "Simply, the function will return the density porosity as written in the last line of code. Here we prefer to have porosity in percentage(multiplied by 100). After defining the density porosity function, we can apply it to the dataset."
},
{
"code": null,
"e": 2742,
"s": 2540,
"text": "Using the apply function, a predefined function (here, density porosity) can be applied to each element of DataFrame either in column or row direction. If we leave it on default, it will on the column."
},
{
"code": null,
"e": 2794,
"s": 2742,
"text": "df['DNPOR'] = df['RHOB'].apply(den, rf=1, rm=2.71 )"
},
{
"code": null,
"e": 3153,
"s": 2794,
"text": "As den function takes 3 values (rb, rf, rm), we can introduce the main one from the dataset (rb =df[‘RHOB’]) and use the apply function to define rf and rm constants manually. Here I assume that fluid content is water with a density of 1 and the dominant mineral is Calcite with a density of 2.71. The Density porosity is stored in a new column called DNPOR."
},
{
"code": null,
"e": 3387,
"s": 3153,
"text": "Lambda function is a simple 1-line function that does not have def or return keywords. In fact, they are implicit. To use this function, we need to type lambda followed by parameters. Then, the colon comes before the return argument."
},
{
"code": null,
"e": 3461,
"s": 3387,
"text": "Total porosity is defined as the average of Density and Neutron porosity."
},
{
"code": null,
"e": 3495,
"s": 3461,
"text": "Tot_por = lambda DN,CN: (DN+CN)/2"
},
{
"code": null,
"e": 3678,
"s": 3495,
"text": "The function name is Tot_por. For lambda function, DN and CN are density and neutron parameters followed by a colon. The average of these two inputs will be returned by the function."
},
{
"code": null,
"e": 3734,
"s": 3678,
"text": "df['TPOR'] = Tot_por(df['CNPOR'], df[\"DNPOR\"])df.head()"
},
{
"code": null,
"e": 3914,
"s": 3734,
"text": "Calling the Tot_por function and introducing corresponding columns of DataFrame as input will create total porosity that will be stored in a new column called TPOR in the dataset."
},
{
"code": null,
"e": 4107,
"s": 3914,
"text": "When we need to segment and sort data values into specific bins, we can use the Cut function. Here we will use this function to define simple rock facies based on petrophysical properties, GR."
},
{
"code": null,
"e": 4312,
"s": 4107,
"text": "Facies classification is a huge topic in geoscience and various metrics can come to play but here, we look at it very simple. Based on GR reading in well logs, we can identify clean from shaly formations."
},
{
"code": null,
"e": 4392,
"s": 4312,
"text": "df['facies_gr'] = pd.cut(df['GR'], bins=[0,40,300], labels=['clean', 'shaly'] )"
},
{
"code": null,
"e": 4521,
"s": 4392,
"text": "A new column is added to the dataset based on GR readings which are binned between 0 and40(clean), and between 40and 300(shaly)."
},
{
"code": null,
"e": 4890,
"s": 4521,
"text": "Commonly, the matplotlib library is used in python for plotting. In this work, I prefer to use the seaborn library for its simplicity. I want to visualize a scatter plot of density porosity vs. neutron porosity with the legend color of facies that in the previous part we defined. This is simply accessible by one line of code while in matplotlib it requires for loop."
},
{
"code": null,
"e": 4946,
"s": 4890,
"text": "sns.lmplot(x='DNPOR', y='DT', hue='facies_gr', data=df)"
},
{
"code": null,
"e": 5262,
"s": 4946,
"text": "In this work, I have tried to use more advanced steps in pandas to process petrophysical well log data. Functions are a convenient way of using programming to avoid repetition. Either python’s functions like apply and cut or self-defined functions(den & Tot_por in this work) can be useful to process well log data."
}
] |
Apache IVY - Quick Guide
|
Apache Ivy is a very popular and very powerful dependency management tool used to manage dependencies in ANT based projects in the same fashion, how Apache Maven manages dependencies.
Apache Ivy is Apache ANT based, follows same design principles, is a subproject of Apache ANT and is actively managed and supported by Apache ANT Community.
Following are the important features of Apache Ivy.
ANT Based − Apache Ivy provides a dependencies management capability to ANT based projects. It is very simple to use as well.
ANT Based − Apache Ivy provides a dependencies management capability to ANT based projects. It is very simple to use as well.
Dependency Reports − Apache Ivy provides options to print dependencies graph in html as well as in reports format.
Dependency Reports − Apache Ivy provides options to print dependencies graph in html as well as in reports format.
Non-intrusive − Apache Ivy don't impose any restrictions as to be part of distribution. Even build files are not dependent on Apache Ivy.
Non-intrusive − Apache Ivy don't impose any restrictions as to be part of distribution. Even build files are not dependent on Apache Ivy.
Highly Flexible − Apache Ivy provides lots of default configurations and can be configured as per the requirement very easily.
Highly Flexible − Apache Ivy provides lots of default configurations and can be configured as per the requirement very easily.
Extendible − Apache Ivy can be extended easily. You can define your own repository, conflict resolvers and latest strategy.
Extendible − Apache Ivy can be extended easily. You can define your own repository, conflict resolvers and latest strategy.
Performance − Apache Ivy is built towards performance. It keeps a cache of library already downloaded. Looks into local repositories first to resolve dependencies than look into other repositories.
Performance − Apache Ivy is built towards performance. It keeps a cache of library already downloaded. Looks into local repositories first to resolve dependencies than look into other repositories.
Transitive Dependencies − Apache Ivy automatically manages transitive dependencies if one project or library depends upon other library which may need another library.
Transitive Dependencies − Apache Ivy automatically manages transitive dependencies if one project or library depends upon other library which may need another library.
Maven Repository − Apache Ivy follows conventions similar to Maven repository conventions. Apache Ivy can resolve dependencies using maven global repository.
Maven Repository − Apache Ivy follows conventions similar to Maven repository conventions. Apache Ivy can resolve dependencies using maven global repository.
Maven 2 POMs − Apache Ivy can read Maven 2 POMs as module descriptors, can set ivy as module descriptor. Thus it makes easy to migrate existing projects to IVY managed projects.
Maven 2 POMs − Apache Ivy can read Maven 2 POMs as module descriptors, can set ivy as module descriptor. Thus it makes easy to migrate existing projects to IVY managed projects.
Publishing − Apache Ivy provides supports to publish your project and simplifies the multi-project environment deployment process.
Publishing − Apache Ivy provides supports to publish your project and simplifies the multi-project environment deployment process.
Free to Use − Apache Ivy is open source and is free to use.
Free to Use − Apache Ivy is open source and is free to use.
Documentation − Apache Ivy has a very detailed documentation and tutorials available to learn.
Documentation − Apache Ivy has a very detailed documentation and tutorials available to learn.
Apache Ivy needs Java and ANT installed on your machine as the only requirement.
Apache Ant is distributed under the Apache Software License, a fully-fledged open source license certified by the open source initiative.
The latest Apache Ant version, including its full-source code, class files, and documentation can be found at http://ant.apache.org.
It is assumed that you have already downloaded and installed Java Development Kit (JDK) on your computer. If not, please follow the instructions here.
Ensure that the JAVA_HOME environment variable is set to the folder where your JDK is installed.
Ensure that the JAVA_HOME environment variable is set to the folder where your JDK is installed.
Download the binaries from https://ant.apache.org
Download the binaries from https://ant.apache.org
Unzip the zip file to a convenient location c:\folder. using Winzip, winRAR, 7-zip or similar tools.
Unzip the zip file to a convenient location c:\folder. using Winzip, winRAR, 7-zip or similar tools.
Create a new environment variable called ANT_HOME that points to the Ant installation folder, in this case c:\apache-ant-1.10.12-bin folder.
Create a new environment variable called ANT_HOME that points to the Ant installation folder, in this case c:\apache-ant-1.10.12-bin folder.
Append the path to the Apache Ant batch file to the PATH environment variable. In our case this would be the c:\apache-ant-1.10.12-bin\bin folder.
Append the path to the Apache Ant batch file to the PATH environment variable. In our case this would be the c:\apache-ant-1.10.12-bin\bin folder.
To verify the successful installation of Apache Ant on your computer, type ant on your command prompt.
You should see an output similar to −
C:\>ant -version
Apache Ant(TM) version 1.10.12 compiled on October 13 2021
If you do not see the above output, then please verify that you have followed the installation steps properly.
Download the binaries from https://ant.apache.org/ivy
Download the binaries from https://ant.apache.org/ivy
Unzip the zip file to a convenient location c:\folder. using Winzip, winRAR, 7-zip or similar tools.
Unzip the zip file to a convenient location c:\folder. using Winzip, winRAR, 7-zip or similar tools.
Copy the ivy-2.5.0.jar to c:\apache-ant-1.10.12-bin/lib folder.
Copy the ivy-2.5.0.jar to c:\apache-ant-1.10.12-bin/lib folder.
To verify the successful installation of Apache Ivy on your computer, create following build file in a folder E: > ivy.
<project name="test ivy installation"
default="test" xmlns:ivy="antlib:org.apache.ivy.ant">
<target name="test" description="Test ivy installation">
<ivy:settings />
</target>
</project>
You should see an output similar to −
C:\>ant
Buildfile: E:\ivy\build.xml
test:
BUILD SUCCESSFUL
Total time: 2 seconds
This tutorial also covers integration of Ant with Eclipse IDE. Hence, if you have not installed Eclipse already, please download and install Eclipse
To install Eclipse −
Download the latest Eclipse binaries from www.eclipse.org
Download the latest Eclipse binaries from www.eclipse.org
Unzip the Eclipse binaries to a convenient location, say c:\folder
Unzip the Eclipse binaries to a convenient location, say c:\folder
Run Eclipse from c:\eclipse\eclipse.exe
Run Eclipse from c:\eclipse\eclipse.exe
Consider the following example ivy.xml to understand Ivy terminology.
<?xml version="1.0" encoding="ISO-8859-1"?>
<ivy-module version="2.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ant.apache.org/ivy/schemas/ivy.xsd">
<info organisation="com.tutorialspoint" module="ivy-test" status="integration">
</info>
<dependencies>
<dependency org="commons-lang" name="commons-lang" rev="2.6" />
</dependencies>
</ivy-module>
Following are the important terms of Ivy Eco-System.
Organisation − As name suggests, it refers to the name of the company, individual developer or team name who creates the project or library. For example, com.tutorialspoint.
Organisation − As name suggests, it refers to the name of the company, individual developer or team name who creates the project or library. For example, com.tutorialspoint.
Module − As name suggests, it refers to the reusable unit or module. A module generally have a version attached to it. For example commons-lang, or ivy-test etc.
Module − As name suggests, it refers to the reusable unit or module. A module generally have a version attached to it. For example commons-lang, or ivy-test etc.
Module Descriptor − Module descriptor refers to ivy.xml file which describes a module. A module descriptor contains the identifier (org, name, branch and version), artifacts published, configurations and dependencies.
Module Descriptor − Module descriptor refers to ivy.xml file which describes a module. A module descriptor contains the identifier (org, name, branch and version), artifacts published, configurations and dependencies.
Artifact − Artifact refers to a single file as deliverable. For example, a jar file. Artifact can be of type: zip, gz etc. Jar, Source Jar, Javadoc Jar are various artifacts of a module.
Artifact − Artifact refers to a single file as deliverable. For example, a jar file. Artifact can be of type: zip, gz etc. Jar, Source Jar, Javadoc Jar are various artifacts of a module.
Type − Type identifies the artifact category like jar, war , src, doc etc.
Type − Type identifies the artifact category like jar, war , src, doc etc.
Artifact file name extension − Artifact extension like .jar, ,zip, .gz etc.
Artifact file name extension − Artifact extension like .jar, ,zip, .gz etc.
Module Revision − A unique revision number of the module or its version number.
Module Revision − A unique revision number of the module or its version number.
Status of Revision − Status of revision indicates the stability of the revision. Following are the important value of status −
integration − Represents continous development, nightly build etc.
milestone − Represents a distribution but not finalized.
release − Represents tested and completed, a major version.
Status of Revision − Status of revision indicates the stability of the revision. Following are the important value of status −
integration − Represents continous development, nightly build etc.
integration − Represents continous development, nightly build etc.
milestone − Represents a distribution but not finalized.
milestone − Represents a distribution but not finalized.
release − Represents tested and completed, a major version.
release − Represents tested and completed, a major version.
Repository − Similar to Maven repositories, repository represents a distribution site where ivy can search a library, artifacts, modules etc. A repository can be public, private or shared.
Repository − Similar to Maven repositories, repository represents a distribution site where ivy can search a library, artifacts, modules etc. A repository can be public, private or shared.
Ivy Settings − Apache Ivy follows Maven principles and comes with lot of default configurations. Default settings can be overridden by defining a ivysettings.xml file.
Ivy Settings − Apache Ivy follows Maven principles and comes with lot of default configurations. Default settings can be overridden by defining a ivysettings.xml file.
Apache Ivy follows Maven principles and comes with lot of default configurations. Default settings can be overridden by defining a ivysettings.xml file.
<ivysettings>
<properties file="${ivy.settings.dir}/ivysettings-file.properties" />
<settings defaultCache="${cache.dir}" defaultResolver="ibiblio" checkUpToDate="false" />
<resolvers>
<ibiblio name="ibiblio" />
<filesystem name="internal">
<ivy pattern="${repository.dir}/[module]/ivy-[revision].xml" />
<artifact pattern="${repository.dir}/[module]/[artifact]-[revision].[ext]" />
</filesystem>
</resolvers>
<modules>
<module organisation="tutorialspoint" name=".*" resolver="internal" />
</modules>
</ivysettings>
Following are the important tags of Ivy Setting file.
property − To set an ivy variable. Cardinality: 0..n
property − To set an ivy variable. Cardinality: 0..n
properties − To set an ivy variables using properties file. Cardinality: 0..n
properties − To set an ivy variables using properties file. Cardinality: 0..n
settings − To configure ivy with default values. Cardinality: 0..1
settings − To configure ivy with default values. Cardinality: 0..1
include − To include another settings file. Cardinality: 0..n
include − To include another settings file. Cardinality: 0..n
classpath − To add a location in the classpath used to load plugins. Cardinality: 0..n
classpath − To add a location in the classpath used to load plugins. Cardinality: 0..n
typedef − To define new types in ivy. Cardinality: 0..n
typedef − To define new types in ivy. Cardinality: 0..n
lock-strategies − To define lock strategies. Cardinality: 0..1
lock-strategies − To define lock strategies. Cardinality: 0..1
caches − To define repository cache managers. Cardinality: 0..1
caches − To define repository cache managers. Cardinality: 0..1
latest-strategies − To define latest strategies. Cardinality: 0..1
latest-strategies − To define latest strategies. Cardinality: 0..1
parsers − To define module descriptor parsers. Cardinality: 0..1
parsers − To define module descriptor parsers. Cardinality: 0..1
version-matchers − To define new version matchers. Cardinality: 0..1
version-matchers − To define new version matchers. Cardinality: 0..1
triggers − To register triggers on ivy events. Cardinality: 0..1
triggers − To register triggers on ivy events. Cardinality: 0..1
namespaces − To define new namespaces. Cardinality: 0..1
namespaces − To define new namespaces. Cardinality: 0..1
macrodef − To define a new macro resolver. Cardinality: 0..n
macrodef − To define a new macro resolver. Cardinality: 0..n
resolvers − To define dependency resolvers. Cardinality: 0..1
resolvers − To define dependency resolvers. Cardinality: 0..1
conflict-managers − To define conflicts managers. Cardinality: 0..1
conflict-managers − To define conflicts managers. Cardinality: 0..1
modules − To define rules between modules and dependency resolvers. Cardinality: 0..1
modules − To define rules between modules and dependency resolvers. Cardinality: 0..1
outputters − To define the list of available report outputters. Cardinality: 0..1
outputters − To define the list of available report outputters. Cardinality: 0..1
statuses − To define the list of available statuses. Cardinality: 0..1
statuses − To define the list of available statuses. Cardinality: 0..1
IvyDE is an Eclipse plugin provided by Apache. To install IvyDE, start Eclipse and navigate to Help > Install New Software. It displays the Available Softwares window. Enter IvyDE update site http://www.apache.org/dist/ant/ivyde/updatesite/ and press enter key. It displays the following plugins.
Click Next and you will see the following screen.
If you are facing any error while installing the plugin then just restart the process. After successful installation, you will see the plugin in eclipe.
Now you can do the dependency management using Eclipse and Ivy.
Resolve task is used to resolve dependencies described in ivy.xml, download and put them in ivy cache.
Let's first create a java file Tester.java in E: > ivy > src > com > tutorialspoint folder which will act as source folder for ant project.
Application.java
package com.tutorialspoint;
import org.apache.commons.lang.StringUtils;
public class Application {
public static void main(String[] args) {
String string = StringUtils.upperCase("Ivy Beginner Guide");
System.out.println(string);
}
}
Above class is using apache commons lang library to use its class StringUtils. Ivy should download this library and thus it should be defined under dependencies section in ivy.xml. Following is the ivy.xml created in E: > ivy folder.
ivy.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<ivy-module version="2.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ant.apache.org/ivy/schemas/ivy.xsd">
<info
organisation="com.tutorialspoint"
module="test"
status="integration">
</info>
<dependencies>
<dependency org="org.apache.commons" name="commons-lang3" rev="3.9"/>
</dependencies>
</ivy-module>
Following are the important terms.
ivy-module − Root element to identify ivy version, namespace etc.
ivy-module − Root element to identify ivy version, namespace etc.
info − element to identify the project as a unique entity.
organisation − name of the organization
module − name of the module
status − status like release, integration or milestone.
info − element to identify the project as a unique entity.
organisation − name of the organization
organisation − name of the organization
module − name of the module
module − name of the module
status − status like release, integration or milestone.
status − status like release, integration or milestone.
dependencies − element to contain project dependencies as dependency tags which has following attributes.
org − name of the dependency's organization
name − name of the dependency.
rev − version of the dependency.
dependencies − element to contain project dependencies as dependency tags which has following attributes.
org − name of the dependency's organization
org − name of the dependency's organization
name − name of the dependency.
name − name of the dependency.
rev − version of the dependency.
rev − version of the dependency.
build.xml
<project name="test" default="resolve" xmlns:ivy="antlib:org.apache.ivy.ant">
<target name="resolve" description="resolve dependencies">
<ivy:resolve />
</target>
</project<
Following are the important terms.
project − Root element to identify project name, default task namespace for ivy etc.
project − Root element to identify project name, default task namespace for ivy etc.
target − target element to create a new task and its description. This contains an ivy resolve task. When ant builds the project, it runs the ivy resolve task which then resolves the dependencies using ivy.
target − target element to create a new task and its description. This contains an ivy resolve task. When ant builds the project, it runs the ivy resolve task which then resolves the dependencies using ivy.
As we've all the files ready. Just go the console. Navigate to E: > ivy folder and run the ant command.
E:\ivy > ant
Ivy will come into action, resolving the dependencies, you will see the following result.
Buildfile: E:\ivy\build.xml
resolve:
[ivy:resolve] :: Apache Ivy 2.5.0 - 20191020104435 :: https://ant.apache.org/ivy
/ ::
[ivy:resolve] :: loading settings :: url = jar:file:/E:/Apache/apache-ant-1.9.14
/lib/ivy-2.5.0.jar!/org/apache/ivy/core/settings/ivysettings.xml
[ivy:resolve] :: resolving dependencies :: com.tutorialspoint#test;working@Acer-
PC
[ivy:resolve] confs: [default]
[ivy:resolve] found commons-lang#commons-lang;2.6 in public
[ivy:resolve] found junit#junit;3.8.1 in public
[ivy:resolve] :: resolution report :: resolve 375ms :: artifacts dl 79ms
---------------------------------------------------------------------
| | modules || artifacts |
| conf | number| search|dwnlded|evicted|| number|dwnlded|
---------------------------------------------------------------------
| default | 2 | 2 | 0 | 0 || 4 | 0 |
---------------------------------------------------------------------
[ivy:retrieve] :: retrieving :: com.tutorialspoint#test [sync]
[ivy:retrieve] confs: [default]
[ivy:retrieve] 0 artifacts copied, 2 already retrieved (0kB/101ms)
BUILD SUCCESSFUL
Total time: 1 second
E:\ivy>
Following are the important terms.
conf − configuration, in our case we are using default configuration.
conf − configuration, in our case we are using default configuration.
modules − indicates the total number of modules, downloaded modules etc.
modules − indicates the total number of modules, downloaded modules etc.
artifacts − indicates the total number of artifacts, downloaded artifacts etc.
artifacts − indicates the total number of artifacts, downloaded artifacts etc.
You can verify the downloaded files in ivy cache's default location in ${ivy.default.ivy.user.dir} > .ivy2 > cache folder. And ${ivy.default.ivy.user.dir} is by default user home: $HOME.
Install task is used to install a module and its dependencies in a resolver. It is used when a public artifact is to be downloaded and used in private repository. By default, a user local repository is his/her private repository and is present in ${ivy.default.ivy.user.dir}/local.
Let's create Tester.java, build.xml and ivy.xml as described in IVY - Resolve Task chapter.
Update the build.xml to use the ivy install task.
build.xml
<project name="test" default="resolve" xmlns:ivy="antlib:org.apache.ivy.ant">
<target name="resolve" description="resolve dependencies">
<ivy:resolve />
</target>
<target name="install" description="install dependencies">
<ivy:install organisation="commons-lang" module="commons-lang"
revision="2.6" transitive="true" overwrite="false"
from="public" to="local" />
</target>
</project>
Following are the important terms.
organisation − name of the organization.
organisation − name of the organization.
module − module name of the project.
module − module name of the project.
revision − version of the project.
revision − version of the project.
from − from repository type.
from − from repository type.
to − to repository type.
to − to repository type.
As we've all the files ready. Just go the console. Navigate to E: > ivy folder and run the ant command.
E:\ivy > ant install
Ivy will come into action, resolving the dependencies, you will see the following result.
E:\ivy > ant install
Buildfile: E:\ivy\build.xml
install:
[ivy:install] :: Apache Ivy 2.5.0 - 20191020104435 :: https://ant.apache.org/ivy
/ ::
[ivy:install] :: loading settings :: url = jar:file:/E:/Apache/apache-ant-1.9.14
/lib/ivy-2.5.0.jar!/org/apache/ivy/core/settings/ivysettings.xml
[ivy:install] :: installing commons-lang#commons-lang;2.6 ::
[ivy:install] :: resolving dependencies ::
[ivy:install] found commons-lang#commons-lang;2.6 in public
[ivy:install] found junit#junit;3.8.1 in public
[ivy:install] :: downloading artifacts to cache ::
[ivy:install] :: installing in local ::
[ivy:install] published commons-lang to C:\Users\Acer\.ivy2\local\commons-lang
\commons-lang\2.6.part\sources\commons-lang.jar
[ivy:install] published commons-lang to C:\Users\Acer\.ivy2\local\commons-lang
\commons-lang\2.6.part\jars\commons-lang.jar
[ivy:install] published commons-lang to C:\Users\Acer\.ivy2\local\commons-lang
\commons-lang\2.6.part\javadocs\commons-lang.jar
[ivy:install] published ivy to C:\Users\Acer\.ivy2\local\commons-lang\commons-
lang\2.6.part\ivys\ivy.xml
[ivy:install] publish committed: moved C:\Users\Acer\.ivy2\local\commons-lang\
commons-lang\2.6.part
[ivy:install] to C:\Users\Acer\.ivy2\local\commons-lang\commons-lang\2
.6
[ivy:install] published junit to C:\Users\Acer\.ivy2\local\junit\junit\3.8.1.p
art\jars\junit.jar
[ivy:install] published ivy to C:\Users\Acer\.ivy2\local\junit\junit\3.8.1.par
t\ivys\ivy.xml
[ivy:install] publish committed: moved C:\Users\Acer\.ivy2\local\junit\junit\3
.8.1.part
[ivy:install] to C:\Users\Acer\.ivy2\local\junit\junit\3.8.1
[ivy:install] :: install resolution report ::
[ivy:install] :: resolution report :: resolve 0ms :: artifacts dl 21ms
---------------------------------------------------------------------
| | modules || artifacts |
| conf | number| search|dwnlded|evicted|| number|dwnlded|
---------------------------------------------------------------------
| default | 2 | 0 | 0 | 0 || 4 | 0 |
---------------------------------------------------------------------
BUILD SUCCESSFUL
Total time: 43 seconds
You can verify the downloaded files in ivy cache's default local repository location ${ivy.default.ivy.user.dir} > .ivy2 > local directory.
retrieve task is used to resolve dependencies to a specified location in project workspace.
Let's create Tester.java, build.xml and ivy.xml as described in IVY - Resolve Task chapter.
Update the build.xml to use the ivy retrieve task.
build.xml
<project name="test" default="resolve" xmlns:ivy="antlib:org.apache.ivy.ant">
<target name="resolve" description="resolve dependencies">
<ivy:resolve />
<ivy:retrieve sync="true" type="jar" />
</target>
</project>
Following are the important terms.
sync − sync true ensure that lib directory is up-to-date and any extra file gets deleted.
sync − sync true ensure that lib directory is up-to-date and any extra file gets deleted.
type − type directs ivy to copy only specified type of artifacts like jar. Source jar, javadoc jar will be ignored. type for source jar is src or source and doc or bundle for javadoc jar.
type − type directs ivy to copy only specified type of artifacts like jar. Source jar, javadoc jar will be ignored. type for source jar is src or source and doc or bundle for javadoc jar.
retrieve tasks copies the resolved dependencies in the lib directory of the project by default and can be changed using pattern attribute.
As we've all the files ready. Just go the console. Navigate to E: > ivy folder and run the ant command.
E:\ivy > ant
Ivy will come into action, resolving the dependencies, you will see the following result.
Buildfile: E:\ivy\build.xml
resolve:
[ivy:resolve] :: Apache Ivy 2.5.0 - 20191020104435 :: https://ant.apache.org/ivy
/ ::
[ivy:resolve] :: loading settings :: url = jar:file:/E:/Apache/apache-ant-1.9.14
/lib/ivy-2.5.0.jar!/org/apache/ivy/core/settings/ivysettings.xml
[ivy:resolve] :: resolving dependencies :: com.tutorialspoint#test;working@Acer-
PC
[ivy:resolve] confs: [default]
[ivy:resolve] found commons-lang#commons-lang;2.6 in public
[ivy:resolve] found junit#junit;3.8.1 in public
[ivy:resolve] :: resolution report :: resolve 316ms :: artifacts dl 18ms
---------------------------------------------------------------------
| | modules || artifacts |
| conf | number| search|dwnlded|evicted|| number|dwnlded|
---------------------------------------------------------------------
| default | 2 | 2 | 0 | 0 || 4 | 0 |
---------------------------------------------------------------------
[ivy:retrieve] :: retrieving :: com.tutorialspoint#test [sync]
[ivy:retrieve] confs: [default]
[ivy:retrieve] 0 artifacts copied, 2 already retrieved (0kB/2756ms)
BUILD SUCCESSFUL
Total time: 31 seconds
You can verify the downloaded files in project lib directory.
cachepath task is used to create an ANT classpath with resolved artifacts present in the cache. As ANT needs jars to be classpath to compile java files, Ivy cachepath builds the classpath.
Let's create Tester.java, build.xml and ivy.xml as described in IVY - Resolve Task chapter.
Update the build.xml to use the ivy retrieve task.
build.xml
<project name="test" default="resolve" xmlns:ivy="antlib:org.apache.ivy.ant">
<target name="resolve" description="resolve dependencies">
<ivy:resolve />
<ivy:cachepath pathid="new.classpath" />
</target>
<target name="compile" depends="resolve" description="Compile">
<mkdir dir="build/classes" />
<javac srcdir="src" destdir="build/classes">
<classpath refid="new.classpath" />
</javac>
</target>
</project>
Following are the important terms.
pathid − id of the classpath where cached jars are present.
pathid − id of the classpath where cached jars are present.
retrieve tasks copies the resolved dependencies in the lib directory of the project by default and can be changed using pattern attribute.
As we've all the files ready. Just go the console. Navigate to E: > ivy folder and run the ant command.
E:\ivy > ant compile
Ivy will come into action, resolving the dependencies, you will see the following result.
Buildfile: E:\ivy\build.xml
resolve:
[ivy:resolve] :: Apache Ivy 2.5.0 - 20191020104435 :: https://ant.apache.org/ivy
/ ::
[ivy:resolve] :: loading settings :: url = jar:file:/E:/Apache/apache-ant-1.9.14
/lib/ivy-2.5.0.jar!/org/apache/ivy/core/settings/ivysettings.xml
[ivy:resolve] :: resolving dependencies :: com.tutorialspoint#test;working@Acer-
PC
[ivy:resolve] confs: [default]
[ivy:resolve] found commons-lang#commons-lang;2.6 in public
[ivy:resolve] found junit#junit;3.8.1 in public
[ivy:resolve] :: resolution report :: resolve 2314ms :: artifacts dl 15ms
---------------------------------------------------------------------
| | modules || artifacts |
| conf | number| search|dwnlded|evicted|| number|dwnlded|
---------------------------------------------------------------------
| default | 2 | 2 | 0 | 0 || 4 | 0 |
---------------------------------------------------------------------
compile:
[javac] E:\ivy\build.xml:13: warning: 'includeantruntime' was not set, defau
lting to build.sysclasspath=last; set to false for repeatable builds
[javac] Compiling 1 source file to E:\ivy\build\classes
BUILD SUCCESSFUL
Total time: 3 seconds
You can verify the compiled class file in project build directory.
publish task is used to publish current artifacts and its resolved descriptor files to mentioned repository.
Let's create Tester.java, build.xml and ivy.xml as described in IVY - Resolve Task chapter.
Update the build.xml to use the ivy publish task. First we'll create a jar file and then publish it.
build.xml
<project name="test" default="resolve" xmlns:ivy="antlib:org.apache.ivy.ant">
<property name = "build.dir" value = "build"/>
<target name="resolve" description="resolve dependencies">
<ivy:resolve />
</target>
<target name = "jar">
<jar destfile = "${build.dir}/lib/application.jar"
basedir = "${build.dir}/classes">
<manifest>
<attribute name = "Main-Class" value = "com.tutorialspoint.Application"/>
</manifest>
</jar>
</target>
<target name="publish" depends="jar">
<ivy:resolve />
<ivy:publish resolver="local" pubrevision="1.0" overwrite="true">
<artifacts pattern="${build.dir}/lib/[artifact].[ext]" />
</ivy:publish>
</target>
</project>
Following are the important terms.
resolver − resolver to be used for publication.
resolver − resolver to be used for publication.
pattern − pattern to locate the artifact.
pattern − pattern to locate the artifact.
Here publish task first build the jar, then resolve the dependencies, set the information and then publish the artifact to local repository.
As we've all the files ready. Just go the console. Navigate to E: > ivy folder and run the ant command.
E:\ivy > ant publish
Ivy will come into action, resolving the dependencies, you will see the following result.
E:\ivy > ant publish
Buildfile: E:\ivy\build.xml
jar:
publish:
[ivy:resolve] :: Apache Ivy 2.5.0 - 20191020104435 :: https://ant.apache.org/ivy
/ ::
[ivy:resolve] :: loading settings :: url = jar:file:/E:/Apache/apache-ant-1.9.14
/lib/ivy-2.5.0.jar!/org/apache/ivy/core/settings/ivysettings.xml
[ivy:resolve] :: resolving dependencies :: com.tutorialspoint#test;1.0.0
[ivy:resolve] confs: [default]
[ivy:resolve] found commons-lang#commons-lang;2.6 in public
[ivy:resolve] found junit#junit;3.8.1 in public
[ivy:resolve] :: resolution report :: resolve 121ms :: artifacts dl 15ms
---------------------------------------------------------------------
| | modules || artifacts |
| conf | number| search|dwnlded|evicted|| number|dwnlded|
---------------------------------------------------------------------
| default | 2 | 2 | 0 | 0 || 4 | 0 |
---------------------------------------------------------------------
[ivy:publish] :: publishing :: com.tutorialspoint#test
[ivy:publish] published application to C:\Users\Acer\.ivy2\local\com.tutorials
point\test\1.0\jars\application.jar
[ivy:publish] published ivy to C:\Users\Acer\.ivy2\local\com.tutorialspoint\te
st\1.0\ivys\ivy.xml
BUILD SUCCESSFUL
Total time: 1 second
You can verify the publish ivy artifacts in local repository.
info task is used to set ivy specific information in a file and can be used without any dependency resolution.
Let's create Tester.java, build.xml and ivy.xml as described in IVY - Resolve Task chapter.
Update the build.xml to use the ivy publish task. First we'll create a jar file and then publish it. Before publish task, we've set the required ivy information using info task.
build.xml
<project name="test" default="resolve" xmlns:ivy="antlib:org.apache.ivy.ant">
<property name = "build.dir" value = "build"/>
<target name="resolve" description="resolve dependencies">
<ivy:resolve />
</target>
<target name = "jar">
<jar destfile = "${build.dir}/lib/application.jar"
basedir = "${build.dir}/classes">
<manifest>
<attribute name = "Main-Class" value = "com.tutorialspoint.Application"/>
</manifest>
</jar>
</target>
<target name="publish" depends="jar">
<ivy:info file="ivy.xml" />
<ivy:publish resolver="local" pubrevision="1.0" overwrite="true">
<artifacts pattern="${build.dir}/lib/[artifact].[ext]" />
</ivy:publish>
</target>
</project>
Here publish task first build the jar, then set the information using ivy:info task and then publish the artifact to local repository.
As we've all the files ready. Just go the console. Navigate to E: > ivy folder and run the ant command.
E:\ivy > ant publish
Ivy will come into action, resolving the dependencies, you will see the following result.
Buildfile: E:\ivy\build.xml
jar:
publish:
[ivy:info] :: Apache Ivy 2.5.0 - 20191020104435 :: https://ant.apache.org/ivy/
::
[ivy:info] :: loading settings :: url = jar:file:/E:/Apache/apache-ant-1.9.14/l
ib/ivy-2.5.0.jar!/org/apache/ivy/core/settings/ivysettings.xml
[ivy:publish] :: publishing :: com.tutorialspoint#test
[ivy:publish] published application to C:\Users\Acer\.ivy2\local\com.tutorials
point\test\1.0\jars\application.jar
[ivy:publish] published ivy to C:\Users\Acer\.ivy2\local\com.tutorialspoint\te
st\1.0\ivys\ivy.xml
BUILD SUCCESSFUL
Total time: 0 seconds
If we do not put the info task then publish task will not work. Use the below modified build.xml and see the error for missing organization attribute and so on.
build.xml
<project name="test" default="resolve" xmlns:ivy="antlib:org.apache.ivy.ant">
<property name = "build.dir" value = "build"/>
<target name="resolve" description="resolve dependencies">
<ivy:resolve />
</target>
<target name = "jar">
<jar destfile = "${build.dir}/lib/application.jar"
basedir = "${build.dir}/classes">
<manifest>
<attribute name = "Main-Class" value = "com.tutorialspoint.Application"/>
</manifest>
</jar>
</target>
<target name="publish" depends="jar">
<ivy:publish resolver="local" pubrevision="1.0" overwrite="true">
<artifacts pattern="${build.dir}/lib/[artifact].[ext]" />
</ivy:publish>
</target>
</project>
Navigate to E: > ivy folder and run the ant command.
E:\ivy > ant publish
Ivy will come into action, resolving the dependencies, you will see the following result.
Buildfile: E:\ivy\build.xml
jar:
publish:
[ivy:publish] :: Apache Ivy 2.5.0 - 20191020104435 :: https://ant.apache.org/ivy
/ ::
[ivy:publish] :: loading settings :: url = jar:file:/E:/Apache/apache-ant-1.9.14
/lib/ivy-2.5.0.jar!/org/apache/ivy/core/settings/ivysettings.xml
BUILD FAILED
E:\ivy\build.xml:28: no organisation provided for ivy publish task: It can eithe
r be set explicitly via the attribute 'organisation' or via 'ivy.organisation' p
roperty or a prior call to <resolve/>
Total time: 3 seconds
Resolvers are used to find locations from where a library is to be downloaded. A dependency resolver also handles common tasks. Ivy provides two types of Resolvers.
Composite − A resolver which uses other resolvers to do its tasks.
Composite − A resolver which uses other resolvers to do its tasks.
Standard − A resolver performs the required tasks.
Standard − A resolver performs the required tasks.
Following table lists down the standard resolvers and their usage.
IvyRep (Standard)
IBiblio (Standard)
BinTray (Standard)
Packager (Standard)
FileSystem (Standard)
URL (Standard)
MirroredURL (Standard)
VFS (Standard)
SSH (Standard)
SFTP (Standard)
Jar (Standard)
Chain (Composite)
Dual (Composite)
OBR (Standard)
Eclipse updatesite (Standard)
OSGi-agg (Composite)
Let's create Tester.java, build.xml and ivy.xml in a new project under E: > ivy2 folder similar to as described in IVY - Resolve Task chapter. Create a settings folder under E: > ivy2. Create the ivysettings.xml in the settings folder.
build.xml
<project name="test" default="resolve" xmlns:ivy="antlib:org.apache.ivy.ant">
<property name = "build.dir" value = "build"/>
<property name = "base.dir" value = ""/>
<target name="resolve" description="resolve dependencies">
<ivy:resolve />
</target>
<target name="compile" depends="resolve" description="Compile">
<mkdir dir="build/classes" />
<javac srcdir="src" destdir="build/classes">
<classpath refid="new.classpath" />
</javac>
</target>
</project>
ivy.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<ivy-module version="2.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ant.apache.org/ivy/schemas/ivy.xsd">
<info organisation="org.apache" module="chained-resolvers"/>
<dependencies>
<dependency org="commons-lang" name="commons-lang" rev="2.6" conf="default"/>
<dependency org="com.tutorialspoint" name="test" rev="1.0"/>
</dependencies>
</ivy-module>
Here we've added two dependencies,one of commons-lang library and another as test which we published in IVY - Publish Task chapter.
ivysettings.xml
<ivysettings>
<settings defaultResolver="multiresolver"/>
<resolvers>
<chain name="multiresolver">
<filesystem name="libraries">
<artifact pattern="${ivy.settings.dir}/repository/[artifact]-[revision].[ext]"/>
</filesystem>
<ibiblio name="ibiblio" m2compatible="true"/>
</chain>
</resolvers>
</ivysettings>
Here we've added created a composite resolver using chain resolver which has two resolver, one named libraries to locate libaries on local repository and one named ibiblio on maven public repository.
As we've all the files ready. Just go the console. Navigate to E: > ivy2 folder and run the ant command.
E:\ivy > ant
Ivy will come into action, resolving the dependencies, you will see the following result.
Buildfile: E:\ivy2\build.xml
resolve:
[ivy:resolve] :: Apache Ivy 2.5.0 - 20191020104435 :: https://ant.apache.org/ivy
/ ::
[ivy:resolve] :: loading settings :: url = jar:file:/E:/Apache/apache-ant-1.9.14
/lib/ivy-2.5.0.jar!/org/apache/ivy/core/settings/ivysettings.xml
[ivy:resolve] :: resolving dependencies :: org.apache#chained-resolvers;working@
Acer-PC
[ivy:resolve] confs: [default]
[ivy:resolve] found commons-lang#commons-lang;2.6 in public
[ivy:resolve] found com.tutorialspoint#test;1.0 in local
[ivy:resolve] found junit#junit;3.8.1 in public
[ivy:resolve] downloading C:\Users\Acer\.ivy2\local\com.tutorialspoint\test\1.0\
jars\application.jar ...
[ivy:resolve] .. (1kB)
[ivy:resolve] .. (0kB)
[ivy:resolve] [SUCCESSFUL ] com.tutorialspoint#test;1.0!application.jar (13ms)
[ivy:resolve] :: resolution report :: resolve 1085ms :: artifacts dl 22ms
---------------------------------------------------------------------
| | modules || artifacts |
| conf | number| search|dwnlded|evicted|| number|dwnlded|
---------------------------------------------------------------------
| default | 3 | 3 | 1 | 0 || 5 | 1 |
---------------------------------------------------------------------
BUILD SUCCESSFUL
Total time: 9 seconds
In the logs you can verify that we have used both local and public repository resolvers.
A local repository is a private repository of a user. It is very useful in case a user is using a library whose version has been changed on other places and have breaking changes. In case of local repository, ivy will use the library present in the local if found and will not look into public or shared repositories.
By default, local repository is present in ${ivy.default.ivy.user.dir}/local folder. If you want to change it, the use the ivy.local.default.root variable in ant file.
build.xml
<target name="resolve">
<property name="ivy.local.default.root" value="/opt/ivy/repository/local"/>
<ivy:resolve />
</target>
Other properties like ivy pattern and artifact pattern can also be customized as follows −
build.xml
<target name="resolve">
<property name="ivy.local.default.root" value="/opt/ivy/repository/local"/>
<property name="ivy.local.default.ivy.pattern" value="[module]/[revision]/ivy.xml"/>
<property name="ivy.local.default.artifact.pattern" value="[module]/[revision]/[artifact].[ext]"/>
<ivy:resolve />
</target>
By default ivy has its configurations in ivysettings.xml present in ivy.jar.
ivysettings.xml
<ivysettings>
<settings defaultResolver="default"/>
<include url="${ivy.default.settings.dir}/ivysettings-public.xml"/>
<include url="${ivy.default.settings.dir}/ivysettings-shared.xml"/>
<include url="${ivy.default.settings.dir}/ivysettings-local.xml"/>
<include url="${ivy.default.settings.dir}/ivysettings-main-chain.xml"/>
<include url="${ivy.default.settings.dir}/ivysettings-default-chain.xml"/>
</ivysettings>
To override local repository setting, update the contents of ivysettings-local.xml.
ivysettings-local.xml
<ivysettings>
<property name="ivy.local.default.root" value="${ivy.default.ivy.user.dir}/local" override="false"/>
<property name="ivy.local.default.ivy.pattern" value="[organisation]/[module]/[revision]/[type]s/[artifact].[ext]" override="false"/>
<property name="ivy.local.default.artifact.pattern" value="[organisation]/[module]/[revision]/[type]s/[artifact].[ext]" override="false"/>
<resolvers>
<filesystem name="local">
<ivy pattern="${ivy.local.default.root}/${ivy.local.default.ivy.pattern}" />
<artifact pattern="${ivy.local.default.root}/${ivy.local.default.artifact.pattern}" />
</filesystem>
</resolvers>
</ivysettings>
A shared repository is a team level shared repository of a team. It is very common to be overridden in organizations.
By default, shared repository is present in ${ivy.default.ivy.user.dir}/shared folder. If you want to change it, the use the ivy.shared.default.root variable in ant file.
build.xml
<target name="resolve">
<property name="ivy.shared.default.root" value="/opt/ivy/repository/shared"/>
<ivy:resolve />
</target>
Other properties like ivy pattern and artifact pattern can also be customized as follows −
build.xml
<target name="resolve">
<property name="ivy.shared.default.root" value="/opt/ivy/repository/shared"/>
<property name="ivy.shared.default.ivy.pattern" value="[organisation]/[module]/[revision]/ivy.xml"/>
<property name="ivy.shared.default.artifact.pattern" value="[organisation]/[module]/[revision]/[artifact].[ext]"/>
<ivy:resolve />
</target>
By default ivy has its configurations in ivysettings.xml present in ivy.jar.
ivysettings.xml
<ivysettings>
<settings defaultResolver="default"/>
<include url="${ivy.default.settings.dir}/ivysettings-public.xml"/>
<include url="${ivy.default.settings.dir}/ivysettings-shared.xml"/>
<include url="${ivy.default.settings.dir}/ivysettings-local.xml"/>
<include url="${ivy.default.settings.dir}/ivysettings-main-chain.xml"/>
<include url="${ivy.default.settings.dir}/ivysettings-default-chain.xml"/>
</ivysettings>
To override shared repository setting, update the contents of ivysettings-shared.xml.
ivysettings-shared.xml
<ivysettings>
<property name="ivy.shared.default.root" value="${ivy.default.ivy.user.dir}/shared" override="false"/>
<property name="ivy.shared.default.ivy.pattern" value="[organisation]/[module]/[revision]/[type]s/[artifact].[ext]" override="false"/>
<property name="ivy.shared.default.artifact.pattern" value="[organisation]/[module]/[revision]/[type]s/[artifact].[ext]" override="false"/>
<resolvers>
<filesystem name="shared">
<ivy pattern="${ivy.shared.default.root}/${ivy.shared.default.ivy.pattern}" />
<artifact pattern="${ivy.shared.default.root}/${ivy.shared.default.artifact.pattern}" />
</filesystem>
</resolvers>
</ivysettings>
A public repository is a repository accessible using internet and have third party modules. By default ibiblio in m2 compatible mode is the public repository. It is also referred as maven 2 public repository.
By default ivy has its configurations in ivysettings.xml present in ivy.jar.
ivysettings.xml
<ivysettings>
<settings defaultResolver="default"/>
<include url="${ivy.default.settings.dir}/ivysettings-public.xml"/>
<include url="${ivy.default.settings.dir}/ivysettings-shared.xml"/>
<include url="${ivy.default.settings.dir}/ivysettings-local.xml"/>
<include url="${ivy.default.settings.dir}/ivysettings-main-chain.xml"/>
<include url="${ivy.default.settings.dir}/ivysettings-default-chain.xml"/>
</ivysettings>
To override public repository setting, update the contents of ivysettings-public.xml or create the ivysettings.xml in setting folder of your project.
ivysettings.xml
<ivysettings>
<settings defaultResolver="default"/>
<include url="http://customserver/ivy/ivysettings-public.xml"/>
<include url="${ivy.default.settings.dir}/ivysettings-shared.xml"/>
<include url="${ivy.default.settings.dir}/ivysettings-local.xml"/>
<include url="${ivy.default.settings.dir}/ivysettings-main-chain.xml"/>
<include url="${ivy.default.settings.dir}/ivysettings-default-chain.xml"/>
</ivysettings>
Update the default ivysetting-public.xml contents.
Original - ivysetting-public.xml
<ivysettings>
<resolvers>
<ibiblio name="public" m2compatible="true"/>
</resolvers>
</ivysettings>
Updated - ivysetting-public.xml
<ivysettings>
<resolvers>
<filesystem name="public">
<ivy pattern="/path/to/my/public/rep/[organisation]/[module]/ivy-[revision].xml" />
<artifact pattern="/path/to/my/public/rep/[organisation]/[module]/[artifact]-[revision].[ext]" />
</filesystem>
</resolvers>
</ivysettings>
46 Lectures
3.5 hours
Arnab Chakraborty
23 Lectures
1.5 hours
Mukund Kumar Mishra
16 Lectures
1 hours
Nilay Mehta
52 Lectures
1.5 hours
Bigdata Engineer
14 Lectures
1 hours
Bigdata Engineer
23 Lectures
1 hours
Bigdata Engineer
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2188,
"s": 2004,
"text": "Apache Ivy is a very popular and very powerful dependency management tool used to manage dependencies in ANT based projects in the same fashion, how Apache Maven manages dependencies."
},
{
"code": null,
"e": 2345,
"s": 2188,
"text": "Apache Ivy is Apache ANT based, follows same design principles, is a subproject of Apache ANT and is actively managed and supported by Apache ANT Community."
},
{
"code": null,
"e": 2397,
"s": 2345,
"text": "Following are the important features of Apache Ivy."
},
{
"code": null,
"e": 2523,
"s": 2397,
"text": "ANT Based − Apache Ivy provides a dependencies management capability to ANT based projects. It is very simple to use as well."
},
{
"code": null,
"e": 2649,
"s": 2523,
"text": "ANT Based − Apache Ivy provides a dependencies management capability to ANT based projects. It is very simple to use as well."
},
{
"code": null,
"e": 2764,
"s": 2649,
"text": "Dependency Reports − Apache Ivy provides options to print dependencies graph in html as well as in reports format."
},
{
"code": null,
"e": 2879,
"s": 2764,
"text": "Dependency Reports − Apache Ivy provides options to print dependencies graph in html as well as in reports format."
},
{
"code": null,
"e": 3017,
"s": 2879,
"text": "Non-intrusive − Apache Ivy don't impose any restrictions as to be part of distribution. Even build files are not dependent on Apache Ivy."
},
{
"code": null,
"e": 3155,
"s": 3017,
"text": "Non-intrusive − Apache Ivy don't impose any restrictions as to be part of distribution. Even build files are not dependent on Apache Ivy."
},
{
"code": null,
"e": 3282,
"s": 3155,
"text": "Highly Flexible − Apache Ivy provides lots of default configurations and can be configured as per the requirement very easily."
},
{
"code": null,
"e": 3409,
"s": 3282,
"text": "Highly Flexible − Apache Ivy provides lots of default configurations and can be configured as per the requirement very easily."
},
{
"code": null,
"e": 3533,
"s": 3409,
"text": "Extendible − Apache Ivy can be extended easily. You can define your own repository, conflict resolvers and latest strategy."
},
{
"code": null,
"e": 3657,
"s": 3533,
"text": "Extendible − Apache Ivy can be extended easily. You can define your own repository, conflict resolvers and latest strategy."
},
{
"code": null,
"e": 3855,
"s": 3657,
"text": "Performance − Apache Ivy is built towards performance. It keeps a cache of library already downloaded. Looks into local repositories first to resolve dependencies than look into other repositories."
},
{
"code": null,
"e": 4053,
"s": 3855,
"text": "Performance − Apache Ivy is built towards performance. It keeps a cache of library already downloaded. Looks into local repositories first to resolve dependencies than look into other repositories."
},
{
"code": null,
"e": 4221,
"s": 4053,
"text": "Transitive Dependencies − Apache Ivy automatically manages transitive dependencies if one project or library depends upon other library which may need another library."
},
{
"code": null,
"e": 4389,
"s": 4221,
"text": "Transitive Dependencies − Apache Ivy automatically manages transitive dependencies if one project or library depends upon other library which may need another library."
},
{
"code": null,
"e": 4547,
"s": 4389,
"text": "Maven Repository − Apache Ivy follows conventions similar to Maven repository conventions. Apache Ivy can resolve dependencies using maven global repository."
},
{
"code": null,
"e": 4705,
"s": 4547,
"text": "Maven Repository − Apache Ivy follows conventions similar to Maven repository conventions. Apache Ivy can resolve dependencies using maven global repository."
},
{
"code": null,
"e": 4883,
"s": 4705,
"text": "Maven 2 POMs − Apache Ivy can read Maven 2 POMs as module descriptors, can set ivy as module descriptor. Thus it makes easy to migrate existing projects to IVY managed projects."
},
{
"code": null,
"e": 5061,
"s": 4883,
"text": "Maven 2 POMs − Apache Ivy can read Maven 2 POMs as module descriptors, can set ivy as module descriptor. Thus it makes easy to migrate existing projects to IVY managed projects."
},
{
"code": null,
"e": 5192,
"s": 5061,
"text": "Publishing − Apache Ivy provides supports to publish your project and simplifies the multi-project environment deployment process."
},
{
"code": null,
"e": 5323,
"s": 5192,
"text": "Publishing − Apache Ivy provides supports to publish your project and simplifies the multi-project environment deployment process."
},
{
"code": null,
"e": 5383,
"s": 5323,
"text": "Free to Use − Apache Ivy is open source and is free to use."
},
{
"code": null,
"e": 5443,
"s": 5383,
"text": "Free to Use − Apache Ivy is open source and is free to use."
},
{
"code": null,
"e": 5538,
"s": 5443,
"text": "Documentation − Apache Ivy has a very detailed documentation and tutorials available to learn."
},
{
"code": null,
"e": 5633,
"s": 5538,
"text": "Documentation − Apache Ivy has a very detailed documentation and tutorials available to learn."
},
{
"code": null,
"e": 5714,
"s": 5633,
"text": "Apache Ivy needs Java and ANT installed on your machine as the only requirement."
},
{
"code": null,
"e": 5852,
"s": 5714,
"text": "Apache Ant is distributed under the Apache Software License, a fully-fledged open source license certified by the open source initiative."
},
{
"code": null,
"e": 5985,
"s": 5852,
"text": "The latest Apache Ant version, including its full-source code, class files, and documentation can be found at http://ant.apache.org."
},
{
"code": null,
"e": 6136,
"s": 5985,
"text": "It is assumed that you have already downloaded and installed Java Development Kit (JDK) on your computer. If not, please follow the instructions here."
},
{
"code": null,
"e": 6233,
"s": 6136,
"text": "Ensure that the JAVA_HOME environment variable is set to the folder where your JDK is installed."
},
{
"code": null,
"e": 6330,
"s": 6233,
"text": "Ensure that the JAVA_HOME environment variable is set to the folder where your JDK is installed."
},
{
"code": null,
"e": 6380,
"s": 6330,
"text": "Download the binaries from https://ant.apache.org"
},
{
"code": null,
"e": 6430,
"s": 6380,
"text": "Download the binaries from https://ant.apache.org"
},
{
"code": null,
"e": 6531,
"s": 6430,
"text": "Unzip the zip file to a convenient location c:\\folder. using Winzip, winRAR, 7-zip or similar tools."
},
{
"code": null,
"e": 6632,
"s": 6531,
"text": "Unzip the zip file to a convenient location c:\\folder. using Winzip, winRAR, 7-zip or similar tools."
},
{
"code": null,
"e": 6773,
"s": 6632,
"text": "Create a new environment variable called ANT_HOME that points to the Ant installation folder, in this case c:\\apache-ant-1.10.12-bin folder."
},
{
"code": null,
"e": 6914,
"s": 6773,
"text": "Create a new environment variable called ANT_HOME that points to the Ant installation folder, in this case c:\\apache-ant-1.10.12-bin folder."
},
{
"code": null,
"e": 7061,
"s": 6914,
"text": "Append the path to the Apache Ant batch file to the PATH environment variable. In our case this would be the c:\\apache-ant-1.10.12-bin\\bin folder."
},
{
"code": null,
"e": 7208,
"s": 7061,
"text": "Append the path to the Apache Ant batch file to the PATH environment variable. In our case this would be the c:\\apache-ant-1.10.12-bin\\bin folder."
},
{
"code": null,
"e": 7311,
"s": 7208,
"text": "To verify the successful installation of Apache Ant on your computer, type ant on your command prompt."
},
{
"code": null,
"e": 7349,
"s": 7311,
"text": "You should see an output similar to −"
},
{
"code": null,
"e": 7426,
"s": 7349,
"text": "C:\\>ant -version\nApache Ant(TM) version 1.10.12 compiled on October 13 2021\n"
},
{
"code": null,
"e": 7537,
"s": 7426,
"text": "If you do not see the above output, then please verify that you have followed the installation steps properly."
},
{
"code": null,
"e": 7591,
"s": 7537,
"text": "Download the binaries from https://ant.apache.org/ivy"
},
{
"code": null,
"e": 7645,
"s": 7591,
"text": "Download the binaries from https://ant.apache.org/ivy"
},
{
"code": null,
"e": 7746,
"s": 7645,
"text": "Unzip the zip file to a convenient location c:\\folder. using Winzip, winRAR, 7-zip or similar tools."
},
{
"code": null,
"e": 7847,
"s": 7746,
"text": "Unzip the zip file to a convenient location c:\\folder. using Winzip, winRAR, 7-zip or similar tools."
},
{
"code": null,
"e": 7911,
"s": 7847,
"text": "Copy the ivy-2.5.0.jar to c:\\apache-ant-1.10.12-bin/lib folder."
},
{
"code": null,
"e": 7975,
"s": 7911,
"text": "Copy the ivy-2.5.0.jar to c:\\apache-ant-1.10.12-bin/lib folder."
},
{
"code": null,
"e": 8095,
"s": 7975,
"text": "To verify the successful installation of Apache Ivy on your computer, create following build file in a folder E: > ivy."
},
{
"code": null,
"e": 8298,
"s": 8095,
"text": "<project name=\"test ivy installation\" \n default=\"test\" xmlns:ivy=\"antlib:org.apache.ivy.ant\">\n <target name=\"test\" description=\"Test ivy installation\">\n <ivy:settings />\n </target>\n</project>"
},
{
"code": null,
"e": 8336,
"s": 8298,
"text": "You should see an output similar to −"
},
{
"code": null,
"e": 8420,
"s": 8336,
"text": "C:\\>ant\nBuildfile: E:\\ivy\\build.xml\n\ntest:\n\nBUILD SUCCESSFUL\nTotal time: 2 seconds\n"
},
{
"code": null,
"e": 8569,
"s": 8420,
"text": "This tutorial also covers integration of Ant with Eclipse IDE. Hence, if you have not installed Eclipse already, please download and install Eclipse"
},
{
"code": null,
"e": 8590,
"s": 8569,
"text": "To install Eclipse −"
},
{
"code": null,
"e": 8648,
"s": 8590,
"text": "Download the latest Eclipse binaries from www.eclipse.org"
},
{
"code": null,
"e": 8706,
"s": 8648,
"text": "Download the latest Eclipse binaries from www.eclipse.org"
},
{
"code": null,
"e": 8773,
"s": 8706,
"text": "Unzip the Eclipse binaries to a convenient location, say c:\\folder"
},
{
"code": null,
"e": 8840,
"s": 8773,
"text": "Unzip the Eclipse binaries to a convenient location, say c:\\folder"
},
{
"code": null,
"e": 8880,
"s": 8840,
"text": "Run Eclipse from c:\\eclipse\\eclipse.exe"
},
{
"code": null,
"e": 8920,
"s": 8880,
"text": "Run Eclipse from c:\\eclipse\\eclipse.exe"
},
{
"code": null,
"e": 8990,
"s": 8920,
"text": "Consider the following example ivy.xml to understand Ivy terminology."
},
{
"code": null,
"e": 9410,
"s": 8990,
"text": "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n<ivy-module version=\"2.0\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:noNamespaceSchemaLocation=\"http://ant.apache.org/ivy/schemas/ivy.xsd\">\n <info organisation=\"com.tutorialspoint\" module=\"ivy-test\" status=\"integration\">\n </info>\n <dependencies>\n <dependency org=\"commons-lang\" name=\"commons-lang\" rev=\"2.6\" />\n </dependencies>\n</ivy-module>"
},
{
"code": null,
"e": 9463,
"s": 9410,
"text": "Following are the important terms of Ivy Eco-System."
},
{
"code": null,
"e": 9637,
"s": 9463,
"text": "Organisation − As name suggests, it refers to the name of the company, individual developer or team name who creates the project or library. For example, com.tutorialspoint."
},
{
"code": null,
"e": 9811,
"s": 9637,
"text": "Organisation − As name suggests, it refers to the name of the company, individual developer or team name who creates the project or library. For example, com.tutorialspoint."
},
{
"code": null,
"e": 9973,
"s": 9811,
"text": "Module − As name suggests, it refers to the reusable unit or module. A module generally have a version attached to it. For example commons-lang, or ivy-test etc."
},
{
"code": null,
"e": 10135,
"s": 9973,
"text": "Module − As name suggests, it refers to the reusable unit or module. A module generally have a version attached to it. For example commons-lang, or ivy-test etc."
},
{
"code": null,
"e": 10353,
"s": 10135,
"text": "Module Descriptor − Module descriptor refers to ivy.xml file which describes a module. A module descriptor contains the identifier (org, name, branch and version), artifacts published, configurations and dependencies."
},
{
"code": null,
"e": 10571,
"s": 10353,
"text": "Module Descriptor − Module descriptor refers to ivy.xml file which describes a module. A module descriptor contains the identifier (org, name, branch and version), artifacts published, configurations and dependencies."
},
{
"code": null,
"e": 10758,
"s": 10571,
"text": "Artifact − Artifact refers to a single file as deliverable. For example, a jar file. Artifact can be of type: zip, gz etc. Jar, Source Jar, Javadoc Jar are various artifacts of a module."
},
{
"code": null,
"e": 10945,
"s": 10758,
"text": "Artifact − Artifact refers to a single file as deliverable. For example, a jar file. Artifact can be of type: zip, gz etc. Jar, Source Jar, Javadoc Jar are various artifacts of a module."
},
{
"code": null,
"e": 11020,
"s": 10945,
"text": "Type − Type identifies the artifact category like jar, war , src, doc etc."
},
{
"code": null,
"e": 11095,
"s": 11020,
"text": "Type − Type identifies the artifact category like jar, war , src, doc etc."
},
{
"code": null,
"e": 11171,
"s": 11095,
"text": "Artifact file name extension − Artifact extension like .jar, ,zip, .gz etc."
},
{
"code": null,
"e": 11247,
"s": 11171,
"text": "Artifact file name extension − Artifact extension like .jar, ,zip, .gz etc."
},
{
"code": null,
"e": 11327,
"s": 11247,
"text": "Module Revision − A unique revision number of the module or its version number."
},
{
"code": null,
"e": 11407,
"s": 11327,
"text": "Module Revision − A unique revision number of the module or its version number."
},
{
"code": null,
"e": 11721,
"s": 11407,
"text": "Status of Revision − Status of revision indicates the stability of the revision. Following are the important value of status −\n\nintegration − Represents continous development, nightly build etc.\nmilestone − Represents a distribution but not finalized.\nrelease − Represents tested and completed, a major version.\n\n"
},
{
"code": null,
"e": 11848,
"s": 11721,
"text": "Status of Revision − Status of revision indicates the stability of the revision. Following are the important value of status −"
},
{
"code": null,
"e": 11915,
"s": 11848,
"text": "integration − Represents continous development, nightly build etc."
},
{
"code": null,
"e": 11982,
"s": 11915,
"text": "integration − Represents continous development, nightly build etc."
},
{
"code": null,
"e": 12039,
"s": 11982,
"text": "milestone − Represents a distribution but not finalized."
},
{
"code": null,
"e": 12096,
"s": 12039,
"text": "milestone − Represents a distribution but not finalized."
},
{
"code": null,
"e": 12156,
"s": 12096,
"text": "release − Represents tested and completed, a major version."
},
{
"code": null,
"e": 12216,
"s": 12156,
"text": "release − Represents tested and completed, a major version."
},
{
"code": null,
"e": 12405,
"s": 12216,
"text": "Repository − Similar to Maven repositories, repository represents a distribution site where ivy can search a library, artifacts, modules etc. A repository can be public, private or shared."
},
{
"code": null,
"e": 12594,
"s": 12405,
"text": "Repository − Similar to Maven repositories, repository represents a distribution site where ivy can search a library, artifacts, modules etc. A repository can be public, private or shared."
},
{
"code": null,
"e": 12762,
"s": 12594,
"text": "Ivy Settings − Apache Ivy follows Maven principles and comes with lot of default configurations. Default settings can be overridden by defining a ivysettings.xml file."
},
{
"code": null,
"e": 12930,
"s": 12762,
"text": "Ivy Settings − Apache Ivy follows Maven principles and comes with lot of default configurations. Default settings can be overridden by defining a ivysettings.xml file."
},
{
"code": null,
"e": 13083,
"s": 12930,
"text": "Apache Ivy follows Maven principles and comes with lot of default configurations. Default settings can be overridden by defining a ivysettings.xml file."
},
{
"code": null,
"e": 13660,
"s": 13083,
"text": "<ivysettings>\n <properties file=\"${ivy.settings.dir}/ivysettings-file.properties\" />\n <settings defaultCache=\"${cache.dir}\" defaultResolver=\"ibiblio\" checkUpToDate=\"false\" />\n <resolvers>\n <ibiblio name=\"ibiblio\" />\n <filesystem name=\"internal\">\n <ivy pattern=\"${repository.dir}/[module]/ivy-[revision].xml\" />\n <artifact pattern=\"${repository.dir}/[module]/[artifact]-[revision].[ext]\" />\n </filesystem>\n </resolvers>\n <modules>\n <module organisation=\"tutorialspoint\" name=\".*\" resolver=\"internal\" />\n </modules>\n</ivysettings>"
},
{
"code": null,
"e": 13714,
"s": 13660,
"text": "Following are the important tags of Ivy Setting file."
},
{
"code": null,
"e": 13767,
"s": 13714,
"text": "property − To set an ivy variable. Cardinality: 0..n"
},
{
"code": null,
"e": 13820,
"s": 13767,
"text": "property − To set an ivy variable. Cardinality: 0..n"
},
{
"code": null,
"e": 13898,
"s": 13820,
"text": "properties − To set an ivy variables using properties file. Cardinality: 0..n"
},
{
"code": null,
"e": 13976,
"s": 13898,
"text": "properties − To set an ivy variables using properties file. Cardinality: 0..n"
},
{
"code": null,
"e": 14043,
"s": 13976,
"text": "settings − To configure ivy with default values. Cardinality: 0..1"
},
{
"code": null,
"e": 14110,
"s": 14043,
"text": "settings − To configure ivy with default values. Cardinality: 0..1"
},
{
"code": null,
"e": 14172,
"s": 14110,
"text": "include − To include another settings file. Cardinality: 0..n"
},
{
"code": null,
"e": 14234,
"s": 14172,
"text": "include − To include another settings file. Cardinality: 0..n"
},
{
"code": null,
"e": 14321,
"s": 14234,
"text": "classpath − To add a location in the classpath used to load plugins. Cardinality: 0..n"
},
{
"code": null,
"e": 14408,
"s": 14321,
"text": "classpath − To add a location in the classpath used to load plugins. Cardinality: 0..n"
},
{
"code": null,
"e": 14464,
"s": 14408,
"text": "typedef − To define new types in ivy. Cardinality: 0..n"
},
{
"code": null,
"e": 14520,
"s": 14464,
"text": "typedef − To define new types in ivy. Cardinality: 0..n"
},
{
"code": null,
"e": 14583,
"s": 14520,
"text": "lock-strategies − To define lock strategies. Cardinality: 0..1"
},
{
"code": null,
"e": 14646,
"s": 14583,
"text": "lock-strategies − To define lock strategies. Cardinality: 0..1"
},
{
"code": null,
"e": 14710,
"s": 14646,
"text": "caches − To define repository cache managers. Cardinality: 0..1"
},
{
"code": null,
"e": 14774,
"s": 14710,
"text": "caches − To define repository cache managers. Cardinality: 0..1"
},
{
"code": null,
"e": 14841,
"s": 14774,
"text": "latest-strategies − To define latest strategies. Cardinality: 0..1"
},
{
"code": null,
"e": 14908,
"s": 14841,
"text": "latest-strategies − To define latest strategies. Cardinality: 0..1"
},
{
"code": null,
"e": 14973,
"s": 14908,
"text": "parsers − To define module descriptor parsers. Cardinality: 0..1"
},
{
"code": null,
"e": 15038,
"s": 14973,
"text": "parsers − To define module descriptor parsers. Cardinality: 0..1"
},
{
"code": null,
"e": 15107,
"s": 15038,
"text": "version-matchers − To define new version matchers. Cardinality: 0..1"
},
{
"code": null,
"e": 15176,
"s": 15107,
"text": "version-matchers − To define new version matchers. Cardinality: 0..1"
},
{
"code": null,
"e": 15241,
"s": 15176,
"text": "triggers − To\tregister triggers on ivy events. Cardinality: 0..1"
},
{
"code": null,
"e": 15306,
"s": 15241,
"text": "triggers − To\tregister triggers on ivy events. Cardinality: 0..1"
},
{
"code": null,
"e": 15363,
"s": 15306,
"text": "namespaces − To define new namespaces. Cardinality: 0..1"
},
{
"code": null,
"e": 15420,
"s": 15363,
"text": "namespaces − To define new namespaces. Cardinality: 0..1"
},
{
"code": null,
"e": 15481,
"s": 15420,
"text": "macrodef − To define a new macro resolver. Cardinality: 0..n"
},
{
"code": null,
"e": 15542,
"s": 15481,
"text": "macrodef − To define a new macro resolver. Cardinality: 0..n"
},
{
"code": null,
"e": 15604,
"s": 15542,
"text": "resolvers − To define dependency resolvers. Cardinality: 0..1"
},
{
"code": null,
"e": 15666,
"s": 15604,
"text": "resolvers − To define dependency resolvers. Cardinality: 0..1"
},
{
"code": null,
"e": 15734,
"s": 15666,
"text": "conflict-managers − To define conflicts managers. Cardinality: 0..1"
},
{
"code": null,
"e": 15802,
"s": 15734,
"text": "conflict-managers − To define conflicts managers. Cardinality: 0..1"
},
{
"code": null,
"e": 15888,
"s": 15802,
"text": "modules − To define rules between modules and dependency resolvers. Cardinality: 0..1"
},
{
"code": null,
"e": 15974,
"s": 15888,
"text": "modules − To define rules between modules and dependency resolvers. Cardinality: 0..1"
},
{
"code": null,
"e": 16056,
"s": 15974,
"text": "outputters − To define the list of available report outputters. Cardinality: 0..1"
},
{
"code": null,
"e": 16138,
"s": 16056,
"text": "outputters − To define the list of available report outputters. Cardinality: 0..1"
},
{
"code": null,
"e": 16209,
"s": 16138,
"text": "statuses − To define the list of available statuses. Cardinality: 0..1"
},
{
"code": null,
"e": 16280,
"s": 16209,
"text": "statuses − To define the list of available statuses. Cardinality: 0..1"
},
{
"code": null,
"e": 16578,
"s": 16280,
"text": "IvyDE is an Eclipse plugin provided by Apache. To install IvyDE, start Eclipse and navigate to Help > Install New Software. It displays the Available Softwares window. Enter IvyDE update site http://www.apache.org/dist/ant/ivyde/updatesite/ and press enter key. It displays the following plugins."
},
{
"code": null,
"e": 16628,
"s": 16578,
"text": "Click Next and you will see the following screen."
},
{
"code": null,
"e": 16781,
"s": 16628,
"text": "If you are facing any error while installing the plugin then just restart the process. After successful installation, you will see the plugin in eclipe."
},
{
"code": null,
"e": 16845,
"s": 16781,
"text": "Now you can do the dependency management using Eclipse and Ivy."
},
{
"code": null,
"e": 16948,
"s": 16845,
"text": "Resolve task is used to resolve dependencies described in ivy.xml, download and put them in ivy cache."
},
{
"code": null,
"e": 17089,
"s": 16948,
"text": "Let's first create a java file Tester.java in E: > ivy > src > com > tutorialspoint folder which will act as source folder for ant project."
},
{
"code": null,
"e": 17106,
"s": 17089,
"text": "Application.java"
},
{
"code": null,
"e": 17357,
"s": 17106,
"text": "package com.tutorialspoint;\nimport org.apache.commons.lang.StringUtils;\npublic class Application {\n public static void main(String[] args) {\n String string = StringUtils.upperCase(\"Ivy Beginner Guide\");\n System.out.println(string);\n }\n}"
},
{
"code": null,
"e": 17593,
"s": 17357,
"text": "Above class is using apache commons lang library to use its class StringUtils. Ivy should download this library and thus it should be defined under dependencies section in ivy.xml. Following is the ivy.xml created in E: > ivy folder."
},
{
"code": null,
"e": 17601,
"s": 17593,
"text": "ivy.xml"
},
{
"code": null,
"e": 18038,
"s": 17601,
"text": "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n<ivy-module version=\"2.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:noNamespaceSchemaLocation=\"http://ant.apache.org/ivy/schemas/ivy.xsd\">\n <info\n organisation=\"com.tutorialspoint\"\n module=\"test\"\n status=\"integration\">\n </info>\n <dependencies>\n <dependency org=\"org.apache.commons\" name=\"commons-lang3\" rev=\"3.9\"/>\n </dependencies>\n</ivy-module>"
},
{
"code": null,
"e": 18073,
"s": 18038,
"text": "Following are the important terms."
},
{
"code": null,
"e": 18139,
"s": 18073,
"text": "ivy-module − Root element to identify ivy version, namespace etc."
},
{
"code": null,
"e": 18205,
"s": 18139,
"text": "ivy-module − Root element to identify ivy version, namespace etc."
},
{
"code": null,
"e": 18391,
"s": 18205,
"text": "info − element to identify the project as a unique entity.\n\norganisation − name of the organization\nmodule − name of the module\nstatus − status like release, integration or milestone.\n\n"
},
{
"code": null,
"e": 18450,
"s": 18391,
"text": "info − element to identify the project as a unique entity."
},
{
"code": null,
"e": 18490,
"s": 18450,
"text": "organisation − name of the organization"
},
{
"code": null,
"e": 18530,
"s": 18490,
"text": "organisation − name of the organization"
},
{
"code": null,
"e": 18558,
"s": 18530,
"text": "module − name of the module"
},
{
"code": null,
"e": 18586,
"s": 18558,
"text": "module − name of the module"
},
{
"code": null,
"e": 18642,
"s": 18586,
"text": "status − status like release, integration or milestone."
},
{
"code": null,
"e": 18698,
"s": 18642,
"text": "status − status like release, integration or milestone."
},
{
"code": null,
"e": 18915,
"s": 18698,
"text": "dependencies − element to contain project dependencies as dependency tags which has following attributes.\n\norg − name of the dependency's organization\nname − name of the dependency.\nrev − version of the dependency.\n\n"
},
{
"code": null,
"e": 19021,
"s": 18915,
"text": "dependencies − element to contain project dependencies as dependency tags which has following attributes."
},
{
"code": null,
"e": 19065,
"s": 19021,
"text": "org − name of the dependency's organization"
},
{
"code": null,
"e": 19109,
"s": 19065,
"text": "org − name of the dependency's organization"
},
{
"code": null,
"e": 19140,
"s": 19109,
"text": "name − name of the dependency."
},
{
"code": null,
"e": 19171,
"s": 19140,
"text": "name − name of the dependency."
},
{
"code": null,
"e": 19204,
"s": 19171,
"text": "rev − version of the dependency."
},
{
"code": null,
"e": 19237,
"s": 19204,
"text": "rev − version of the dependency."
},
{
"code": null,
"e": 19247,
"s": 19237,
"text": "build.xml"
},
{
"code": null,
"e": 19433,
"s": 19247,
"text": "<project name=\"test\" default=\"resolve\" xmlns:ivy=\"antlib:org.apache.ivy.ant\">\n <target name=\"resolve\" description=\"resolve dependencies\">\n <ivy:resolve />\n </target>\n</project<"
},
{
"code": null,
"e": 19468,
"s": 19433,
"text": "Following are the important terms."
},
{
"code": null,
"e": 19553,
"s": 19468,
"text": "project − Root element to identify project name, default task namespace for ivy etc."
},
{
"code": null,
"e": 19638,
"s": 19553,
"text": "project − Root element to identify project name, default task namespace for ivy etc."
},
{
"code": null,
"e": 19845,
"s": 19638,
"text": "target − target element to create a new task and its description. This contains an ivy resolve task. When ant builds the project, it runs the ivy resolve task which then resolves the dependencies using ivy."
},
{
"code": null,
"e": 20052,
"s": 19845,
"text": "target − target element to create a new task and its description. This contains an ivy resolve task. When ant builds the project, it runs the ivy resolve task which then resolves the dependencies using ivy."
},
{
"code": null,
"e": 20157,
"s": 20052,
"text": "As we've all the files ready. Just go the console. Navigate to E: > ivy folder and run the ant command."
},
{
"code": null,
"e": 20171,
"s": 20157,
"text": "E:\\ivy > ant\n"
},
{
"code": null,
"e": 20261,
"s": 20171,
"text": "Ivy will come into action, resolving the dependencies, you will see the following result."
},
{
"code": null,
"e": 21499,
"s": 20261,
"text": "Buildfile: E:\\ivy\\build.xml\nresolve:\n[ivy:resolve] :: Apache Ivy 2.5.0 - 20191020104435 :: https://ant.apache.org/ivy\n/ ::\n[ivy:resolve] :: loading settings :: url = jar:file:/E:/Apache/apache-ant-1.9.14\n/lib/ivy-2.5.0.jar!/org/apache/ivy/core/settings/ivysettings.xml\n[ivy:resolve] :: resolving dependencies :: com.tutorialspoint#test;working@Acer-\nPC\n[ivy:resolve] confs: [default]\n[ivy:resolve] found commons-lang#commons-lang;2.6 in public\n[ivy:resolve] found junit#junit;3.8.1 in public\n[ivy:resolve] :: resolution report :: resolve 375ms :: artifacts dl 79ms\n ---------------------------------------------------------------------\n | | modules || artifacts |\n | conf | number| search|dwnlded|evicted|| number|dwnlded|\n ---------------------------------------------------------------------\n | default | 2 | 2 | 0 | 0 || 4 | 0 |\n ---------------------------------------------------------------------\n[ivy:retrieve] :: retrieving :: com.tutorialspoint#test [sync]\n[ivy:retrieve] confs: [default]\n[ivy:retrieve] 0 artifacts copied, 2 already retrieved (0kB/101ms)\nBUILD SUCCESSFUL\nTotal time: 1 second\nE:\\ivy>\n"
},
{
"code": null,
"e": 21534,
"s": 21499,
"text": "Following are the important terms."
},
{
"code": null,
"e": 21604,
"s": 21534,
"text": "conf − configuration, in our case we are using default configuration."
},
{
"code": null,
"e": 21674,
"s": 21604,
"text": "conf − configuration, in our case we are using default configuration."
},
{
"code": null,
"e": 21748,
"s": 21674,
"text": "modules − indicates the total number of modules, downloaded modules etc. "
},
{
"code": null,
"e": 21822,
"s": 21748,
"text": "modules − indicates the total number of modules, downloaded modules etc. "
},
{
"code": null,
"e": 21902,
"s": 21822,
"text": "artifacts − indicates the total number of artifacts, downloaded artifacts etc. "
},
{
"code": null,
"e": 21982,
"s": 21902,
"text": "artifacts − indicates the total number of artifacts, downloaded artifacts etc. "
},
{
"code": null,
"e": 22170,
"s": 21982,
"text": "You can verify the downloaded files in ivy cache's default location in ${ivy.default.ivy.user.dir} > .ivy2 > cache folder. And ${ivy.default.ivy.user.dir} is by default user home: $HOME."
},
{
"code": null,
"e": 22453,
"s": 22170,
"text": "Install task is used to install a module and its dependencies in a resolver. It is used when a public artifact is to be downloaded and used in private repository. By default, a user local repository is his/her private repository and is present in ${ivy.default.ivy.user.dir}/local."
},
{
"code": null,
"e": 22545,
"s": 22453,
"text": "Let's create Tester.java, build.xml and ivy.xml as described in IVY - Resolve Task chapter."
},
{
"code": null,
"e": 22595,
"s": 22545,
"text": "Update the build.xml to use the ivy install task."
},
{
"code": null,
"e": 22605,
"s": 22595,
"text": "build.xml"
},
{
"code": null,
"e": 23034,
"s": 22605,
"text": "<project name=\"test\" default=\"resolve\" xmlns:ivy=\"antlib:org.apache.ivy.ant\">\n <target name=\"resolve\" description=\"resolve dependencies\">\n <ivy:resolve />\n </target>\n <target name=\"install\" description=\"install dependencies\">\n <ivy:install organisation=\"commons-lang\" module=\"commons-lang\" \n revision=\"2.6\" transitive=\"true\" overwrite=\"false\" \n from=\"public\" to=\"local\" />\n </target>\n</project>"
},
{
"code": null,
"e": 23069,
"s": 23034,
"text": "Following are the important terms."
},
{
"code": null,
"e": 23110,
"s": 23069,
"text": "organisation − name of the organization."
},
{
"code": null,
"e": 23151,
"s": 23110,
"text": "organisation − name of the organization."
},
{
"code": null,
"e": 23188,
"s": 23151,
"text": "module − module name of the project."
},
{
"code": null,
"e": 23225,
"s": 23188,
"text": "module − module name of the project."
},
{
"code": null,
"e": 23260,
"s": 23225,
"text": "revision − version of the project."
},
{
"code": null,
"e": 23295,
"s": 23260,
"text": "revision − version of the project."
},
{
"code": null,
"e": 23324,
"s": 23295,
"text": "from − from repository type."
},
{
"code": null,
"e": 23353,
"s": 23324,
"text": "from − from repository type."
},
{
"code": null,
"e": 23378,
"s": 23353,
"text": "to − to repository type."
},
{
"code": null,
"e": 23403,
"s": 23378,
"text": "to − to repository type."
},
{
"code": null,
"e": 23508,
"s": 23403,
"text": "As we've all the files ready. Just go the console. Navigate to E: > ivy folder and run the ant command."
},
{
"code": null,
"e": 23530,
"s": 23508,
"text": "E:\\ivy > ant install\n"
},
{
"code": null,
"e": 23620,
"s": 23530,
"text": "Ivy will come into action, resolving the dependencies, you will see the following result."
},
{
"code": null,
"e": 25869,
"s": 23620,
"text": "E:\\ivy > ant install\nBuildfile: E:\\ivy\\build.xml\ninstall:\n[ivy:install] :: Apache Ivy 2.5.0 - 20191020104435 :: https://ant.apache.org/ivy\n/ ::\n[ivy:install] :: loading settings :: url = jar:file:/E:/Apache/apache-ant-1.9.14\n/lib/ivy-2.5.0.jar!/org/apache/ivy/core/settings/ivysettings.xml\n[ivy:install] :: installing commons-lang#commons-lang;2.6 ::\n[ivy:install] :: resolving dependencies ::\n[ivy:install] found commons-lang#commons-lang;2.6 in public\n[ivy:install] found junit#junit;3.8.1 in public\n[ivy:install] :: downloading artifacts to cache ::\n[ivy:install] :: installing in local ::\n[ivy:install] published commons-lang to C:\\Users\\Acer\\.ivy2\\local\\commons-lang\n\\commons-lang\\2.6.part\\sources\\commons-lang.jar\n[ivy:install] published commons-lang to C:\\Users\\Acer\\.ivy2\\local\\commons-lang\n\\commons-lang\\2.6.part\\jars\\commons-lang.jar\n[ivy:install] published commons-lang to C:\\Users\\Acer\\.ivy2\\local\\commons-lang\n\\commons-lang\\2.6.part\\javadocs\\commons-lang.jar\n[ivy:install] published ivy to C:\\Users\\Acer\\.ivy2\\local\\commons-lang\\commons-\nlang\\2.6.part\\ivys\\ivy.xml\n[ivy:install] publish committed: moved C:\\Users\\Acer\\.ivy2\\local\\commons-lang\\\ncommons-lang\\2.6.part\n[ivy:install] to C:\\Users\\Acer\\.ivy2\\local\\commons-lang\\commons-lang\\2\n.6\n[ivy:install] published junit to C:\\Users\\Acer\\.ivy2\\local\\junit\\junit\\3.8.1.p\nart\\jars\\junit.jar\n[ivy:install] published ivy to C:\\Users\\Acer\\.ivy2\\local\\junit\\junit\\3.8.1.par\nt\\ivys\\ivy.xml\n[ivy:install] publish committed: moved C:\\Users\\Acer\\.ivy2\\local\\junit\\junit\\3\n.8.1.part\n[ivy:install] to C:\\Users\\Acer\\.ivy2\\local\\junit\\junit\\3.8.1\n[ivy:install] :: install resolution report ::\n[ivy:install] :: resolution report :: resolve 0ms :: artifacts dl 21ms\n ---------------------------------------------------------------------\n | | modules || artifacts |\n | conf | number| search|dwnlded|evicted|| number|dwnlded|\n ---------------------------------------------------------------------\n | default | 2 | 0 | 0 | 0 || 4 | 0 |\n ---------------------------------------------------------------------\nBUILD SUCCESSFUL\nTotal time: 43 seconds\n"
},
{
"code": null,
"e": 26010,
"s": 25869,
"text": "You can verify the downloaded files in ivy cache's default local repository location ${ivy.default.ivy.user.dir} > .ivy2 > local directory."
},
{
"code": null,
"e": 26102,
"s": 26010,
"text": "retrieve task is used to resolve dependencies to a specified location in project workspace."
},
{
"code": null,
"e": 26194,
"s": 26102,
"text": "Let's create Tester.java, build.xml and ivy.xml as described in IVY - Resolve Task chapter."
},
{
"code": null,
"e": 26245,
"s": 26194,
"text": "Update the build.xml to use the ivy retrieve task."
},
{
"code": null,
"e": 26255,
"s": 26245,
"text": "build.xml"
},
{
"code": null,
"e": 26487,
"s": 26255,
"text": "<project name=\"test\" default=\"resolve\" xmlns:ivy=\"antlib:org.apache.ivy.ant\">\n <target name=\"resolve\" description=\"resolve dependencies\">\n <ivy:resolve />\n <ivy:retrieve sync=\"true\" type=\"jar\" />\n </target>\n</project>"
},
{
"code": null,
"e": 26522,
"s": 26487,
"text": "Following are the important terms."
},
{
"code": null,
"e": 26612,
"s": 26522,
"text": "sync − sync true ensure that lib directory is up-to-date and any extra file gets deleted."
},
{
"code": null,
"e": 26702,
"s": 26612,
"text": "sync − sync true ensure that lib directory is up-to-date and any extra file gets deleted."
},
{
"code": null,
"e": 26890,
"s": 26702,
"text": "type − type directs ivy to copy only specified type of artifacts like jar. Source jar, javadoc jar will be ignored. type for source jar is src or source and doc or bundle for javadoc jar."
},
{
"code": null,
"e": 27078,
"s": 26890,
"text": "type − type directs ivy to copy only specified type of artifacts like jar. Source jar, javadoc jar will be ignored. type for source jar is src or source and doc or bundle for javadoc jar."
},
{
"code": null,
"e": 27217,
"s": 27078,
"text": "retrieve tasks copies the resolved dependencies in the lib directory of the project by default and can be changed using pattern attribute."
},
{
"code": null,
"e": 27322,
"s": 27217,
"text": "As we've all the files ready. Just go the console. Navigate to E: > ivy folder and run the ant command."
},
{
"code": null,
"e": 27336,
"s": 27322,
"text": "E:\\ivy > ant\n"
},
{
"code": null,
"e": 27426,
"s": 27336,
"text": "Ivy will come into action, resolving the dependencies, you will see the following result."
},
{
"code": null,
"e": 28659,
"s": 27426,
"text": "Buildfile: E:\\ivy\\build.xml\nresolve:\n[ivy:resolve] :: Apache Ivy 2.5.0 - 20191020104435 :: https://ant.apache.org/ivy\n/ ::\n[ivy:resolve] :: loading settings :: url = jar:file:/E:/Apache/apache-ant-1.9.14\n/lib/ivy-2.5.0.jar!/org/apache/ivy/core/settings/ivysettings.xml\n[ivy:resolve] :: resolving dependencies :: com.tutorialspoint#test;working@Acer-\nPC\n[ivy:resolve] confs: [default]\n[ivy:resolve] found commons-lang#commons-lang;2.6 in public\n[ivy:resolve] found junit#junit;3.8.1 in public\n[ivy:resolve] :: resolution report :: resolve 316ms :: artifacts dl 18ms\n ---------------------------------------------------------------------\n | | modules || artifacts |\n | conf | number| search|dwnlded|evicted|| number|dwnlded|\n ---------------------------------------------------------------------\n | default | 2 | 2 | 0 | 0 || 4 | 0 |\n ---------------------------------------------------------------------\n[ivy:retrieve] :: retrieving :: com.tutorialspoint#test [sync]\n[ivy:retrieve] confs: [default]\n[ivy:retrieve] 0 artifacts copied, 2 already retrieved (0kB/2756ms)\nBUILD SUCCESSFUL\nTotal time: 31 seconds\n"
},
{
"code": null,
"e": 28721,
"s": 28659,
"text": "You can verify the downloaded files in project lib directory."
},
{
"code": null,
"e": 28910,
"s": 28721,
"text": "cachepath task is used to create an ANT classpath with resolved artifacts present in the cache. As ANT needs jars to be classpath to compile java files, Ivy cachepath builds the classpath."
},
{
"code": null,
"e": 29002,
"s": 28910,
"text": "Let's create Tester.java, build.xml and ivy.xml as described in IVY - Resolve Task chapter."
},
{
"code": null,
"e": 29053,
"s": 29002,
"text": "Update the build.xml to use the ivy retrieve task."
},
{
"code": null,
"e": 29063,
"s": 29053,
"text": "build.xml"
},
{
"code": null,
"e": 29523,
"s": 29063,
"text": "<project name=\"test\" default=\"resolve\" xmlns:ivy=\"antlib:org.apache.ivy.ant\">\n <target name=\"resolve\" description=\"resolve dependencies\">\n <ivy:resolve />\n <ivy:cachepath pathid=\"new.classpath\" />\n </target>\n <target name=\"compile\" depends=\"resolve\" description=\"Compile\">\n <mkdir dir=\"build/classes\" />\n <javac srcdir=\"src\" destdir=\"build/classes\">\n <classpath refid=\"new.classpath\" />\n </javac>\n </target>\n</project>"
},
{
"code": null,
"e": 29558,
"s": 29523,
"text": "Following are the important terms."
},
{
"code": null,
"e": 29618,
"s": 29558,
"text": "pathid − id of the classpath where cached jars are present."
},
{
"code": null,
"e": 29678,
"s": 29618,
"text": "pathid − id of the classpath where cached jars are present."
},
{
"code": null,
"e": 29817,
"s": 29678,
"text": "retrieve tasks copies the resolved dependencies in the lib directory of the project by default and can be changed using pattern attribute."
},
{
"code": null,
"e": 29922,
"s": 29817,
"text": "As we've all the files ready. Just go the console. Navigate to E: > ivy folder and run the ant command."
},
{
"code": null,
"e": 29944,
"s": 29922,
"text": "E:\\ivy > ant compile\n"
},
{
"code": null,
"e": 30034,
"s": 29944,
"text": "Ivy will come into action, resolving the dependencies, you will see the following result."
},
{
"code": null,
"e": 31319,
"s": 30034,
"text": "Buildfile: E:\\ivy\\build.xml\nresolve:\n[ivy:resolve] :: Apache Ivy 2.5.0 - 20191020104435 :: https://ant.apache.org/ivy\n/ ::\n[ivy:resolve] :: loading settings :: url = jar:file:/E:/Apache/apache-ant-1.9.14\n/lib/ivy-2.5.0.jar!/org/apache/ivy/core/settings/ivysettings.xml\n[ivy:resolve] :: resolving dependencies :: com.tutorialspoint#test;working@Acer-\nPC\n[ivy:resolve] confs: [default]\n[ivy:resolve] found commons-lang#commons-lang;2.6 in public\n[ivy:resolve] found junit#junit;3.8.1 in public\n[ivy:resolve] :: resolution report :: resolve 2314ms :: artifacts dl 15ms\n ---------------------------------------------------------------------\n | | modules || artifacts |\n | conf | number| search|dwnlded|evicted|| number|dwnlded|\n ---------------------------------------------------------------------\n | default | 2 | 2 | 0 | 0 || 4 | 0 |\n ---------------------------------------------------------------------\ncompile:\n [javac] E:\\ivy\\build.xml:13: warning: 'includeantruntime' was not set, defau\nlting to build.sysclasspath=last; set to false for repeatable builds\n [javac] Compiling 1 source file to E:\\ivy\\build\\classes\nBUILD SUCCESSFUL\nTotal time: 3 seconds\n"
},
{
"code": null,
"e": 31386,
"s": 31319,
"text": "You can verify the compiled class file in project build directory."
},
{
"code": null,
"e": 31495,
"s": 31386,
"text": "publish task is used to publish current artifacts and its resolved descriptor files to mentioned repository."
},
{
"code": null,
"e": 31587,
"s": 31495,
"text": "Let's create Tester.java, build.xml and ivy.xml as described in IVY - Resolve Task chapter."
},
{
"code": null,
"e": 31688,
"s": 31587,
"text": "Update the build.xml to use the ivy publish task. First we'll create a jar file and then publish it."
},
{
"code": null,
"e": 31698,
"s": 31688,
"text": "build.xml"
},
{
"code": null,
"e": 32457,
"s": 31698,
"text": "<project name=\"test\" default=\"resolve\" xmlns:ivy=\"antlib:org.apache.ivy.ant\">\n <property name = \"build.dir\" value = \"build\"/>\n <target name=\"resolve\" description=\"resolve dependencies\">\n <ivy:resolve />\n </target>\n <target name = \"jar\">\n <jar destfile = \"${build.dir}/lib/application.jar\"\n basedir = \"${build.dir}/classes\"> \n <manifest>\n <attribute name = \"Main-Class\" value = \"com.tutorialspoint.Application\"/>\n </manifest>\n </jar>\n </target>\n <target name=\"publish\" depends=\"jar\">\n <ivy:resolve />\n <ivy:publish resolver=\"local\" pubrevision=\"1.0\" overwrite=\"true\">\n <artifacts pattern=\"${build.dir}/lib/[artifact].[ext]\" />\n </ivy:publish> \n </target>\n</project>"
},
{
"code": null,
"e": 32492,
"s": 32457,
"text": "Following are the important terms."
},
{
"code": null,
"e": 32540,
"s": 32492,
"text": "resolver − resolver to be used for publication."
},
{
"code": null,
"e": 32588,
"s": 32540,
"text": "resolver − resolver to be used for publication."
},
{
"code": null,
"e": 32630,
"s": 32588,
"text": "pattern − pattern to locate the artifact."
},
{
"code": null,
"e": 32672,
"s": 32630,
"text": "pattern − pattern to locate the artifact."
},
{
"code": null,
"e": 32813,
"s": 32672,
"text": "Here publish task first build the jar, then resolve the dependencies, set the information and then publish the artifact to local repository."
},
{
"code": null,
"e": 32918,
"s": 32813,
"text": "As we've all the files ready. Just go the console. Navigate to E: > ivy folder and run the ant command."
},
{
"code": null,
"e": 32940,
"s": 32918,
"text": "E:\\ivy > ant publish\n"
},
{
"code": null,
"e": 33030,
"s": 32940,
"text": "Ivy will come into action, resolving the dependencies, you will see the following result."
},
{
"code": null,
"e": 34384,
"s": 33030,
"text": "E:\\ivy > ant publish\nBuildfile: E:\\ivy\\build.xml\njar:\npublish:\n[ivy:resolve] :: Apache Ivy 2.5.0 - 20191020104435 :: https://ant.apache.org/ivy\n/ ::\n[ivy:resolve] :: loading settings :: url = jar:file:/E:/Apache/apache-ant-1.9.14\n/lib/ivy-2.5.0.jar!/org/apache/ivy/core/settings/ivysettings.xml\n[ivy:resolve] :: resolving dependencies :: com.tutorialspoint#test;1.0.0\n[ivy:resolve] confs: [default]\n[ivy:resolve] found commons-lang#commons-lang;2.6 in public\n[ivy:resolve] found junit#junit;3.8.1 in public\n[ivy:resolve] :: resolution report :: resolve 121ms :: artifacts dl 15ms\n ---------------------------------------------------------------------\n | | modules || artifacts |\n | conf | number| search|dwnlded|evicted|| number|dwnlded|\n ---------------------------------------------------------------------\n | default | 2 | 2 | 0 | 0 || 4 | 0 |\n ---------------------------------------------------------------------\n[ivy:publish] :: publishing :: com.tutorialspoint#test\n[ivy:publish] published application to C:\\Users\\Acer\\.ivy2\\local\\com.tutorials\npoint\\test\\1.0\\jars\\application.jar\n[ivy:publish] published ivy to C:\\Users\\Acer\\.ivy2\\local\\com.tutorialspoint\\te\nst\\1.0\\ivys\\ivy.xml\nBUILD SUCCESSFUL\nTotal time: 1 second\n"
},
{
"code": null,
"e": 34446,
"s": 34384,
"text": "You can verify the publish ivy artifacts in local repository."
},
{
"code": null,
"e": 34557,
"s": 34446,
"text": "info task is used to set ivy specific information in a file and can be used without any dependency resolution."
},
{
"code": null,
"e": 34649,
"s": 34557,
"text": "Let's create Tester.java, build.xml and ivy.xml as described in IVY - Resolve Task chapter."
},
{
"code": null,
"e": 34827,
"s": 34649,
"text": "Update the build.xml to use the ivy publish task. First we'll create a jar file and then publish it. Before publish task, we've set the required ivy information using info task."
},
{
"code": null,
"e": 34837,
"s": 34827,
"text": "build.xml"
},
{
"code": null,
"e": 35608,
"s": 34837,
"text": "<project name=\"test\" default=\"resolve\" xmlns:ivy=\"antlib:org.apache.ivy.ant\">\n <property name = \"build.dir\" value = \"build\"/>\n <target name=\"resolve\" description=\"resolve dependencies\">\n <ivy:resolve />\n </target>\n <target name = \"jar\">\n <jar destfile = \"${build.dir}/lib/application.jar\"\n basedir = \"${build.dir}/classes\"> \n <manifest>\n <attribute name = \"Main-Class\" value = \"com.tutorialspoint.Application\"/>\n </manifest>\n </jar>\n </target>\n <target name=\"publish\" depends=\"jar\">\n <ivy:info file=\"ivy.xml\" />\n <ivy:publish resolver=\"local\" pubrevision=\"1.0\" overwrite=\"true\">\n <artifacts pattern=\"${build.dir}/lib/[artifact].[ext]\" />\n </ivy:publish> \n </target>\n</project>"
},
{
"code": null,
"e": 35743,
"s": 35608,
"text": "Here publish task first build the jar, then set the information using ivy:info task and then publish the artifact to local repository."
},
{
"code": null,
"e": 35848,
"s": 35743,
"text": "As we've all the files ready. Just go the console. Navigate to E: > ivy folder and run the ant command."
},
{
"code": null,
"e": 35870,
"s": 35848,
"text": "E:\\ivy > ant publish\n"
},
{
"code": null,
"e": 35960,
"s": 35870,
"text": "Ivy will come into action, resolving the dependencies, you will see the following result."
},
{
"code": null,
"e": 36542,
"s": 35960,
"text": "Buildfile: E:\\ivy\\build.xml\njar:\npublish:\n [ivy:info] :: Apache Ivy 2.5.0 - 20191020104435 :: https://ant.apache.org/ivy/\n::\n [ivy:info] :: loading settings :: url = jar:file:/E:/Apache/apache-ant-1.9.14/l\nib/ivy-2.5.0.jar!/org/apache/ivy/core/settings/ivysettings.xml\n[ivy:publish] :: publishing :: com.tutorialspoint#test\n[ivy:publish] published application to C:\\Users\\Acer\\.ivy2\\local\\com.tutorials\npoint\\test\\1.0\\jars\\application.jar\n[ivy:publish] published ivy to C:\\Users\\Acer\\.ivy2\\local\\com.tutorialspoint\\te\nst\\1.0\\ivys\\ivy.xml\nBUILD SUCCESSFUL\nTotal time: 0 seconds\n"
},
{
"code": null,
"e": 36703,
"s": 36542,
"text": "If we do not put the info task then publish task will not work. Use the below modified build.xml and see the error for missing organization attribute and so on."
},
{
"code": null,
"e": 36713,
"s": 36703,
"text": "build.xml"
},
{
"code": null,
"e": 37450,
"s": 36713,
"text": "<project name=\"test\" default=\"resolve\" xmlns:ivy=\"antlib:org.apache.ivy.ant\">\n <property name = \"build.dir\" value = \"build\"/>\n <target name=\"resolve\" description=\"resolve dependencies\">\n <ivy:resolve />\n </target>\n <target name = \"jar\">\n <jar destfile = \"${build.dir}/lib/application.jar\"\n basedir = \"${build.dir}/classes\"> \n <manifest>\n <attribute name = \"Main-Class\" value = \"com.tutorialspoint.Application\"/>\n </manifest>\n </jar>\n </target>\n <target name=\"publish\" depends=\"jar\">\n <ivy:publish resolver=\"local\" pubrevision=\"1.0\" overwrite=\"true\">\n <artifacts pattern=\"${build.dir}/lib/[artifact].[ext]\" />\n </ivy:publish> \n </target>\n</project>"
},
{
"code": null,
"e": 37504,
"s": 37450,
"text": "Navigate to E: > ivy folder and run the ant command."
},
{
"code": null,
"e": 37526,
"s": 37504,
"text": "E:\\ivy > ant publish\n"
},
{
"code": null,
"e": 37616,
"s": 37526,
"text": "Ivy will come into action, resolving the dependencies, you will see the following result."
},
{
"code": null,
"e": 38126,
"s": 37616,
"text": "Buildfile: E:\\ivy\\build.xml\njar:\npublish:\n[ivy:publish] :: Apache Ivy 2.5.0 - 20191020104435 :: https://ant.apache.org/ivy\n/ ::\n[ivy:publish] :: loading settings :: url = jar:file:/E:/Apache/apache-ant-1.9.14\n/lib/ivy-2.5.0.jar!/org/apache/ivy/core/settings/ivysettings.xml\nBUILD FAILED\nE:\\ivy\\build.xml:28: no organisation provided for ivy publish task: It can eithe\nr be set explicitly via the attribute 'organisation' or via 'ivy.organisation' p\nroperty or a prior call to <resolve/>\nTotal time: 3 seconds\n"
},
{
"code": null,
"e": 38292,
"s": 38126,
"text": "Resolvers are used to find locations from where a library is to be downloaded. A dependency resolver also handles common tasks. Ivy provides two types of Resolvers. "
},
{
"code": null,
"e": 38359,
"s": 38292,
"text": "Composite − A resolver which uses other resolvers to do its tasks."
},
{
"code": null,
"e": 38426,
"s": 38359,
"text": "Composite − A resolver which uses other resolvers to do its tasks."
},
{
"code": null,
"e": 38477,
"s": 38426,
"text": "Standard − A resolver performs the required tasks."
},
{
"code": null,
"e": 38528,
"s": 38477,
"text": "Standard − A resolver performs the required tasks."
},
{
"code": null,
"e": 38595,
"s": 38528,
"text": "Following table lists down the standard resolvers and their usage."
},
{
"code": null,
"e": 38613,
"s": 38595,
"text": "IvyRep (Standard)"
},
{
"code": null,
"e": 38632,
"s": 38613,
"text": "IBiblio (Standard)"
},
{
"code": null,
"e": 38651,
"s": 38632,
"text": "BinTray (Standard)"
},
{
"code": null,
"e": 38671,
"s": 38651,
"text": "Packager (Standard)"
},
{
"code": null,
"e": 38693,
"s": 38671,
"text": "FileSystem (Standard)"
},
{
"code": null,
"e": 38708,
"s": 38693,
"text": "URL (Standard)"
},
{
"code": null,
"e": 38731,
"s": 38708,
"text": "MirroredURL (Standard)"
},
{
"code": null,
"e": 38746,
"s": 38731,
"text": "VFS (Standard)"
},
{
"code": null,
"e": 38761,
"s": 38746,
"text": "SSH (Standard)"
},
{
"code": null,
"e": 38777,
"s": 38761,
"text": "SFTP (Standard)"
},
{
"code": null,
"e": 38792,
"s": 38777,
"text": "Jar (Standard)"
},
{
"code": null,
"e": 38810,
"s": 38792,
"text": "Chain (Composite)"
},
{
"code": null,
"e": 38827,
"s": 38810,
"text": "Dual (Composite)"
},
{
"code": null,
"e": 38842,
"s": 38827,
"text": "OBR (Standard)"
},
{
"code": null,
"e": 38872,
"s": 38842,
"text": "Eclipse updatesite (Standard)"
},
{
"code": null,
"e": 38893,
"s": 38872,
"text": "OSGi-agg (Composite)"
},
{
"code": null,
"e": 39129,
"s": 38893,
"text": "Let's create Tester.java, build.xml and ivy.xml in a new project under E: > ivy2 folder similar to as described in IVY - Resolve Task chapter. Create a settings folder under E: > ivy2. Create the ivysettings.xml in the settings folder."
},
{
"code": null,
"e": 39139,
"s": 39129,
"text": "build.xml"
},
{
"code": null,
"e": 39646,
"s": 39139,
"text": "<project name=\"test\" default=\"resolve\" xmlns:ivy=\"antlib:org.apache.ivy.ant\">\n <property name = \"build.dir\" value = \"build\"/>\n <property name = \"base.dir\" value = \"\"/>\n <target name=\"resolve\" description=\"resolve dependencies\">\n <ivy:resolve />\n </target>\n <target name=\"compile\" depends=\"resolve\" description=\"Compile\">\n <mkdir dir=\"build/classes\" />\n <javac srcdir=\"src\" destdir=\"build/classes\">\n <classpath refid=\"new.classpath\" />\n </javac>\n </target>\n</project>"
},
{
"code": null,
"e": 39654,
"s": 39646,
"text": "ivy.xml"
},
{
"code": null,
"e": 40122,
"s": 39654,
"text": "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n<ivy-module version=\"2.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:noNamespaceSchemaLocation=\"http://ant.apache.org/ivy/schemas/ivy.xsd\">\n <info organisation=\"org.apache\" module=\"chained-resolvers\"/>\n <dependencies>\n <dependency org=\"commons-lang\" name=\"commons-lang\" rev=\"2.6\" conf=\"default\"/>\n <dependency org=\"com.tutorialspoint\" name=\"test\" rev=\"1.0\"/>\n </dependencies>\n</ivy-module>"
},
{
"code": null,
"e": 40254,
"s": 40122,
"text": "Here we've added two dependencies,one of commons-lang library and another as test which we published in IVY - Publish Task chapter."
},
{
"code": null,
"e": 40270,
"s": 40254,
"text": "ivysettings.xml"
},
{
"code": null,
"e": 40637,
"s": 40270,
"text": "<ivysettings>\n <settings defaultResolver=\"multiresolver\"/>\n <resolvers>\n <chain name=\"multiresolver\">\n <filesystem name=\"libraries\">\n <artifact pattern=\"${ivy.settings.dir}/repository/[artifact]-[revision].[ext]\"/>\n </filesystem>\n <ibiblio name=\"ibiblio\" m2compatible=\"true\"/>\n </chain>\n </resolvers>\n</ivysettings>"
},
{
"code": null,
"e": 40837,
"s": 40637,
"text": "Here we've added created a composite resolver using chain resolver which has two resolver, one named libraries to locate libaries on local repository and one named ibiblio on maven public repository."
},
{
"code": null,
"e": 40943,
"s": 40837,
"text": "As we've all the files ready. Just go the console. Navigate to E: > ivy2 folder and run the ant command."
},
{
"code": null,
"e": 40957,
"s": 40943,
"text": "E:\\ivy > ant\n"
},
{
"code": null,
"e": 41047,
"s": 40957,
"text": "Ivy will come into action, resolving the dependencies, you will see the following result."
},
{
"code": null,
"e": 42413,
"s": 41047,
"text": "Buildfile: E:\\ivy2\\build.xml\nresolve:\n[ivy:resolve] :: Apache Ivy 2.5.0 - 20191020104435 :: https://ant.apache.org/ivy\n/ ::\n[ivy:resolve] :: loading settings :: url = jar:file:/E:/Apache/apache-ant-1.9.14\n/lib/ivy-2.5.0.jar!/org/apache/ivy/core/settings/ivysettings.xml\n[ivy:resolve] :: resolving dependencies :: org.apache#chained-resolvers;working@\nAcer-PC\n[ivy:resolve] confs: [default]\n[ivy:resolve] found commons-lang#commons-lang;2.6 in public\n[ivy:resolve] found com.tutorialspoint#test;1.0 in local\n[ivy:resolve] found junit#junit;3.8.1 in public\n[ivy:resolve] downloading C:\\Users\\Acer\\.ivy2\\local\\com.tutorialspoint\\test\\1.0\\\njars\\application.jar ...\n[ivy:resolve] .. (1kB)\n[ivy:resolve] .. (0kB)\n[ivy:resolve] [SUCCESSFUL ] com.tutorialspoint#test;1.0!application.jar (13ms)\n[ivy:resolve] :: resolution report :: resolve 1085ms :: artifacts dl 22ms\n ---------------------------------------------------------------------\n | | modules || artifacts |\n | conf | number| search|dwnlded|evicted|| number|dwnlded|\n ---------------------------------------------------------------------\n | default | 3 | 3 | 1 | 0 || 5 | 1 |\n ---------------------------------------------------------------------\nBUILD SUCCESSFUL\nTotal time: 9 seconds\n"
},
{
"code": null,
"e": 42502,
"s": 42413,
"text": "In the logs you can verify that we have used both local and public repository resolvers."
},
{
"code": null,
"e": 42820,
"s": 42502,
"text": "A local repository is a private repository of a user. It is very useful in case a user is using a library whose version has been changed on other places and have breaking changes. In case of local repository, ivy will use the library present in the local if found and will not look into public or shared repositories."
},
{
"code": null,
"e": 42988,
"s": 42820,
"text": "By default, local repository is present in ${ivy.default.ivy.user.dir}/local folder. If you want to change it, the use the ivy.local.default.root variable in ant file."
},
{
"code": null,
"e": 42998,
"s": 42988,
"text": "build.xml"
},
{
"code": null,
"e": 43130,
"s": 42998,
"text": "<target name=\"resolve\">\n <property name=\"ivy.local.default.root\" value=\"/opt/ivy/repository/local\"/>\n <ivy:resolve />\n</target>"
},
{
"code": null,
"e": 43221,
"s": 43130,
"text": "Other properties like ivy pattern and artifact pattern can also be customized as follows −"
},
{
"code": null,
"e": 43231,
"s": 43221,
"text": "build.xml"
},
{
"code": null,
"e": 43553,
"s": 43231,
"text": "<target name=\"resolve\">\n <property name=\"ivy.local.default.root\" value=\"/opt/ivy/repository/local\"/>\n <property name=\"ivy.local.default.ivy.pattern\" value=\"[module]/[revision]/ivy.xml\"/>\n <property name=\"ivy.local.default.artifact.pattern\" value=\"[module]/[revision]/[artifact].[ext]\"/>\n <ivy:resolve />\n</target>"
},
{
"code": null,
"e": 43630,
"s": 43553,
"text": "By default ivy has its configurations in ivysettings.xml present in ivy.jar."
},
{
"code": null,
"e": 43646,
"s": 43630,
"text": "ivysettings.xml"
},
{
"code": null,
"e": 44081,
"s": 43646,
"text": "<ivysettings>\n <settings defaultResolver=\"default\"/>\n <include url=\"${ivy.default.settings.dir}/ivysettings-public.xml\"/>\n <include url=\"${ivy.default.settings.dir}/ivysettings-shared.xml\"/>\n <include url=\"${ivy.default.settings.dir}/ivysettings-local.xml\"/>\n <include url=\"${ivy.default.settings.dir}/ivysettings-main-chain.xml\"/>\n <include url=\"${ivy.default.settings.dir}/ivysettings-default-chain.xml\"/>\n</ivysettings>"
},
{
"code": null,
"e": 44165,
"s": 44081,
"text": "To override local repository setting, update the contents of ivysettings-local.xml."
},
{
"code": null,
"e": 44187,
"s": 44165,
"text": "ivysettings-local.xml"
},
{
"code": null,
"e": 44864,
"s": 44187,
"text": "<ivysettings>\n <property name=\"ivy.local.default.root\" value=\"${ivy.default.ivy.user.dir}/local\" override=\"false\"/>\n <property name=\"ivy.local.default.ivy.pattern\" value=\"[organisation]/[module]/[revision]/[type]s/[artifact].[ext]\" override=\"false\"/>\n <property name=\"ivy.local.default.artifact.pattern\" value=\"[organisation]/[module]/[revision]/[type]s/[artifact].[ext]\" override=\"false\"/>\n <resolvers>\n <filesystem name=\"local\">\n <ivy pattern=\"${ivy.local.default.root}/${ivy.local.default.ivy.pattern}\" />\n <artifact pattern=\"${ivy.local.default.root}/${ivy.local.default.artifact.pattern}\" />\n </filesystem>\n </resolvers>\n</ivysettings>"
},
{
"code": null,
"e": 44982,
"s": 44864,
"text": "A shared repository is a team level shared repository of a team. It is very common to be overridden in organizations."
},
{
"code": null,
"e": 45153,
"s": 44982,
"text": "By default, shared repository is present in ${ivy.default.ivy.user.dir}/shared folder. If you want to change it, the use the ivy.shared.default.root variable in ant file."
},
{
"code": null,
"e": 45163,
"s": 45153,
"text": "build.xml"
},
{
"code": null,
"e": 45297,
"s": 45163,
"text": "<target name=\"resolve\">\n <property name=\"ivy.shared.default.root\" value=\"/opt/ivy/repository/shared\"/>\n <ivy:resolve />\n</target>"
},
{
"code": null,
"e": 45388,
"s": 45297,
"text": "Other properties like ivy pattern and artifact pattern can also be customized as follows −"
},
{
"code": null,
"e": 45398,
"s": 45388,
"text": "build.xml"
},
{
"code": null,
"e": 45754,
"s": 45398,
"text": "<target name=\"resolve\">\n <property name=\"ivy.shared.default.root\" value=\"/opt/ivy/repository/shared\"/>\n <property name=\"ivy.shared.default.ivy.pattern\" value=\"[organisation]/[module]/[revision]/ivy.xml\"/>\n <property name=\"ivy.shared.default.artifact.pattern\" value=\"[organisation]/[module]/[revision]/[artifact].[ext]\"/>\n <ivy:resolve />\n</target>"
},
{
"code": null,
"e": 45831,
"s": 45754,
"text": "By default ivy has its configurations in ivysettings.xml present in ivy.jar."
},
{
"code": null,
"e": 45847,
"s": 45831,
"text": "ivysettings.xml"
},
{
"code": null,
"e": 46282,
"s": 45847,
"text": "<ivysettings>\n <settings defaultResolver=\"default\"/>\n <include url=\"${ivy.default.settings.dir}/ivysettings-public.xml\"/>\n <include url=\"${ivy.default.settings.dir}/ivysettings-shared.xml\"/>\n <include url=\"${ivy.default.settings.dir}/ivysettings-local.xml\"/>\n <include url=\"${ivy.default.settings.dir}/ivysettings-main-chain.xml\"/>\n <include url=\"${ivy.default.settings.dir}/ivysettings-default-chain.xml\"/>\n</ivysettings>"
},
{
"code": null,
"e": 46368,
"s": 46282,
"text": "To override shared repository setting, update the contents of ivysettings-shared.xml."
},
{
"code": null,
"e": 46391,
"s": 46368,
"text": "ivysettings-shared.xml"
},
{
"code": null,
"e": 47077,
"s": 46391,
"text": "<ivysettings>\n <property name=\"ivy.shared.default.root\" value=\"${ivy.default.ivy.user.dir}/shared\" override=\"false\"/>\n <property name=\"ivy.shared.default.ivy.pattern\" value=\"[organisation]/[module]/[revision]/[type]s/[artifact].[ext]\" override=\"false\"/>\n <property name=\"ivy.shared.default.artifact.pattern\" value=\"[organisation]/[module]/[revision]/[type]s/[artifact].[ext]\" override=\"false\"/>\n <resolvers>\n <filesystem name=\"shared\">\n <ivy pattern=\"${ivy.shared.default.root}/${ivy.shared.default.ivy.pattern}\" />\n <artifact pattern=\"${ivy.shared.default.root}/${ivy.shared.default.artifact.pattern}\" />\n </filesystem>\n </resolvers>\n</ivysettings>"
},
{
"code": null,
"e": 47286,
"s": 47077,
"text": "A public repository is a repository accessible using internet and have third party modules. By default ibiblio in m2 compatible mode is the public repository. It is also referred as maven 2 public repository."
},
{
"code": null,
"e": 47363,
"s": 47286,
"text": "By default ivy has its configurations in ivysettings.xml present in ivy.jar."
},
{
"code": null,
"e": 47379,
"s": 47363,
"text": "ivysettings.xml"
},
{
"code": null,
"e": 47814,
"s": 47379,
"text": "<ivysettings>\n <settings defaultResolver=\"default\"/>\n <include url=\"${ivy.default.settings.dir}/ivysettings-public.xml\"/>\n <include url=\"${ivy.default.settings.dir}/ivysettings-shared.xml\"/>\n <include url=\"${ivy.default.settings.dir}/ivysettings-local.xml\"/>\n <include url=\"${ivy.default.settings.dir}/ivysettings-main-chain.xml\"/>\n <include url=\"${ivy.default.settings.dir}/ivysettings-default-chain.xml\"/>\n</ivysettings>"
},
{
"code": null,
"e": 47964,
"s": 47814,
"text": "To override public repository setting, update the contents of ivysettings-public.xml or create the ivysettings.xml in setting folder of your project."
},
{
"code": null,
"e": 47980,
"s": 47964,
"text": "ivysettings.xml"
},
{
"code": null,
"e": 48411,
"s": 47980,
"text": "<ivysettings>\n <settings defaultResolver=\"default\"/>\n <include url=\"http://customserver/ivy/ivysettings-public.xml\"/>\n <include url=\"${ivy.default.settings.dir}/ivysettings-shared.xml\"/>\n <include url=\"${ivy.default.settings.dir}/ivysettings-local.xml\"/>\n <include url=\"${ivy.default.settings.dir}/ivysettings-main-chain.xml\"/>\n <include url=\"${ivy.default.settings.dir}/ivysettings-default-chain.xml\"/>\n</ivysettings>"
},
{
"code": null,
"e": 48462,
"s": 48411,
"text": "Update the default ivysetting-public.xml contents."
},
{
"code": null,
"e": 48495,
"s": 48462,
"text": "Original - ivysetting-public.xml"
},
{
"code": null,
"e": 48606,
"s": 48495,
"text": "<ivysettings>\n <resolvers>\n <ibiblio name=\"public\" m2compatible=\"true\"/>\n </resolvers>\n</ivysettings>"
},
{
"code": null,
"e": 48638,
"s": 48606,
"text": "Updated - ivysetting-public.xml"
},
{
"code": null,
"e": 48951,
"s": 48638,
"text": "<ivysettings>\n <resolvers>\n <filesystem name=\"public\">\n <ivy pattern=\"/path/to/my/public/rep/[organisation]/[module]/ivy-[revision].xml\" />\n <artifact pattern=\"/path/to/my/public/rep/[organisation]/[module]/[artifact]-[revision].[ext]\" />\n </filesystem>\n </resolvers>\n</ivysettings>"
},
{
"code": null,
"e": 48986,
"s": 48951,
"text": "\n 46 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 49005,
"s": 48986,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 49040,
"s": 49005,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 49061,
"s": 49040,
"text": " Mukund Kumar Mishra"
},
{
"code": null,
"e": 49094,
"s": 49061,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 49107,
"s": 49094,
"text": " Nilay Mehta"
},
{
"code": null,
"e": 49142,
"s": 49107,
"text": "\n 52 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 49160,
"s": 49142,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 49193,
"s": 49160,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 49211,
"s": 49193,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 49244,
"s": 49211,
"text": "\n 23 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 49262,
"s": 49244,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 49269,
"s": 49262,
"text": " Print"
},
{
"code": null,
"e": 49280,
"s": 49269,
"text": " Add Notes"
}
] |
Plotly Python: Scatter Plots. A Deep Dive Into Scatter Plots with... | by Bryan White | Towards Data Science
|
In my last article on Plotly, we did a quick introduction to the library itself — covering the general structure of a graph object, using traces, and making customization's through the update_trace and update_layout functions.
Today we’re going to take a more intensive look at building and customizing scatter plots using the Plotly library.
For our dataset today, I have selected a Steam Games dataset from Kaggle, and I am interested in seeing if there is any relationship between the price of the game and the average playtime.
Loading into a dataframe, we can see the head as below:
Now, if you aren’t familiar with Steam you may not realize just how many games are on the platform. In the case of this dataset, if we do a count of the number of entries in the name column, we get 27075 titles.
However, since anyone can publish on Steam there are also a lot of outlier games that will affect our results — namely the amount of games with an average playtime of 0.If we run steamdf[steamdf[‘average_playtime’] == 0].count()we can see that there are 20905 games with no playtime!
Once I applied the criteria of:
steamdf = steamdf[(steamdf['average_playtime'] != 0) & (steamdf['average_playtime'] < 40000)] steamdf = steamdf[steamdf['price'] < 80]
I am left with 6160 games that we can look at.
So, let’s throw this into a quick scatter plot figure and see what the initial data looks like.
import plotly.graph_objects as gofig = go.Figure(data=go.Scatter( x=steamdf['price'], y=steamdf['average_playtime'], mode='markers'))fig.show()
Pretty basic — but hey, we need to start somewhere, right?
Let’s go ahead and add a title and axis legends.While we’re at it, let’s style our markers a little. They look a little bland and blend in together.
import plotly.graph_objects as gofig = go.Figure(data=go.Scatter( x=steamdf['price'], y=steamdf['average_playtime'], mode='markers', marker_size=steamdf['ratio'], marker=dict( color='rgb(255, 178, 102)', size=10, line=dict( color='DarkSlateGrey', width=1 ) )))fig.update_layout( title='Price vs. Average Playtime', xaxis_title='Price (GBP)', yaxis_title='Average Playtime (Minutes)')fig.show()
We start by using marker=dict() which then takes all the parameters that we use to style our markers (data points). There is an additional dict within marker that corresponds to the style options for the marker border.
Note how we color the markers themselves using an RGB value, whereas we color the marker outline with a CSS color code.Both are perfectly acceptable — you can even use RGBA to set the alpha.
The marker size is adjusted via the marker_size attribute. I created a new dataframe column ‘ratio’ where I did a scaled value of the positive_ratings / negative_ratings.A larger bubble means the game had a higher ratio of positive to negative ratings; we expect these games to generally have a higher average playtime.
Right now when we hover over the points, we only see the x and y values which isn’t exactly useful. However, it’s easy to add proper hover text to our points, so we can see the name of the game that we’re looking at.
By including the below code in our Figure object we can take the above hover data and turn it into something much better!
hovertext=steamdf['name'],hoverlabel=dict(namelength=0),hovertemplate='%{hovertext}<br>Price: %{x} <br>Avg. Playtime: %{y}'
It may look a little overwhelming, but lets break it down:-hovertext is a variable we are defining for use in our template-hoverlabel is mainly aesthetic in purpose. If you keep it in you may see the trace number off to the side of the tooltip box. I don’t like it, so this code will remove it.-hovertemplate allows you to create a template string to render whatever information you want to appear on the hoverbox.
Variables are added using the %{variable} format and you can make use of HTML tags such as <br>, <i>, <b>, etc.
You could spend countless hours playing around with all the style options that are available.If you feel you are lacking some inspiration, you could use the template property in fig.update_layout().
Example: fig.update_layout(template=’plotly_white’)
Options are: “plotly”, “plotly_white”, “plotly_dark”, “ggplot2”, “seaborn”, “simple_white”
However, I have whipped up something quickly to show you some of the most common customization’s you’ll want to do.
Namely, we have changed:- Axis grid/zero/plot border lines (color, width, and visibility)- Plot background and paper background colors- Title font, size, color- Custom ranging
fig = go.Figure(data=go.Scatter( x=steamdf['price'], y=steamdf['average_playtime'], mode='markers', marker_size=steamdf['ratio'], hovertext=steamdf['name'], hoverlabel=dict(namelength=0), hovertemplate='%{hovertext}<br>Price: %{x:$} <br>Avg. Playtime: %{y:,} min', marker=dict( color='rgb(255, 178, 102)', size=10, line=dict( color='DarkSlateGrey', width=1 ) )))fig.update_layout( title='Price vs. Average Playtime', xaxis_title='Price (GBP)', yaxis_title='Average Playtime (Minutes)', plot_bgcolor = 'white', paper_bgcolor = 'whitesmoke', font=dict( family='Verdana', size=16, color='black' ))fig.update_xaxes(showline=True, linewidth=2, linecolor='black', mirror=True, showgrid=False, zerolinecolor='black', zerolinewidth=1, range=[-1, 65])fig.update_yaxes(showline=True, linewidth=2, linecolor='black', mirror=True, showgrid=True, gridwidth=1, gridcolor='grey', zerolinecolor='black', zerolinewidth=1, range=[-2000, 40000])fig.show()
I hope this covers enough to get you feeling confident with creating and customizing scatter plots with Plotly!
|
[
{
"code": null,
"e": 399,
"s": 172,
"text": "In my last article on Plotly, we did a quick introduction to the library itself — covering the general structure of a graph object, using traces, and making customization's through the update_trace and update_layout functions."
},
{
"code": null,
"e": 515,
"s": 399,
"text": "Today we’re going to take a more intensive look at building and customizing scatter plots using the Plotly library."
},
{
"code": null,
"e": 704,
"s": 515,
"text": "For our dataset today, I have selected a Steam Games dataset from Kaggle, and I am interested in seeing if there is any relationship between the price of the game and the average playtime."
},
{
"code": null,
"e": 760,
"s": 704,
"text": "Loading into a dataframe, we can see the head as below:"
},
{
"code": null,
"e": 972,
"s": 760,
"text": "Now, if you aren’t familiar with Steam you may not realize just how many games are on the platform. In the case of this dataset, if we do a count of the number of entries in the name column, we get 27075 titles."
},
{
"code": null,
"e": 1256,
"s": 972,
"text": "However, since anyone can publish on Steam there are also a lot of outlier games that will affect our results — namely the amount of games with an average playtime of 0.If we run steamdf[steamdf[‘average_playtime’] == 0].count()we can see that there are 20905 games with no playtime!"
},
{
"code": null,
"e": 1288,
"s": 1256,
"text": "Once I applied the criteria of:"
},
{
"code": null,
"e": 1433,
"s": 1288,
"text": "steamdf = steamdf[(steamdf['average_playtime'] != 0) & (steamdf['average_playtime'] < 40000)] steamdf = steamdf[steamdf['price'] < 80]"
},
{
"code": null,
"e": 1480,
"s": 1433,
"text": "I am left with 6160 games that we can look at."
},
{
"code": null,
"e": 1576,
"s": 1480,
"text": "So, let’s throw this into a quick scatter plot figure and see what the initial data looks like."
},
{
"code": null,
"e": 1765,
"s": 1576,
"text": "import plotly.graph_objects as gofig = go.Figure(data=go.Scatter( x=steamdf['price'], y=steamdf['average_playtime'], mode='markers'))fig.show()"
},
{
"code": null,
"e": 1824,
"s": 1765,
"text": "Pretty basic — but hey, we need to start somewhere, right?"
},
{
"code": null,
"e": 1973,
"s": 1824,
"text": "Let’s go ahead and add a title and axis legends.While we’re at it, let’s style our markers a little. They look a little bland and blend in together."
},
{
"code": null,
"e": 2592,
"s": 1973,
"text": "import plotly.graph_objects as gofig = go.Figure(data=go.Scatter( x=steamdf['price'], y=steamdf['average_playtime'], mode='markers', marker_size=steamdf['ratio'], marker=dict( color='rgb(255, 178, 102)', size=10, line=dict( color='DarkSlateGrey', width=1 ) )))fig.update_layout( title='Price vs. Average Playtime', xaxis_title='Price (GBP)', yaxis_title='Average Playtime (Minutes)')fig.show()"
},
{
"code": null,
"e": 2811,
"s": 2592,
"text": "We start by using marker=dict() which then takes all the parameters that we use to style our markers (data points). There is an additional dict within marker that corresponds to the style options for the marker border."
},
{
"code": null,
"e": 3002,
"s": 2811,
"text": "Note how we color the markers themselves using an RGB value, whereas we color the marker outline with a CSS color code.Both are perfectly acceptable — you can even use RGBA to set the alpha."
},
{
"code": null,
"e": 3322,
"s": 3002,
"text": "The marker size is adjusted via the marker_size attribute. I created a new dataframe column ‘ratio’ where I did a scaled value of the positive_ratings / negative_ratings.A larger bubble means the game had a higher ratio of positive to negative ratings; we expect these games to generally have a higher average playtime."
},
{
"code": null,
"e": 3539,
"s": 3322,
"text": "Right now when we hover over the points, we only see the x and y values which isn’t exactly useful. However, it’s easy to add proper hover text to our points, so we can see the name of the game that we’re looking at."
},
{
"code": null,
"e": 3661,
"s": 3539,
"text": "By including the below code in our Figure object we can take the above hover data and turn it into something much better!"
},
{
"code": null,
"e": 3785,
"s": 3661,
"text": "hovertext=steamdf['name'],hoverlabel=dict(namelength=0),hovertemplate='%{hovertext}<br>Price: %{x} <br>Avg. Playtime: %{y}'"
},
{
"code": null,
"e": 4200,
"s": 3785,
"text": "It may look a little overwhelming, but lets break it down:-hovertext is a variable we are defining for use in our template-hoverlabel is mainly aesthetic in purpose. If you keep it in you may see the trace number off to the side of the tooltip box. I don’t like it, so this code will remove it.-hovertemplate allows you to create a template string to render whatever information you want to appear on the hoverbox."
},
{
"code": null,
"e": 4312,
"s": 4200,
"text": "Variables are added using the %{variable} format and you can make use of HTML tags such as <br>, <i>, <b>, etc."
},
{
"code": null,
"e": 4511,
"s": 4312,
"text": "You could spend countless hours playing around with all the style options that are available.If you feel you are lacking some inspiration, you could use the template property in fig.update_layout()."
},
{
"code": null,
"e": 4563,
"s": 4511,
"text": "Example: fig.update_layout(template=’plotly_white’)"
},
{
"code": null,
"e": 4654,
"s": 4563,
"text": "Options are: “plotly”, “plotly_white”, “plotly_dark”, “ggplot2”, “seaborn”, “simple_white”"
},
{
"code": null,
"e": 4770,
"s": 4654,
"text": "However, I have whipped up something quickly to show you some of the most common customization’s you’ll want to do."
},
{
"code": null,
"e": 4946,
"s": 4770,
"text": "Namely, we have changed:- Axis grid/zero/plot border lines (color, width, and visibility)- Plot background and paper background colors- Title font, size, color- Custom ranging"
},
{
"code": null,
"e": 6497,
"s": 4946,
"text": "fig = go.Figure(data=go.Scatter( x=steamdf['price'], y=steamdf['average_playtime'], mode='markers', marker_size=steamdf['ratio'], hovertext=steamdf['name'], hoverlabel=dict(namelength=0), hovertemplate='%{hovertext}<br>Price: %{x:$} <br>Avg. Playtime: %{y:,} min', marker=dict( color='rgb(255, 178, 102)', size=10, line=dict( color='DarkSlateGrey', width=1 ) )))fig.update_layout( title='Price vs. Average Playtime', xaxis_title='Price (GBP)', yaxis_title='Average Playtime (Minutes)', plot_bgcolor = 'white', paper_bgcolor = 'whitesmoke', font=dict( family='Verdana', size=16, color='black' ))fig.update_xaxes(showline=True, linewidth=2, linecolor='black', mirror=True, showgrid=False, zerolinecolor='black', zerolinewidth=1, range=[-1, 65])fig.update_yaxes(showline=True, linewidth=2, linecolor='black', mirror=True, showgrid=True, gridwidth=1, gridcolor='grey', zerolinecolor='black', zerolinewidth=1, range=[-2000, 40000])fig.show()"
}
] |
Is it possible to give arguments in the main() function in C language?
|
Yes, we can give arguments in the main() function.
Command line arguments in C are specified after the name of the program in the system’s command line, and these argument values are passed on to your program during program execution.
The argc and argv are the two arguments that can pass to main function.
But main() function is actually called by the operating system (or shell program) when you run the program from the terminal.
The syntax is explained below −
int main(int argc, char *argv[]){
//Code
return 0;
}
Live Demo
#include<stdio.h>
int main(int argc, char *argv[]){
int i;
for (i = 0; i < argc; i++) {
printf("Arg %d: %s\n", i, argv[i]);
}
return 1;
}
Arg 0: G:\CP\CP programs\main with arguments.exe
Explanation:
The program that prints all the arguments passed to your program, including the program name itself.
|
[
{
"code": null,
"e": 1113,
"s": 1062,
"text": "Yes, we can give arguments in the main() function."
},
{
"code": null,
"e": 1297,
"s": 1113,
"text": "Command line arguments in C are specified after the name of the program in the system’s command line, and these argument values are passed on to your program during program execution."
},
{
"code": null,
"e": 1369,
"s": 1297,
"text": "The argc and argv are the two arguments that can pass to main function."
},
{
"code": null,
"e": 1495,
"s": 1369,
"text": "But main() function is actually called by the operating system (or shell program) when you run the program from the terminal."
},
{
"code": null,
"e": 1527,
"s": 1495,
"text": "The syntax is explained below −"
},
{
"code": null,
"e": 1586,
"s": 1527,
"text": "int main(int argc, char *argv[]){\n //Code\n return 0;\n}"
},
{
"code": null,
"e": 1597,
"s": 1586,
"text": " Live Demo"
},
{
"code": null,
"e": 1753,
"s": 1597,
"text": "#include<stdio.h>\nint main(int argc, char *argv[]){\n int i;\n for (i = 0; i < argc; i++) {\n printf(\"Arg %d: %s\\n\", i, argv[i]);\n }\n return 1;\n}"
},
{
"code": null,
"e": 1916,
"s": 1753,
"text": "Arg 0: G:\\CP\\CP programs\\main with arguments.exe\nExplanation:\nThe program that prints all the arguments passed to your program, including the program name itself."
}
] |
SQL Tryit Editor v1.6
|
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
LEFT JOIN Orders
ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;
Edit the SQL Statement, and click "Run SQL" to see the result.
This SQL-Statement is not supported in the WebSQL Database.
The example still works, because it uses a modified version of SQL.
Your browser does not support WebSQL.
Your are now using a light-version of the Try-SQL Editor, with a read-only Database.
If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time.
Our Try-SQL Editor uses WebSQL to demonstrate SQL.
A Database-object is created in your browser, for testing purposes.
You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button.
WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object.
WebSQL is supported in Chrome, Safari, Opera, and Edge(79).
If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.
|
[
{
"code": null,
"e": 46,
"s": 0,
"text": "SELECT Customers.CustomerName, Orders.OrderID"
},
{
"code": null,
"e": 61,
"s": 46,
"text": "FROM Customers"
},
{
"code": null,
"e": 78,
"s": 61,
"text": "LEFT JOIN Orders"
},
{
"code": null,
"e": 120,
"s": 78,
"text": "ON Customers.CustomerID=Orders.CustomerID"
},
{
"code": null,
"e": 153,
"s": 120,
"text": "ORDER BY Customers.CustomerName;"
},
{
"code": null,
"e": 155,
"s": 153,
"text": ""
},
{
"code": null,
"e": 218,
"s": 155,
"text": "Edit the SQL Statement, and click \"Run SQL\" to see the result."
},
{
"code": null,
"e": 278,
"s": 218,
"text": "This SQL-Statement is not supported in the WebSQL Database."
},
{
"code": null,
"e": 346,
"s": 278,
"text": "The example still works, because it uses a modified version of SQL."
},
{
"code": null,
"e": 384,
"s": 346,
"text": "Your browser does not support WebSQL."
},
{
"code": null,
"e": 469,
"s": 384,
"text": "Your are now using a light-version of the Try-SQL Editor, with a read-only Database."
},
{
"code": null,
"e": 643,
"s": 469,
"text": "If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time."
},
{
"code": null,
"e": 694,
"s": 643,
"text": "Our Try-SQL Editor uses WebSQL to demonstrate SQL."
},
{
"code": null,
"e": 762,
"s": 694,
"text": "A Database-object is created in your browser, for testing purposes."
},
{
"code": null,
"e": 933,
"s": 762,
"text": "You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the \"Restore Database\" button."
},
{
"code": null,
"e": 1033,
"s": 933,
"text": "WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object."
},
{
"code": null,
"e": 1093,
"s": 1033,
"text": "WebSQL is supported in Chrome, Safari, Opera, and Edge(79)."
}
] |
4 Methods for Adding Columns to Pandas Dataframes | by Soner Yıldırım | Towards Data Science
|
Pandas is a data analysis and manipulation library for Python. It provides numerous functions and methods to manage tabular data. The core data structure of Pandas is data frame which stores data in tabular form with labelled rows and columns.
From data perspective, rows represent observations or data points. Columns represent features or attributes about the observations. Consider a data frame of house prices. Each row is a house and each column is a feature about the house such as age, number of rooms, price, and so on.
Adding or dropping columns is a common operation in data analysis. In this article, we will go over 4 different ways of adding a new column to a data frame.
Let’s first create a simple data frame to use in the examples.
import numpy as npimport pandas as pddf = pd.DataFrame({"A": [1, 2, 3, 4], "B": [5, 6, 7, 8]})df
This might be the most commonly used method for creating a new column.
df["C"] = [10, 20, 30, 40]df
We specify the column name like we are selecting a column in the data frame. Then, the values are assigned to this column. The new column is added as the last column (i.e. the column with the highest index).
We can add multiple columns at once. Column names are passed in a list and values need to be two dimensional compatible with the number of rows and columns. For instance, the following code adds three columns filled with random integers between 0 and 10.
df[["1of3", "2of3", "3of3"]] = np.random.randint(10, size=(4,3))df
Let’s drop these three columns before going to the next method.
df.drop(["1of3", "2of3", "3of3"], axis=1, inplace=True)
In the first method, the new column is added at the end. Pandas also allows for adding new column at a specific index. The insert function can be used to customize the location of the new column. Let’s add one next to column A.
df.insert(1, "D", 5)df
The insert function takes 3 parameters which are the index, the name of the column, and the values. The column indices start from 0 so we set the index parameter as 1 to add the new column next to column A. We can pass a constant value to be filled in all rows.
The loc method selects rows and columns using their labels. It is also possible to create a new column with this method.
df.loc[:, "E"] = list("abcd")df
In order to select rows and columns, we pass the desired labels. The colon indicates that we want to select all the rows. In the column part, we specify the labels of the columns to be selected. Since the data frame does not have column E, Pandas creates a new column.
The last method is the assign function.
df = df.assign(F = df.C * 10)df
We specify both the column name and values inside the assign function. You may notice that we derive the values using another column in the data frame. The previous methods also allow for such derivations.
There is an important difference between the insert and assign functions. The insert function works in place which means the change (adding new column) is saved in the data frame.
The situation is a little different with the assign function. It returns the modified data frame but does not change the original one. In order to use the modified version (with the new column), we need to explicitly assign it.
We have covered 4 different methods for adding new columns to a Pandas data frame. It is a common operation in data analysis and manipulation.
One of the things I like about Pandas is that it usually provides multiple ways to perform a given task. I think it is a result of the flexibility and versatility of Pandas.
Thank you for reading. Please let me know if you have any feedback.
|
[
{
"code": null,
"e": 416,
"s": 172,
"text": "Pandas is a data analysis and manipulation library for Python. It provides numerous functions and methods to manage tabular data. The core data structure of Pandas is data frame which stores data in tabular form with labelled rows and columns."
},
{
"code": null,
"e": 700,
"s": 416,
"text": "From data perspective, rows represent observations or data points. Columns represent features or attributes about the observations. Consider a data frame of house prices. Each row is a house and each column is a feature about the house such as age, number of rooms, price, and so on."
},
{
"code": null,
"e": 857,
"s": 700,
"text": "Adding or dropping columns is a common operation in data analysis. In this article, we will go over 4 different ways of adding a new column to a data frame."
},
{
"code": null,
"e": 920,
"s": 857,
"text": "Let’s first create a simple data frame to use in the examples."
},
{
"code": null,
"e": 1035,
"s": 920,
"text": "import numpy as npimport pandas as pddf = pd.DataFrame({\"A\": [1, 2, 3, 4], \"B\": [5, 6, 7, 8]})df"
},
{
"code": null,
"e": 1106,
"s": 1035,
"text": "This might be the most commonly used method for creating a new column."
},
{
"code": null,
"e": 1135,
"s": 1106,
"text": "df[\"C\"] = [10, 20, 30, 40]df"
},
{
"code": null,
"e": 1343,
"s": 1135,
"text": "We specify the column name like we are selecting a column in the data frame. Then, the values are assigned to this column. The new column is added as the last column (i.e. the column with the highest index)."
},
{
"code": null,
"e": 1598,
"s": 1343,
"text": "We can add multiple columns at once. Column names are passed in a list and values need to be two dimensional compatible with the number of rows and columns. For instance, the following code adds three columns filled with random integers between 0 and 10."
},
{
"code": null,
"e": 1665,
"s": 1598,
"text": "df[[\"1of3\", \"2of3\", \"3of3\"]] = np.random.randint(10, size=(4,3))df"
},
{
"code": null,
"e": 1729,
"s": 1665,
"text": "Let’s drop these three columns before going to the next method."
},
{
"code": null,
"e": 1785,
"s": 1729,
"text": "df.drop([\"1of3\", \"2of3\", \"3of3\"], axis=1, inplace=True)"
},
{
"code": null,
"e": 2013,
"s": 1785,
"text": "In the first method, the new column is added at the end. Pandas also allows for adding new column at a specific index. The insert function can be used to customize the location of the new column. Let’s add one next to column A."
},
{
"code": null,
"e": 2036,
"s": 2013,
"text": "df.insert(1, \"D\", 5)df"
},
{
"code": null,
"e": 2298,
"s": 2036,
"text": "The insert function takes 3 parameters which are the index, the name of the column, and the values. The column indices start from 0 so we set the index parameter as 1 to add the new column next to column A. We can pass a constant value to be filled in all rows."
},
{
"code": null,
"e": 2419,
"s": 2298,
"text": "The loc method selects rows and columns using their labels. It is also possible to create a new column with this method."
},
{
"code": null,
"e": 2451,
"s": 2419,
"text": "df.loc[:, \"E\"] = list(\"abcd\")df"
},
{
"code": null,
"e": 2720,
"s": 2451,
"text": "In order to select rows and columns, we pass the desired labels. The colon indicates that we want to select all the rows. In the column part, we specify the labels of the columns to be selected. Since the data frame does not have column E, Pandas creates a new column."
},
{
"code": null,
"e": 2760,
"s": 2720,
"text": "The last method is the assign function."
},
{
"code": null,
"e": 2792,
"s": 2760,
"text": "df = df.assign(F = df.C * 10)df"
},
{
"code": null,
"e": 2998,
"s": 2792,
"text": "We specify both the column name and values inside the assign function. You may notice that we derive the values using another column in the data frame. The previous methods also allow for such derivations."
},
{
"code": null,
"e": 3178,
"s": 2998,
"text": "There is an important difference between the insert and assign functions. The insert function works in place which means the change (adding new column) is saved in the data frame."
},
{
"code": null,
"e": 3406,
"s": 3178,
"text": "The situation is a little different with the assign function. It returns the modified data frame but does not change the original one. In order to use the modified version (with the new column), we need to explicitly assign it."
},
{
"code": null,
"e": 3549,
"s": 3406,
"text": "We have covered 4 different methods for adding new columns to a Pandas data frame. It is a common operation in data analysis and manipulation."
},
{
"code": null,
"e": 3723,
"s": 3549,
"text": "One of the things I like about Pandas is that it usually provides multiple ways to perform a given task. I think it is a result of the flexibility and versatility of Pandas."
}
] |
Partial Functions in Python - GeeksforGeeks
|
10 Feb, 2020
Partial functions allow us to fix a certain number of arguments of a function and generate a new function.
Example:
from functools import partial # A normal functiondef f(a, b, c, x): return 1000*a + 100*b + 10*c + x # A partial function that calls f with# a as 3, b as 1 and c as 4.g = partial(f, 3, 1, 4) # Calling g()print(g(5))
Output:
3145
In the example we have pre-filled our function with some constant values of a, b and c. And g() just takes a single argument i.e. the variable x.
Another Example :
from functools import * # A normal functiondef add(a, b, c): return 100 * a + 10 * b + c # A partial function with b = 1 and c = 2add_part = partial(add, c = 2, b = 1) # Calling partial functionprint(add_part(3))
Output:
312
Partial functions can be used to derive specialized functions from general functions and therefore help us to reuse our code.
This feature is similar to bind in C++.
YouTubeGeeksforGeeks507K subscribersPython Programming Tutorial | Partial Functions in Python | 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 / 2:56•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=rI8gqpHOyw8" 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 Mayank Rawat .If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Akanksha_Rai
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
|
[
{
"code": null,
"e": 25595,
"s": 25567,
"text": "\n10 Feb, 2020"
},
{
"code": null,
"e": 25702,
"s": 25595,
"text": "Partial functions allow us to fix a certain number of arguments of a function and generate a new function."
},
{
"code": null,
"e": 25711,
"s": 25702,
"text": "Example:"
},
{
"code": "from functools import partial # A normal functiondef f(a, b, c, x): return 1000*a + 100*b + 10*c + x # A partial function that calls f with# a as 3, b as 1 and c as 4.g = partial(f, 3, 1, 4) # Calling g()print(g(5))",
"e": 25933,
"s": 25711,
"text": null
},
{
"code": null,
"e": 25941,
"s": 25933,
"text": "Output:"
},
{
"code": null,
"e": 25947,
"s": 25941,
"text": "3145\n"
},
{
"code": null,
"e": 26093,
"s": 25947,
"text": "In the example we have pre-filled our function with some constant values of a, b and c. And g() just takes a single argument i.e. the variable x."
},
{
"code": null,
"e": 26111,
"s": 26093,
"text": "Another Example :"
},
{
"code": "from functools import * # A normal functiondef add(a, b, c): return 100 * a + 10 * b + c # A partial function with b = 1 and c = 2add_part = partial(add, c = 2, b = 1) # Calling partial functionprint(add_part(3))",
"e": 26330,
"s": 26111,
"text": null
},
{
"code": null,
"e": 26338,
"s": 26330,
"text": "Output:"
},
{
"code": null,
"e": 26343,
"s": 26338,
"text": "312\n"
},
{
"code": null,
"e": 26469,
"s": 26343,
"text": "Partial functions can be used to derive specialized functions from general functions and therefore help us to reuse our code."
},
{
"code": null,
"e": 26509,
"s": 26469,
"text": "This feature is similar to bind in C++."
},
{
"code": null,
"e": 27365,
"s": 26509,
"text": "YouTubeGeeksforGeeks507K subscribersPython Programming Tutorial | Partial Functions in Python | 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 / 2:56•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=rI8gqpHOyw8\" 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": 27665,
"s": 27365,
"text": "This article is contributed by Mayank Rawat .If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 27790,
"s": 27665,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 27803,
"s": 27790,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 27810,
"s": 27803,
"text": "Python"
},
{
"code": null,
"e": 27908,
"s": 27810,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27926,
"s": 27908,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27961,
"s": 27926,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27993,
"s": 27961,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28015,
"s": 27993,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28057,
"s": 28015,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28087,
"s": 28057,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 28113,
"s": 28087,
"text": "Python String | replace()"
},
{
"code": null,
"e": 28142,
"s": 28113,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 28186,
"s": 28142,
"text": "Reading and Writing to text files in Python"
}
] |
Program to print prime numbers from 1 to N. - GeeksforGeeks
|
07 Mar, 2022
Given a number N, the task is to print the prime numbers from 1 to N.Examples:
Input: N = 10
Output: 2, 3, 5, 7
Input: N = 5
Output: 2, 3, 5
Algorithm:
First, take the number N as input.
Then use a for loop to iterate the numbers from 1 to N
Then check for each number to be a prime number. If it is a prime number, print it.
Approach 1: Now, according to formal definition, a number ‘n’ is prime if it is not divisible by any number other than 1 and n. In other words a number is prime if it is not divisible by any number from 2 to n-1.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to display Prime numbers till N#include <bits/stdc++.h>using namespace std; //function to check if a given number is primebool isPrime(int n){ //since 0 and 1 is not prime return false. if(n==1||n==0) return false; //Run a loop from 2 to n-1 for(int i=2; i<n; i++){ // if the number is divisible by i, then n is not a prime number. if(n%i==0) return false; } //otherwise, n is prime number. return true;} // Driver codeint main(){ int N = 100; //check for every number from 1 to N for(int i=1; i<=N; i++){ //check if current number is prime if(isPrime(i)) { cout << i << " "; } } return 0;}
// Java program to display Prime numbers till Nclass GFG{ //function to check if a given number is prime static boolean isPrime(int n){ //since 0 and 1 is not prime return false. if(n==1||n==0)return false; //Run a loop from 2 to n-1 for(int i=2; i<n; i++){ // if the number is divisible by i, then n is not a prime number. if(n%i==0)return false; } //otherwise, n is prime number. return true; } // Driver code public static void main (String[] args) { int N = 100; //check for every number from 1 to N for(int i=1; i<=N; i++){ //check if current number is prime if(isPrime(i)) { System.out.print(i + " "); } } }}
# Python3 program to display Prime numbers till N #function to check if a given number is primedef isPrime(n): #since 0 and 1 is not prime return false. if(n==1 or n==0): return False #Run a loop from 2 to n-1 for i in range(2,n): #if the number is divisible by i, then n is not a prime number. if(n%i==0): return False #otherwise, n is prime number. return True # Driver codeN = 100;#check for every number from 1 to Nfor i in range(1,N+1): #check if current number is prime if(isPrime(i)): print(i,end=" ")
// C# program to display Prime numbers till Nusing System; class GFG{ //function to check if a given number is prime static bool isPrime(int n){ //since 0 and 1 is not prime return false. if(n==1||n==0) return false; //Run a loop from 2 to n-1 for(int i=2; i<n; i++) { // if the number is divisible by i, then n is not a prime number. if(n%i==0) return false; } //otherwise, n is prime number. return true; } // Driver code public static void Main (String[] args) { int N = 100; //check for every number from 1 to N for(int i=1; i<=N; i++) { //check if current number is prime if(isPrime(i)) { Console.Write(i + " "); } } }} // This code is contributed by Rajput-Ji
<script> // JavaScript program to display Prime numbers till N // function to check if a given number is primefunction isPrime( n){ // since 0 and 1 is not prime return false. if(n == 1 || n == 0) return false; // Run a loop from 2 to n-1 for(var i = 2; i < n; i++) { // if the number is divisible by i, then n is not a prime number. if(n % i == 0) return false; } // otherwise, n is prime number. return true;} // Driver codevar N = 100; // check for every number from 1 to N for(var i = 1; i <= N; i++) { // check if current number is prime if(isPrime(i)) { console.log( i ); }} // This code is contributed by ukasp.</script>
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
Time Complexity: O(N^2), Space Complexity: O(1)
Approach 2: For checking if a number is prime or not do we really need to iterate through all the number form 2 to n-1? We already know that a number ‘n’ cannot be divided by any number greater than ‘n/2’. So, according to this logic we only need to iterate through 2 to n/2 since number greater than n/2 cannot divide n.
C++
Java
Python3
C#
Javascript
// C++ program to display Prime numbers till N#include <bits/stdc++.h>using namespace std; //function to check if a given number is primebool isPrime(int n){ //since 0 and 1 is not prime return false. if(n==1||n==0) return false; //Run a loop from 2 to n/2. for(int i=2; i<=n/2; i++) { // if the number is divisible by i, then n is not a prime number. if(n%i==0) return false; } //otherwise, n is prime number. return true;} // Driver codeint main(){ int N = 100; //check for every number from 1 to N for(int i=1; i<=N; i++){ //check if current number is prime if(isPrime(i)) { cout << i << " "; } } return 0;}
// Java program to display// Prime numbers till Nclass GFG{ //function to check if a given number is prime static boolean isPrime(int n){ //since 0 and 1 is not prime return false. if(n==1||n==0) return false; //Run a loop from 2 to n-1 for(int i=2; i<=n/2; i++){ // if the number is divisible by i, then n is not a prime number. if(n%i==0)return false; } //otherwise, n is prime number. return true; } // Driver code public static void main (String[] args) { int N = 100; //check for every number from 1 to N for(int i=1; i<=N; i++){ //check if current number is prime if(isPrime(i)) { System.out.print(i + " "); } } }}
# Python3 program to display Prime numbers till N #function to check if a given number is primedef isPrime(n): #since 0 and 1 is not prime return false. if(n==1 or n==0): return False #Run a loop from 2 to n/2 for i in range(2,(n//2)+1): #if the number is divisible by i, then n is not a prime number. if(n%i==0): return False #otherwise, n is prime number. return True # Driver codeN = 100;#check for every number from 1 to Nfor i in range(1,N+1): #check if current number is prime if(isPrime(i)): print(i,end=" ")
// C# program to display// Prime numbers till Nusing System; class GFG{ //function to check if a given number is prime static bool isPrime(int n){ //since 0 and 1 is not prime return false. if(n==1||n==0)return false; //Run a loop from 2 to n/2. for(int i=2; i<=n/2; i++){ // if the number is divisible by i, then n is not a prime number. if(n%i==0)return false; } //otherwise, n is prime number. return true;} // Driver codepublic static void Main (String[] args){ int N = 100; //check for every number from 1 to N for(int i=1; i<=N; i++){ //check if current number is prime if(isPrime(i)) { Console.Write(i + " "); } } }} // This code is contributed by Rajput-Ji
<script>// Javascript program to display Prime numbers till N // function to check if a given number is primefunction isPrime(n){ // since 0 and 1 is not prime return false. if(n == 1 || n == 0) return false; // Run a loop from 2 to n/2. for(let i = 2; i <= n / 2; i++) { // if the number is divisible by i, then n is not a prime number. if(n % i == 0) return false; } // otherwise, n is prime number. return true;} // Driver codelet N = 100; // check for every number from 1 to Nfor(let i = 1; i <= N; i++){ // check if current number is prime if(isPrime(i)) { document.write(i + " "); }} // This code is contributed by shubham348.</script>
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
Time Complexity: O(N^2), Space Complexity: O(1)
Approach 3: If a number ‘n’ is not divided by any number less than or equals to the square root of n then, it will not be divided by any other number greater than the square root of n. So, we only need to check up to the square root of n.
C++
Java
Python3
C#
Javascript
// C++ program to display Prime numbers till N#include <bits/stdc++.h>using namespace std; //function to check if a given number is primebool isPrime(int n){ //since 0 and 1 is not prime return false. if(n==1||n==0)return false; //Run a loop from 2 to square root of n. for(int i=2; i*i<=n; i++){ // if the number is divisible by i, then n is not a prime number. if(n%i==0)return false; } //otherwise, n is prime number. return true;} // Driver codeint main(){ int N = 100; //check for every number from 1 to N for(int i=1; i<=N; i++){ //check if current number is prime if(isPrime(i)) { cout << i << " "; } } return 0;}
// Java program to display// Prime numbers till Nclass GFG{ //function to check if a given number is prime static boolean isPrime(int n){ //since 0 and 1 is not prime return false. if(n==1||n==0)return false; //Run a loop from 2 to square root of n for(int i=2; i*i<=n; i++){ // if the number is divisible by i, then n is not a prime number. if(n%i==0)return false; } //otherwise, n is prime number. return true;} // Driver codepublic static void main (String[] args){ int N = 100; //check for every number from 1 to N for(int i=1; i<=N; i++){ //check if current number is prime if(isPrime(i)) { System.out.print(i + " "); } } }}
# Python3 program to display Prime numbers till N #function to check if a given number is primedef isPrime(n): #since 0 and 1 is not prime return false. if(n==1 or n==0): return False #Run a loop from 2 to square root of n. for i in range(2,int(n**(1/2))+1): #if the number is divisible by i, then n is not a prime number. if(n%i==0): return False #otherwise, n is prime number. return True # Driver codeN = 100;#check for every number from 1 to Nfor i in range(1,N+1): #check if current number is prime if(isPrime(i)): print(i,end=" ")
// C# program to display// Prime numbers till Nusing System; class GFG{ //function to check if a given number is prime static bool isPrime(int n){ //since 0 and 1 is not prime return false. if(n==1||n==0)return false; //Run a loop from 2 to square root of n. for(int i=2; i*i<=n; i++){ // if the number is divisible by i, then n is not a prime number. if(n%i==0)return false; } //otherwise, n is prime number. return true;} // Driver codepublic static void Main (String[] args){ int N = 100; //check for every number from 1 to N for(int i=1; i<=N; i++){ //check if current number is prime if(isPrime(i)) { Console.Write(i + " "); } } }} // This code is contributed by Rajput-Ji
<script>// JavaScript program to display Prime numbers till N // function to check if a given number is primeconst isPrime = (n) => { // since 0 and 1 is not prime return false. if(n === 1||n === 0)return false; // Run a loop from 2 to square root of n. for(let i = 2; i <= Math.floor(Math.sqrt(n)); i++) { // if the number is divisible by i, then n is not a prime number. if(n % i == 0)return false; } // otherwise, n is prime number. return true; } // Driver code let N = 100; // check for every number from 1 to N for(let i=1; i<=N; i++) { // check if current number is prime if(isPrime(i)) { document.write(i); } } // This code is contributed by shinjanpatra </script>
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
Time Complexity: O(N^(3/2)), Space Complexity: O(1)
You can further optimize the time complexity to O(n*log(log(n))). Check Sieve of Eratosthenes.
ankthon
Rajput-Ji
vishnusreddy
_saurabh_jaiswal
gabaa406
gsingh6122016
ukasp
singhdushyant260
shinjanpatra
subham348
Prime Number
Mathematical
Mathematical
Prime Number
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Modulo Operator (%) in C/C++ with Examples
Print all possible combinations of r elements in a given array of size n
Operators in C / C++
Program for factorial of a number
The Knight's tour problem | Backtracking-1
Find minimum number of coins that make a given value
Program to find sum of elements in a given array
Euclidean algorithms (Basic and Extended)
Minimum number of jumps to reach end
How to swap two numbers without using a temporary variable?
|
[
{
"code": null,
"e": 26327,
"s": 26299,
"text": "\n07 Mar, 2022"
},
{
"code": null,
"e": 26407,
"s": 26327,
"text": "Given a number N, the task is to print the prime numbers from 1 to N.Examples: "
},
{
"code": null,
"e": 26471,
"s": 26407,
"text": "Input: N = 10\nOutput: 2, 3, 5, 7\n\nInput: N = 5\nOutput: 2, 3, 5 "
},
{
"code": null,
"e": 26484,
"s": 26471,
"text": "Algorithm: "
},
{
"code": null,
"e": 26519,
"s": 26484,
"text": "First, take the number N as input."
},
{
"code": null,
"e": 26574,
"s": 26519,
"text": "Then use a for loop to iterate the numbers from 1 to N"
},
{
"code": null,
"e": 26658,
"s": 26574,
"text": "Then check for each number to be a prime number. If it is a prime number, print it."
},
{
"code": null,
"e": 26872,
"s": 26658,
"text": "Approach 1: Now, according to formal definition, a number ‘n’ is prime if it is not divisible by any number other than 1 and n. In other words a number is prime if it is not divisible by any number from 2 to n-1."
},
{
"code": null,
"e": 26925,
"s": 26872,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26929,
"s": 26925,
"text": "C++"
},
{
"code": null,
"e": 26934,
"s": 26929,
"text": "Java"
},
{
"code": null,
"e": 26942,
"s": 26934,
"text": "Python3"
},
{
"code": null,
"e": 26945,
"s": 26942,
"text": "C#"
},
{
"code": null,
"e": 26956,
"s": 26945,
"text": "Javascript"
},
{
"code": "// C++ program to display Prime numbers till N#include <bits/stdc++.h>using namespace std; //function to check if a given number is primebool isPrime(int n){ //since 0 and 1 is not prime return false. if(n==1||n==0) return false; //Run a loop from 2 to n-1 for(int i=2; i<n; i++){ // if the number is divisible by i, then n is not a prime number. if(n%i==0) return false; } //otherwise, n is prime number. return true;} // Driver codeint main(){ int N = 100; //check for every number from 1 to N for(int i=1; i<=N; i++){ //check if current number is prime if(isPrime(i)) { cout << i << \" \"; } } return 0;}",
"e": 27672,
"s": 26956,
"text": null
},
{
"code": "// Java program to display Prime numbers till Nclass GFG{ //function to check if a given number is prime static boolean isPrime(int n){ //since 0 and 1 is not prime return false. if(n==1||n==0)return false; //Run a loop from 2 to n-1 for(int i=2; i<n; i++){ // if the number is divisible by i, then n is not a prime number. if(n%i==0)return false; } //otherwise, n is prime number. return true; } // Driver code public static void main (String[] args) { int N = 100; //check for every number from 1 to N for(int i=1; i<=N; i++){ //check if current number is prime if(isPrime(i)) { System.out.print(i + \" \"); } } }}",
"e": 28486,
"s": 27672,
"text": null
},
{
"code": "# Python3 program to display Prime numbers till N #function to check if a given number is primedef isPrime(n): #since 0 and 1 is not prime return false. if(n==1 or n==0): return False #Run a loop from 2 to n-1 for i in range(2,n): #if the number is divisible by i, then n is not a prime number. if(n%i==0): return False #otherwise, n is prime number. return True # Driver codeN = 100;#check for every number from 1 to Nfor i in range(1,N+1): #check if current number is prime if(isPrime(i)): print(i,end=\" \")",
"e": 29028,
"s": 28486,
"text": null
},
{
"code": "// C# program to display Prime numbers till Nusing System; class GFG{ //function to check if a given number is prime static bool isPrime(int n){ //since 0 and 1 is not prime return false. if(n==1||n==0) return false; //Run a loop from 2 to n-1 for(int i=2; i<n; i++) { // if the number is divisible by i, then n is not a prime number. if(n%i==0) return false; } //otherwise, n is prime number. return true; } // Driver code public static void Main (String[] args) { int N = 100; //check for every number from 1 to N for(int i=1; i<=N; i++) { //check if current number is prime if(isPrime(i)) { Console.Write(i + \" \"); } } }} // This code is contributed by Rajput-Ji",
"e": 29866,
"s": 29028,
"text": null
},
{
"code": "<script> // JavaScript program to display Prime numbers till N // function to check if a given number is primefunction isPrime( n){ // since 0 and 1 is not prime return false. if(n == 1 || n == 0) return false; // Run a loop from 2 to n-1 for(var i = 2; i < n; i++) { // if the number is divisible by i, then n is not a prime number. if(n % i == 0) return false; } // otherwise, n is prime number. return true;} // Driver codevar N = 100; // check for every number from 1 to N for(var i = 1; i <= N; i++) { // check if current number is prime if(isPrime(i)) { console.log( i ); }} // This code is contributed by ukasp.</script>",
"e": 30584,
"s": 29866,
"text": null
},
{
"code": null,
"e": 30656,
"s": 30584,
"text": "2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 "
},
{
"code": null,
"e": 30704,
"s": 30656,
"text": "Time Complexity: O(N^2), Space Complexity: O(1)"
},
{
"code": null,
"e": 31027,
"s": 30704,
"text": "Approach 2: For checking if a number is prime or not do we really need to iterate through all the number form 2 to n-1? We already know that a number ‘n’ cannot be divided by any number greater than ‘n/2’. So, according to this logic we only need to iterate through 2 to n/2 since number greater than n/2 cannot divide n."
},
{
"code": null,
"e": 31031,
"s": 31027,
"text": "C++"
},
{
"code": null,
"e": 31036,
"s": 31031,
"text": "Java"
},
{
"code": null,
"e": 31044,
"s": 31036,
"text": "Python3"
},
{
"code": null,
"e": 31047,
"s": 31044,
"text": "C#"
},
{
"code": null,
"e": 31058,
"s": 31047,
"text": "Javascript"
},
{
"code": "// C++ program to display Prime numbers till N#include <bits/stdc++.h>using namespace std; //function to check if a given number is primebool isPrime(int n){ //since 0 and 1 is not prime return false. if(n==1||n==0) return false; //Run a loop from 2 to n/2. for(int i=2; i<=n/2; i++) { // if the number is divisible by i, then n is not a prime number. if(n%i==0) return false; } //otherwise, n is prime number. return true;} // Driver codeint main(){ int N = 100; //check for every number from 1 to N for(int i=1; i<=N; i++){ //check if current number is prime if(isPrime(i)) { cout << i << \" \"; } } return 0;}",
"e": 31759,
"s": 31058,
"text": null
},
{
"code": "// Java program to display// Prime numbers till Nclass GFG{ //function to check if a given number is prime static boolean isPrime(int n){ //since 0 and 1 is not prime return false. if(n==1||n==0) return false; //Run a loop from 2 to n-1 for(int i=2; i<=n/2; i++){ // if the number is divisible by i, then n is not a prime number. if(n%i==0)return false; } //otherwise, n is prime number. return true; } // Driver code public static void main (String[] args) { int N = 100; //check for every number from 1 to N for(int i=1; i<=N; i++){ //check if current number is prime if(isPrime(i)) { System.out.print(i + \" \"); } } }}",
"e": 32560,
"s": 31759,
"text": null
},
{
"code": "# Python3 program to display Prime numbers till N #function to check if a given number is primedef isPrime(n): #since 0 and 1 is not prime return false. if(n==1 or n==0): return False #Run a loop from 2 to n/2 for i in range(2,(n//2)+1): #if the number is divisible by i, then n is not a prime number. if(n%i==0): return False #otherwise, n is prime number. return True # Driver codeN = 100;#check for every number from 1 to Nfor i in range(1,N+1): #check if current number is prime if(isPrime(i)): print(i,end=\" \")",
"e": 33109,
"s": 32560,
"text": null
},
{
"code": "// C# program to display// Prime numbers till Nusing System; class GFG{ //function to check if a given number is prime static bool isPrime(int n){ //since 0 and 1 is not prime return false. if(n==1||n==0)return false; //Run a loop from 2 to n/2. for(int i=2; i<=n/2; i++){ // if the number is divisible by i, then n is not a prime number. if(n%i==0)return false; } //otherwise, n is prime number. return true;} // Driver codepublic static void Main (String[] args){ int N = 100; //check for every number from 1 to N for(int i=1; i<=N; i++){ //check if current number is prime if(isPrime(i)) { Console.Write(i + \" \"); } } }} // This code is contributed by Rajput-Ji",
"e": 33864,
"s": 33109,
"text": null
},
{
"code": "<script>// Javascript program to display Prime numbers till N // function to check if a given number is primefunction isPrime(n){ // since 0 and 1 is not prime return false. if(n == 1 || n == 0) return false; // Run a loop from 2 to n/2. for(let i = 2; i <= n / 2; i++) { // if the number is divisible by i, then n is not a prime number. if(n % i == 0) return false; } // otherwise, n is prime number. return true;} // Driver codelet N = 100; // check for every number from 1 to Nfor(let i = 1; i <= N; i++){ // check if current number is prime if(isPrime(i)) { document.write(i + \" \"); }} // This code is contributed by shubham348.</script>",
"e": 34575,
"s": 33864,
"text": null
},
{
"code": null,
"e": 34647,
"s": 34575,
"text": "2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 "
},
{
"code": null,
"e": 34695,
"s": 34647,
"text": "Time Complexity: O(N^2), Space Complexity: O(1)"
},
{
"code": null,
"e": 34934,
"s": 34695,
"text": "Approach 3: If a number ‘n’ is not divided by any number less than or equals to the square root of n then, it will not be divided by any other number greater than the square root of n. So, we only need to check up to the square root of n."
},
{
"code": null,
"e": 34938,
"s": 34934,
"text": "C++"
},
{
"code": null,
"e": 34943,
"s": 34938,
"text": "Java"
},
{
"code": null,
"e": 34951,
"s": 34943,
"text": "Python3"
},
{
"code": null,
"e": 34954,
"s": 34951,
"text": "C#"
},
{
"code": null,
"e": 34965,
"s": 34954,
"text": "Javascript"
},
{
"code": "// C++ program to display Prime numbers till N#include <bits/stdc++.h>using namespace std; //function to check if a given number is primebool isPrime(int n){ //since 0 and 1 is not prime return false. if(n==1||n==0)return false; //Run a loop from 2 to square root of n. for(int i=2; i*i<=n; i++){ // if the number is divisible by i, then n is not a prime number. if(n%i==0)return false; } //otherwise, n is prime number. return true;} // Driver codeint main(){ int N = 100; //check for every number from 1 to N for(int i=1; i<=N; i++){ //check if current number is prime if(isPrime(i)) { cout << i << \" \"; } } return 0;}",
"e": 35644,
"s": 34965,
"text": null
},
{
"code": "// Java program to display// Prime numbers till Nclass GFG{ //function to check if a given number is prime static boolean isPrime(int n){ //since 0 and 1 is not prime return false. if(n==1||n==0)return false; //Run a loop from 2 to square root of n for(int i=2; i*i<=n; i++){ // if the number is divisible by i, then n is not a prime number. if(n%i==0)return false; } //otherwise, n is prime number. return true;} // Driver codepublic static void main (String[] args){ int N = 100; //check for every number from 1 to N for(int i=1; i<=N; i++){ //check if current number is prime if(isPrime(i)) { System.out.print(i + \" \"); } } }}",
"e": 36340,
"s": 35644,
"text": null
},
{
"code": "# Python3 program to display Prime numbers till N #function to check if a given number is primedef isPrime(n): #since 0 and 1 is not prime return false. if(n==1 or n==0): return False #Run a loop from 2 to square root of n. for i in range(2,int(n**(1/2))+1): #if the number is divisible by i, then n is not a prime number. if(n%i==0): return False #otherwise, n is prime number. return True # Driver codeN = 100;#check for every number from 1 to Nfor i in range(1,N+1): #check if current number is prime if(isPrime(i)): print(i,end=\" \")",
"e": 36910,
"s": 36340,
"text": null
},
{
"code": "// C# program to display// Prime numbers till Nusing System; class GFG{ //function to check if a given number is prime static bool isPrime(int n){ //since 0 and 1 is not prime return false. if(n==1||n==0)return false; //Run a loop from 2 to square root of n. for(int i=2; i*i<=n; i++){ // if the number is divisible by i, then n is not a prime number. if(n%i==0)return false; } //otherwise, n is prime number. return true;} // Driver codepublic static void Main (String[] args){ int N = 100; //check for every number from 1 to N for(int i=1; i<=N; i++){ //check if current number is prime if(isPrime(i)) { Console.Write(i + \" \"); } } }} // This code is contributed by Rajput-Ji",
"e": 37678,
"s": 36910,
"text": null
},
{
"code": "<script>// JavaScript program to display Prime numbers till N // function to check if a given number is primeconst isPrime = (n) => { // since 0 and 1 is not prime return false. if(n === 1||n === 0)return false; // Run a loop from 2 to square root of n. for(let i = 2; i <= Math.floor(Math.sqrt(n)); i++) { // if the number is divisible by i, then n is not a prime number. if(n % i == 0)return false; } // otherwise, n is prime number. return true; } // Driver code let N = 100; // check for every number from 1 to N for(let i=1; i<=N; i++) { // check if current number is prime if(isPrime(i)) { document.write(i); } } // This code is contributed by shinjanpatra </script>",
"e": 38448,
"s": 37678,
"text": null
},
{
"code": null,
"e": 38520,
"s": 38448,
"text": "2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 "
},
{
"code": null,
"e": 38572,
"s": 38520,
"text": "Time Complexity: O(N^(3/2)), Space Complexity: O(1)"
},
{
"code": null,
"e": 38667,
"s": 38572,
"text": "You can further optimize the time complexity to O(n*log(log(n))). Check Sieve of Eratosthenes."
},
{
"code": null,
"e": 38675,
"s": 38667,
"text": "ankthon"
},
{
"code": null,
"e": 38685,
"s": 38675,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 38698,
"s": 38685,
"text": "vishnusreddy"
},
{
"code": null,
"e": 38715,
"s": 38698,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 38724,
"s": 38715,
"text": "gabaa406"
},
{
"code": null,
"e": 38738,
"s": 38724,
"text": "gsingh6122016"
},
{
"code": null,
"e": 38744,
"s": 38738,
"text": "ukasp"
},
{
"code": null,
"e": 38761,
"s": 38744,
"text": "singhdushyant260"
},
{
"code": null,
"e": 38774,
"s": 38761,
"text": "shinjanpatra"
},
{
"code": null,
"e": 38784,
"s": 38774,
"text": "subham348"
},
{
"code": null,
"e": 38797,
"s": 38784,
"text": "Prime Number"
},
{
"code": null,
"e": 38810,
"s": 38797,
"text": "Mathematical"
},
{
"code": null,
"e": 38823,
"s": 38810,
"text": "Mathematical"
},
{
"code": null,
"e": 38836,
"s": 38823,
"text": "Prime Number"
},
{
"code": null,
"e": 38934,
"s": 38836,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 38977,
"s": 38934,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 39050,
"s": 38977,
"text": "Print all possible combinations of r elements in a given array of size n"
},
{
"code": null,
"e": 39071,
"s": 39050,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 39105,
"s": 39071,
"text": "Program for factorial of a number"
},
{
"code": null,
"e": 39148,
"s": 39105,
"text": "The Knight's tour problem | Backtracking-1"
},
{
"code": null,
"e": 39201,
"s": 39148,
"text": "Find minimum number of coins that make a given value"
},
{
"code": null,
"e": 39250,
"s": 39201,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 39292,
"s": 39250,
"text": "Euclidean algorithms (Basic and Extended)"
},
{
"code": null,
"e": 39329,
"s": 39292,
"text": "Minimum number of jumps to reach end"
}
] |
Append row to CSV using R - GeeksforGeeks
|
28 Apr, 2021
In this article, we will see how to append rows to a CSV file using R Programming Language.
By default, the write.csv() function overwrites entire file content. In order to append the data to a CSV File, use the write.table() method instead and set the parameter, append = TRUE. The write.table method prints its required argument x, upon conversion of the .csv file into the data frame to a file or connection.
Syntax:
write.table(x, file = “”, append = FALSE, quote = TRUE, sep = ” “, row.names = TRUE, col.names = TRUE)
Parameters:
x : The row data in the data frame object
file : The file to append row to
sep : The field separator string, that is within each row of x values are separated by this separator.
In case the file is empty, the contents are written on to the .csv file upon creation within the same directory. The following code illustrates the applicability of write.table() method on an empty .csv file.
Example
R
# defining the data for the csv file # data is organised into 4 columnsdata = data.frame(ID = 1:4, Name = c("A","B","C","D"), Post=c("Peon","SDE","Manager","SDE"), Age = c(23,39,28,39)) # write data to a sample.csv filewrite.table(data, file = "sample.csv")
Output
The contents are written onto the empty sample.csv file
The following snippet shows how to append a row to the CSV file already composed of a few rows. The changes are made to the specified CSV file, and upon each operation, one-row count is incremented.
Example:
R
# defining a row row <- data.frame('1', 'A', 'Manager', '24') # sample csv namecsv_fname = "sample.csv" # writing row in the csv filewrite.table(row, file = csv_fname, sep = ",", append = TRUE, quote = FALSE, col.names = FALSE, row.names = FALSE)
Output
“sample.csv” : After the execution of Python script
Picked
R-CSV
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to import an Excel File into R ?
How to filter R DataFrame by values in a column?
Time Series Analysis in R
R - if statement
Logistic Regression in R Programming
|
[
{
"code": null,
"e": 26487,
"s": 26459,
"text": "\n28 Apr, 2021"
},
{
"code": null,
"e": 26580,
"s": 26487,
"text": "In this article, we will see how to append rows to a CSV file using R Programming Language. "
},
{
"code": null,
"e": 26901,
"s": 26580,
"text": "By default, the write.csv() function overwrites entire file content. In order to append the data to a CSV File, use the write.table() method instead and set the parameter, append = TRUE. The write.table method prints its required argument x, upon conversion of the .csv file into the data frame to a file or connection. "
},
{
"code": null,
"e": 26909,
"s": 26901,
"text": "Syntax:"
},
{
"code": null,
"e": 27012,
"s": 26909,
"text": "write.table(x, file = “”, append = FALSE, quote = TRUE, sep = ” “, row.names = TRUE, col.names = TRUE)"
},
{
"code": null,
"e": 27024,
"s": 27012,
"text": "Parameters:"
},
{
"code": null,
"e": 27066,
"s": 27024,
"text": "x : The row data in the data frame object"
},
{
"code": null,
"e": 27099,
"s": 27066,
"text": "file : The file to append row to"
},
{
"code": null,
"e": 27202,
"s": 27099,
"text": "sep : The field separator string, that is within each row of x values are separated by this separator."
},
{
"code": null,
"e": 27412,
"s": 27202,
"text": "In case the file is empty, the contents are written on to the .csv file upon creation within the same directory. The following code illustrates the applicability of write.table() method on an empty .csv file. "
},
{
"code": null,
"e": 27420,
"s": 27412,
"text": "Example"
},
{
"code": null,
"e": 27422,
"s": 27420,
"text": "R"
},
{
"code": "# defining the data for the csv file # data is organised into 4 columnsdata = data.frame(ID = 1:4, Name = c(\"A\",\"B\",\"C\",\"D\"), Post=c(\"Peon\",\"SDE\",\"Manager\",\"SDE\"), Age = c(23,39,28,39)) # write data to a sample.csv filewrite.table(data, file = \"sample.csv\") ",
"e": 27717,
"s": 27422,
"text": null
},
{
"code": null,
"e": 27724,
"s": 27717,
"text": "Output"
},
{
"code": null,
"e": 27780,
"s": 27724,
"text": "The contents are written onto the empty sample.csv file"
},
{
"code": null,
"e": 27980,
"s": 27780,
"text": "The following snippet shows how to append a row to the CSV file already composed of a few rows. The changes are made to the specified CSV file, and upon each operation, one-row count is incremented. "
},
{
"code": null,
"e": 27989,
"s": 27980,
"text": "Example:"
},
{
"code": null,
"e": 27991,
"s": 27989,
"text": "R"
},
{
"code": "# defining a row row <- data.frame('1', 'A', 'Manager', '24') # sample csv namecsv_fname = \"sample.csv\" # writing row in the csv filewrite.table(row, file = csv_fname, sep = \",\", append = TRUE, quote = FALSE, col.names = FALSE, row.names = FALSE)",
"e": 28262,
"s": 27991,
"text": null
},
{
"code": null,
"e": 28269,
"s": 28262,
"text": "Output"
},
{
"code": null,
"e": 28321,
"s": 28269,
"text": "“sample.csv” : After the execution of Python script"
},
{
"code": null,
"e": 28328,
"s": 28321,
"text": "Picked"
},
{
"code": null,
"e": 28334,
"s": 28328,
"text": "R-CSV"
},
{
"code": null,
"e": 28345,
"s": 28334,
"text": "R Language"
},
{
"code": null,
"e": 28443,
"s": 28345,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28495,
"s": 28443,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 28530,
"s": 28495,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 28568,
"s": 28530,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 28626,
"s": 28568,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 28669,
"s": 28626,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 28706,
"s": 28669,
"text": "How to import an Excel File into R ?"
},
{
"code": null,
"e": 28755,
"s": 28706,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 28781,
"s": 28755,
"text": "Time Series Analysis in R"
},
{
"code": null,
"e": 28798,
"s": 28781,
"text": "R - if statement"
}
] |
Hangman Game in Python - GeeksforGeeks
|
08 Jun, 2018
Hangman is a word game in which computer will randomly select a word from the dictionary and player has to guess it correctly in given number of turns. The word to be guessed is represented by row of stars. If the guessed letter is present is word, script will automatically be placed to correct places.
Rules to guess the word :
Input single letter in one turn.Don’t use repeated letters.Turns will be decremented after every guess.
Input single letter in one turn.
Don’t use repeated letters.
Turns will be decremented after every guess.
This is the text file used inside the code words.txt, which contains 50,000 English words.
Module needed :
import random
Below is the implementation :
# Python program to implement Hangman game # Importing random moduleimport random # Function to randomly select# a word from dictionarydef get_word(): # Path to the text file with open('/Users/Admin/Desktop/words.txt', 'r') as f: # Reads each word after splitting words1 = f.read().splitlines() # Returns any random word return random.choice(words1) myword = get_word() # Function prints row of# stars in place of wordsfor i in myword: print("*", end = " ") # Calculating length of wordl = len(myword)print("\nWord has %d letters" %l) # Check if entered letter is correctdef check(myword, your_word, guess1): status = '' matches = 0 for letter in myword: if letter in your_word: status += letter else: status += '*' if letter == guess1: matches += 1 if matches > 1: print(matches, guess1) elif matches == 1: print(guess1) return status # Main Game functiondef game(): guess = 0 guessed = False your_word = [] turns = len(myword) + 1 turns1 = turns print("Total turns: ", turns) while guess < turns1: guess1 = input("Enter your guess: ") # Decrementing turn # after every guess turns -= 1 # Print turns left print("Turns left", turns) # If letter is already guessed if guess1 in your_word: print("You already guessed") elif len(guess1) == 1: # Appending the letters # on their place your_word.append(guess1) result = check(myword, your_word, guess1) if result == myword: guessed = True print("You won " + name) print(myword) else: print(result) else: print("Invalid entry") guess += 1 if guess == turns1: print("Word is:") print(myword) # Driver Codegame()
Output :
* * * * *
Word has 5 letters
Total turns: 11
Enter your guess: a
Turns left 10
**********
Enter your guess: i
Turns left 9
i
**i**i****
Enter your guess: s
Turns left 8
s
**i**i**ss
Enter your guess: r
Turns left 7
**i**i**ss
Enter your guess: h
Turns left 6
**i**i**ss
Enter your guess: e
Turns left 5
e
**i**i*ess
Enter your guess: o
Turns left 4
**i**i*ess
Enter your guess: u
Turns left 3
u
*ui**i*ess
Enter your guess: t
Turns left 2
t
*ui*ti*ess
Enter your guess: n
Turns left 1
n
*ui*tiness
Enter your guess: l
Turns left 0
l
*uiltiness
Word is:
guiltiness
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
|
[
{
"code": null,
"e": 25969,
"s": 25941,
"text": "\n08 Jun, 2018"
},
{
"code": null,
"e": 26273,
"s": 25969,
"text": "Hangman is a word game in which computer will randomly select a word from the dictionary and player has to guess it correctly in given number of turns. The word to be guessed is represented by row of stars. If the guessed letter is present is word, script will automatically be placed to correct places."
},
{
"code": null,
"e": 26299,
"s": 26273,
"text": "Rules to guess the word :"
},
{
"code": null,
"e": 26403,
"s": 26299,
"text": "Input single letter in one turn.Don’t use repeated letters.Turns will be decremented after every guess."
},
{
"code": null,
"e": 26436,
"s": 26403,
"text": "Input single letter in one turn."
},
{
"code": null,
"e": 26464,
"s": 26436,
"text": "Don’t use repeated letters."
},
{
"code": null,
"e": 26509,
"s": 26464,
"text": "Turns will be decremented after every guess."
},
{
"code": null,
"e": 26600,
"s": 26509,
"text": "This is the text file used inside the code words.txt, which contains 50,000 English words."
},
{
"code": null,
"e": 26616,
"s": 26600,
"text": "Module needed :"
},
{
"code": null,
"e": 26630,
"s": 26616,
"text": "import random"
},
{
"code": null,
"e": 26660,
"s": 26630,
"text": "Below is the implementation :"
},
{
"code": "# Python program to implement Hangman game # Importing random moduleimport random # Function to randomly select# a word from dictionarydef get_word(): # Path to the text file with open('/Users/Admin/Desktop/words.txt', 'r') as f: # Reads each word after splitting words1 = f.read().splitlines() # Returns any random word return random.choice(words1) myword = get_word() # Function prints row of# stars in place of wordsfor i in myword: print(\"*\", end = \" \") # Calculating length of wordl = len(myword)print(\"\\nWord has %d letters\" %l) # Check if entered letter is correctdef check(myword, your_word, guess1): status = '' matches = 0 for letter in myword: if letter in your_word: status += letter else: status += '*' if letter == guess1: matches += 1 if matches > 1: print(matches, guess1) elif matches == 1: print(guess1) return status # Main Game functiondef game(): guess = 0 guessed = False your_word = [] turns = len(myword) + 1 turns1 = turns print(\"Total turns: \", turns) while guess < turns1: guess1 = input(\"Enter your guess: \") # Decrementing turn # after every guess turns -= 1 # Print turns left print(\"Turns left\", turns) # If letter is already guessed if guess1 in your_word: print(\"You already guessed\") elif len(guess1) == 1: # Appending the letters # on their place your_word.append(guess1) result = check(myword, your_word, guess1) if result == myword: guessed = True print(\"You won \" + name) print(myword) else: print(result) else: print(\"Invalid entry\") guess += 1 if guess == turns1: print(\"Word is:\") print(myword) # Driver Codegame()",
"e": 28732,
"s": 26660,
"text": null
},
{
"code": null,
"e": 28741,
"s": 28732,
"text": "Output :"
},
{
"code": null,
"e": 29320,
"s": 28741,
"text": "* * * * * \nWord has 5 letters\nTotal turns: 11\n\nEnter your guess: a\nTurns left 10\n**********\n\nEnter your guess: i\nTurns left 9\ni\n**i**i****\n\nEnter your guess: s\nTurns left 8\ns\n**i**i**ss\n\nEnter your guess: r\nTurns left 7\n**i**i**ss\n\nEnter your guess: h\nTurns left 6\n**i**i**ss\n\nEnter your guess: e\nTurns left 5\ne\n**i**i*ess\n\nEnter your guess: o\nTurns left 4\n**i**i*ess\n\nEnter your guess: u\nTurns left 3\nu\n*ui**i*ess\n\nEnter your guess: t\nTurns left 2\nt\n*ui*ti*ess\n\nEnter your guess: n\nTurns left 1\nn\n*ui*tiness\n\nEnter your guess: l\nTurns left 0\nl\n*uiltiness\n\nWord is:\nguiltiness\n"
},
{
"code": null,
"e": 29327,
"s": 29320,
"text": "Python"
},
{
"code": null,
"e": 29343,
"s": 29327,
"text": "Python Programs"
},
{
"code": null,
"e": 29441,
"s": 29343,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29459,
"s": 29441,
"text": "Python Dictionary"
},
{
"code": null,
"e": 29491,
"s": 29459,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29513,
"s": 29491,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 29555,
"s": 29513,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 29581,
"s": 29555,
"text": "Python String | replace()"
},
{
"code": null,
"e": 29603,
"s": 29581,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 29642,
"s": 29603,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 29688,
"s": 29642,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 29726,
"s": 29688,
"text": "Python | Convert a list to dictionary"
}
] |
Maximum number of teams that can be formed with given persons - GeeksforGeeks
|
31 Mar, 2021
Given two integers N and M which denote the number of persons of Type1 and Type2 respectively. The task is to find the maximum number of teams that can be formed with these two types of persons. A team can contain either 2 persons of Type1 and 1 person of Type2 or 1 person of Type1 and 2 persons of Type2.Examples:
Input: N = 2, M = 6 Output: 2 (Type1, Type2, Type2) and (Type1, Type2, Type2) are the two possible teams.Input: N = 4, M = 5 Output: 3
Approach: A greedy approach is to choose 2 persons from the group which has more members and 1 person from the group with lesser members and update the count of persons in each of the group accordingly. Termination condition will be when no more teams can be formed.Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function that returns true if it possible// to form a team with the given n and mbool canFormTeam(int n, int m){ // 1 person of Type1 and 2 persons of Type2 // can be chosen if (n >= 1 && m >= 2) return true; // 1 person of Type2 and 2 persons of Type1 // can be chosen if (m >= 1 && n >= 2) return true; // Cannot from a team return false;} // Function to return the maximum number of teams// that can be formedint maxTeams(int n, int m){ // To store the required count of teams formed int count = 0; while (canFormTeam(n, m)) { if (n > m) { // Choose 2 persons of Type1 n -= 2; // And 1 person of Type2 m -= 1; } else { // Choose 2 persons of Type2 m -= 2; // And 1 person of Type1 n -= 1; } // Another team has been formed count++; } return count;} // Driver codeint main(){ int n = 4, m = 5; cout << maxTeams(n, m); return 0;}
// Java implementation of the approachclass GFG{ // Function that returns true // if it possible to form a // team with the given n and m static boolean canFormTeam(int n, int m) { // 1 person of Type1 and 2 persons // of Type2 can be chosen if (n >= 1 && m >= 2) return true; // 1 person of Type2 and 2 persons // of Type1 can be chosen if (m >= 1 && n >= 2) return true; // Cannot from a team return false; } // Function to return the maximum // number of teams that can be formed static int maxTeams(int n, int m) { // To store the required count // of teams formed int count = 0; while (canFormTeam(n, m)) { if (n > m) { // Choose 2 persons of Type1 n -= 2; // And 1 person of Type2 m -= 1; } else { // Choose 2 persons of Type2 m -= 2; // And 1 person of Type1 n -= 1; } // Another team has been formed count++; } return count; } // Driver code public static void main(String args[]) { int n = 4, m = 5; System.out.println(maxTeams(n, m)); }} // This code is contributed by Ryuga
# Python 3 implementation of the approach # Function that returns true if it possible# to form a team with the given n and mdef canFormTeam(n, m): # 1 person of Type1 and 2 persons of Type2 # can be chosen if (n >= 1 and m >= 2): return True # 1 person of Type2 and 2 persons of Type1 # can be chosen if (m >= 1 and n >= 2): return True # Cannot from a team return False # Function to return the maximum number of teams# that can be formeddef maxTeams(n, m): # To store the required count of teams formed count = 0 while (canFormTeam(n, m)): if (n > m): # Choose 2 persons of Type1 n -= 2 # And 1 person of Type2 m -= 1 else: # Choose 2 persons of Type2 m -= 2 # And 1 person of Type1 n -= 1 # Another team has been formed count += 1 return count # Driver codeif __name__ == '__main__': n = 4 m = 5 print(maxTeams(n, m)) # This code is contributed by# Surendra_Gangwar
// C# implementation of the approachusing System; class GFG{ // Function that returns true if it possible// to form a team with the given n and mstatic bool canFormTeam(int n, int m){ // 1 person of Type1 and 2 persons // of Type2 can be chosen if (n >= 1 && m >= 2) return true; // 1 person of Type2 and 2 persons // of Type1 can be chosen if (m >= 1 && n >= 2) return true; // Cannot from a team return false;} // Function to return the maximum// number of teams that can be formedstatic int maxTeams(int n, int m){ // To store the required count // of teams formed int count = 0; while (canFormTeam(n, m)) { if (n > m) { // Choose 2 persons of Type1 n -= 2; // And 1 person of Type2 m -= 1; } else { // Choose 2 persons of Type2 m -= 2; // And 1 person of Type1 n -= 1; } // Another team has been formed count++; } return count;} // Driver codepublic static void Main(){ int n = 4, m = 5; Console.WriteLine(maxTeams(n, m));}} // This code is contributed by// tufan_gupta2000
<?php// PHP implementation of the approach // Function that returns true if it possible// to form a team with the given n and mfunction canFormTeam($n, $m){ // 1 person of Type1 and 2 persons // of Type2 can be chosen if ($n >= 1 && $m >= 2) return true; // 1 person of Type2 and 2 persons // of Type1 can be chosen if ($m >= 1 && $n >= 2) return true; // Cannot from a team return false;} // Function to return the maximum number// of teams that can be formedfunction maxTeams($n, $m){ // To store the required count // of teams formed $count = 0; while (canFormTeam($n, $m)) { if ($n > $m) { // Choose 2 persons of Type1 $n -= 2; // And 1 person of Type2 $m -= 1; } else { // Choose 2 persons of Type2 $m -= 2; // And 1 person of Type1 $n -= 1; } // Another team has been formed $count++; } return $count;} // Driver code$n = 4;$m = 5;echo maxTeams($n, $m); // This code is contributed by mits?>
<script>// javascript implementation of the approach // Function that returns true // if it possible to form a // team with the given n and m function canFormTeam(n, m) { // 1 person of Type1 and 2 persons // of Type2 can be chosen if (n >= 1 && m >= 2) return true; // 1 person of Type2 and 2 persons // of Type1 can be chosen if (m >= 1 && n >= 2) return true; // Cannot from a team return false; } // Function to return the maximum // number of teams that can be formed function maxTeams(n , m) { // To store the required count // of teams formed var count = 0; while (canFormTeam(n, m)) { if (n > m) { // Choose 2 persons of Type1 n -= 2; // And 1 person of Type2 m -= 1; } else { // Choose 2 persons of Type2 m -= 2; // And 1 person of Type1 n -= 1; } // Another team has been formed count++; } return count; } // Driver code var n = 4, m = 5; document.write(maxTeams(n, m)); // This code is contributed by todaysgaurav</script>
3
tufan_gupta2000
ankthon
SURENDRA_GANGWAR
Mithun Kumar
todaysgaurav
Competitive Programming
Greedy
Mathematical
Greedy
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Prefix Sum Array - Implementation and Applications in Competitive Programming
Ordered Set and GNU C++ PBDS
Modulo 10^9+7 (1000000007)
Bits manipulation (Important tactics)
7 Best Coding Challenge Websites in 2020
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
Program for array rotation
Write a program to print all permutations of a given string
|
[
{
"code": null,
"e": 26659,
"s": 26631,
"text": "\n31 Mar, 2021"
},
{
"code": null,
"e": 26977,
"s": 26659,
"text": "Given two integers N and M which denote the number of persons of Type1 and Type2 respectively. The task is to find the maximum number of teams that can be formed with these two types of persons. A team can contain either 2 persons of Type1 and 1 person of Type2 or 1 person of Type1 and 2 persons of Type2.Examples: "
},
{
"code": null,
"e": 27114,
"s": 26977,
"text": "Input: N = 2, M = 6 Output: 2 (Type1, Type2, Type2) and (Type1, Type2, Type2) are the two possible teams.Input: N = 4, M = 5 Output: 3 "
},
{
"code": null,
"e": 27435,
"s": 27116,
"text": "Approach: A greedy approach is to choose 2 persons from the group which has more members and 1 person from the group with lesser members and update the count of persons in each of the group accordingly. Termination condition will be when no more teams can be formed.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 27439,
"s": 27435,
"text": "C++"
},
{
"code": null,
"e": 27444,
"s": 27439,
"text": "Java"
},
{
"code": null,
"e": 27452,
"s": 27444,
"text": "Python3"
},
{
"code": null,
"e": 27455,
"s": 27452,
"text": "C#"
},
{
"code": null,
"e": 27459,
"s": 27455,
"text": "PHP"
},
{
"code": null,
"e": 27470,
"s": 27459,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function that returns true if it possible// to form a team with the given n and mbool canFormTeam(int n, int m){ // 1 person of Type1 and 2 persons of Type2 // can be chosen if (n >= 1 && m >= 2) return true; // 1 person of Type2 and 2 persons of Type1 // can be chosen if (m >= 1 && n >= 2) return true; // Cannot from a team return false;} // Function to return the maximum number of teams// that can be formedint maxTeams(int n, int m){ // To store the required count of teams formed int count = 0; while (canFormTeam(n, m)) { if (n > m) { // Choose 2 persons of Type1 n -= 2; // And 1 person of Type2 m -= 1; } else { // Choose 2 persons of Type2 m -= 2; // And 1 person of Type1 n -= 1; } // Another team has been formed count++; } return count;} // Driver codeint main(){ int n = 4, m = 5; cout << maxTeams(n, m); return 0;}",
"e": 28589,
"s": 27470,
"text": null
},
{
"code": "// Java implementation of the approachclass GFG{ // Function that returns true // if it possible to form a // team with the given n and m static boolean canFormTeam(int n, int m) { // 1 person of Type1 and 2 persons // of Type2 can be chosen if (n >= 1 && m >= 2) return true; // 1 person of Type2 and 2 persons // of Type1 can be chosen if (m >= 1 && n >= 2) return true; // Cannot from a team return false; } // Function to return the maximum // number of teams that can be formed static int maxTeams(int n, int m) { // To store the required count // of teams formed int count = 0; while (canFormTeam(n, m)) { if (n > m) { // Choose 2 persons of Type1 n -= 2; // And 1 person of Type2 m -= 1; } else { // Choose 2 persons of Type2 m -= 2; // And 1 person of Type1 n -= 1; } // Another team has been formed count++; } return count; } // Driver code public static void main(String args[]) { int n = 4, m = 5; System.out.println(maxTeams(n, m)); }} // This code is contributed by Ryuga",
"e": 30028,
"s": 28589,
"text": null
},
{
"code": "# Python 3 implementation of the approach # Function that returns true if it possible# to form a team with the given n and mdef canFormTeam(n, m): # 1 person of Type1 and 2 persons of Type2 # can be chosen if (n >= 1 and m >= 2): return True # 1 person of Type2 and 2 persons of Type1 # can be chosen if (m >= 1 and n >= 2): return True # Cannot from a team return False # Function to return the maximum number of teams# that can be formeddef maxTeams(n, m): # To store the required count of teams formed count = 0 while (canFormTeam(n, m)): if (n > m): # Choose 2 persons of Type1 n -= 2 # And 1 person of Type2 m -= 1 else: # Choose 2 persons of Type2 m -= 2 # And 1 person of Type1 n -= 1 # Another team has been formed count += 1 return count # Driver codeif __name__ == '__main__': n = 4 m = 5 print(maxTeams(n, m)) # This code is contributed by# Surendra_Gangwar",
"e": 31087,
"s": 30028,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ // Function that returns true if it possible// to form a team with the given n and mstatic bool canFormTeam(int n, int m){ // 1 person of Type1 and 2 persons // of Type2 can be chosen if (n >= 1 && m >= 2) return true; // 1 person of Type2 and 2 persons // of Type1 can be chosen if (m >= 1 && n >= 2) return true; // Cannot from a team return false;} // Function to return the maximum// number of teams that can be formedstatic int maxTeams(int n, int m){ // To store the required count // of teams formed int count = 0; while (canFormTeam(n, m)) { if (n > m) { // Choose 2 persons of Type1 n -= 2; // And 1 person of Type2 m -= 1; } else { // Choose 2 persons of Type2 m -= 2; // And 1 person of Type1 n -= 1; } // Another team has been formed count++; } return count;} // Driver codepublic static void Main(){ int n = 4, m = 5; Console.WriteLine(maxTeams(n, m));}} // This code is contributed by// tufan_gupta2000",
"e": 32288,
"s": 31087,
"text": null
},
{
"code": "<?php// PHP implementation of the approach // Function that returns true if it possible// to form a team with the given n and mfunction canFormTeam($n, $m){ // 1 person of Type1 and 2 persons // of Type2 can be chosen if ($n >= 1 && $m >= 2) return true; // 1 person of Type2 and 2 persons // of Type1 can be chosen if ($m >= 1 && $n >= 2) return true; // Cannot from a team return false;} // Function to return the maximum number// of teams that can be formedfunction maxTeams($n, $m){ // To store the required count // of teams formed $count = 0; while (canFormTeam($n, $m)) { if ($n > $m) { // Choose 2 persons of Type1 $n -= 2; // And 1 person of Type2 $m -= 1; } else { // Choose 2 persons of Type2 $m -= 2; // And 1 person of Type1 $n -= 1; } // Another team has been formed $count++; } return $count;} // Driver code$n = 4;$m = 5;echo maxTeams($n, $m); // This code is contributed by mits?>",
"e": 33404,
"s": 32288,
"text": null
},
{
"code": "<script>// javascript implementation of the approach // Function that returns true // if it possible to form a // team with the given n and m function canFormTeam(n, m) { // 1 person of Type1 and 2 persons // of Type2 can be chosen if (n >= 1 && m >= 2) return true; // 1 person of Type2 and 2 persons // of Type1 can be chosen if (m >= 1 && n >= 2) return true; // Cannot from a team return false; } // Function to return the maximum // number of teams that can be formed function maxTeams(n , m) { // To store the required count // of teams formed var count = 0; while (canFormTeam(n, m)) { if (n > m) { // Choose 2 persons of Type1 n -= 2; // And 1 person of Type2 m -= 1; } else { // Choose 2 persons of Type2 m -= 2; // And 1 person of Type1 n -= 1; } // Another team has been formed count++; } return count; } // Driver code var n = 4, m = 5; document.write(maxTeams(n, m)); // This code is contributed by todaysgaurav</script>",
"e": 34732,
"s": 33404,
"text": null
},
{
"code": null,
"e": 34734,
"s": 34732,
"text": "3"
},
{
"code": null,
"e": 34752,
"s": 34736,
"text": "tufan_gupta2000"
},
{
"code": null,
"e": 34760,
"s": 34752,
"text": "ankthon"
},
{
"code": null,
"e": 34777,
"s": 34760,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 34790,
"s": 34777,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 34803,
"s": 34790,
"text": "todaysgaurav"
},
{
"code": null,
"e": 34827,
"s": 34803,
"text": "Competitive Programming"
},
{
"code": null,
"e": 34834,
"s": 34827,
"text": "Greedy"
},
{
"code": null,
"e": 34847,
"s": 34834,
"text": "Mathematical"
},
{
"code": null,
"e": 34854,
"s": 34847,
"text": "Greedy"
},
{
"code": null,
"e": 34867,
"s": 34854,
"text": "Mathematical"
},
{
"code": null,
"e": 34965,
"s": 34867,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35043,
"s": 34965,
"text": "Prefix Sum Array - Implementation and Applications in Competitive Programming"
},
{
"code": null,
"e": 35072,
"s": 35043,
"text": "Ordered Set and GNU C++ PBDS"
},
{
"code": null,
"e": 35099,
"s": 35072,
"text": "Modulo 10^9+7 (1000000007)"
},
{
"code": null,
"e": 35137,
"s": 35099,
"text": "Bits manipulation (Important tactics)"
},
{
"code": null,
"e": 35178,
"s": 35137,
"text": "7 Best Coding Challenge Websites in 2020"
},
{
"code": null,
"e": 35229,
"s": 35178,
"text": "Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 35287,
"s": 35229,
"text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2"
},
{
"code": null,
"e": 35338,
"s": 35287,
"text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5"
},
{
"code": null,
"e": 35365,
"s": 35338,
"text": "Program for array rotation"
}
] |
Compiling a C++ program with GCC
|
Here we will see how to compile C++ program using GCC (GNU C Compiler). Let us consider, we want to compile this program.
#include<iostream>
using namespace std;
main() {
cout << "Hello World. This is C++ program" << endl;
}
If this is a C program, we can compile with GCC like below −
gcc test.c
But if we put c++ filename in that area, it may generate some error.
gcc test.cpp
/tmp/ccf1KGDi.o: In function `main':
1325.test.cpp:(.text+0xe): undefined reference to `std::cout'
1325.test.cpp:(.text+0x13): undefined reference to `std::basic_ostream<char, std::char_traits<char> >&
std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*)'
1325.test.cpp:(.text+0x1d): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& std::endl<char,
std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&)'
1325.test.cpp:(.text+0x28): undefined reference to `std::ostream::operator<<(std::ostream& (*)(std::ostream&))'
/tmp/ccf1KGDi.o: In function `__static_initialization_and_destruction_0(int, int)':
1325.test.cpp:(.text+0x58): undefined reference to `std::ios_base::Init::Init()'
1325.test.cpp:(.text+0x6d): undefined reference to `std::ios_base::Init::~Init()'
collect2: error: ld returned 1 exit status
$
This is not compilation error. This is linking error. To add the correct linker, we have to use –lstdc++ option.
gcc test.cpp -lstdc++
$ ./a.out
Hello World. This is C++ program
$
|
[
{
"code": null,
"e": 1184,
"s": 1062,
"text": "Here we will see how to compile C++ program using GCC (GNU C Compiler). Let us consider, we want to compile this program."
},
{
"code": null,
"e": 1290,
"s": 1184,
"text": "#include<iostream>\nusing namespace std;\nmain() {\n cout << \"Hello World. This is C++ program\" << endl;\n}"
},
{
"code": null,
"e": 1351,
"s": 1290,
"text": "If this is a C program, we can compile with GCC like below −"
},
{
"code": null,
"e": 1362,
"s": 1351,
"text": "gcc test.c"
},
{
"code": null,
"e": 1431,
"s": 1362,
"text": "But if we put c++ filename in that area, it may generate some error."
},
{
"code": null,
"e": 1444,
"s": 1431,
"text": "gcc test.cpp"
},
{
"code": null,
"e": 2357,
"s": 1444,
"text": "/tmp/ccf1KGDi.o: In function `main':\n1325.test.cpp:(.text+0xe): undefined reference to `std::cout'\n1325.test.cpp:(.text+0x13): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& \nstd::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*)'\n1325.test.cpp:(.text+0x1d): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& std::endl<char, \nstd::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&)'\n1325.test.cpp:(.text+0x28): undefined reference to `std::ostream::operator<<(std::ostream& (*)(std::ostream&))'\n/tmp/ccf1KGDi.o: In function `__static_initialization_and_destruction_0(int, int)':\n1325.test.cpp:(.text+0x58): undefined reference to `std::ios_base::Init::Init()'\n1325.test.cpp:(.text+0x6d): undefined reference to `std::ios_base::Init::~Init()'\ncollect2: error: ld returned 1 exit status\n$"
},
{
"code": null,
"e": 2470,
"s": 2357,
"text": "This is not compilation error. This is linking error. To add the correct linker, we have to use –lstdc++ option."
},
{
"code": null,
"e": 2492,
"s": 2470,
"text": "gcc test.cpp -lstdc++"
},
{
"code": null,
"e": 2537,
"s": 2492,
"text": "$ ./a.out\nHello World. This is C++ program\n$"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.