title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
Show android notification every five minutes? | This example demonstrate about How to Show android notification every five minutes
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<? xml version = "1.0" encoding = "utf-8" ?>
<RelativeLayout xmlns: android = "http://schemas.android.com/apk/res/android"
xmlns: tools = "http://schemas.android.com/tools"
android :layout_width = "match_parent"
android :layout_height = "match_parent"
android :padding = "16dp"
tools :context = ".MainActivity" >
<Button
android :layout_width = "match_parent"
android :layout_height = "wrap_content"
android :layout_centerInParent = "true"
android :onClick = "closeApp"
android :text = "close App for notification" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity
package app.tutorialspoint.com.notifyme ;
import android.content.Intent ;
import android.os.Bundle ;
import android.support.v7.app.AppCompatActivity ;
import android.view.View ;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate (Bundle savedInstanceState) {
super .onCreate(savedInstanceState) ;
setContentView(R.layout. activity_main ) ;
}
@Override
protected void onStop () {
super .onStop() ;
startService( new Intent( this, NotificationService. class )) ;
}
public void closeApp (View view) {
finish() ;
}
}
Step 4 − Add the following code to src/NotificationService
package app.tutorialspoint.com.notifyme ;
import android.app.NotificationChannel ;
import android.app.NotificationManager ;
import android.app.Service ;
import android.content.Intent ;
import android.os.Handler ;
import android.os.IBinder ;
import android.support.v4.app.NotificationCompat ;
import android.util.Log ;
import java.util.Timer ;
import java.util.TimerTask ;
public class NotificationService extends Service {
public static final String NOTIFICATION_CHANNEL_ID = "10001" ;
private final static String default_notification_channel_id = "default" ;
Timer timer ;
TimerTask timerTask ;
String TAG = "Timers" ;
int Your_X_SECS = 5 ;
@Override
public IBinder onBind (Intent arg0) {
return null;
}
@Override
public int onStartCommand (Intent intent , int flags , int startId) {
Log. e ( TAG , "onStartCommand" ) ;
super .onStartCommand(intent , flags , startId) ;
startTimer() ;
return START_STICKY ;
}
@Override
public void onCreate () {
Log. e ( TAG , "onCreate" ) ;
}
@Override
public void onDestroy () {
Log. e ( TAG , "onDestroy" ) ;
stopTimerTask() ;
super .onDestroy() ;
}
//we are going to use a handler to be able to run in our TimerTask
final Handler handler = new Handler() ;
public void startTimer () {
timer = new Timer() ;
initializeTimerTask() ;
timer .schedule( timerTask , 500000 , Your_X_SECS * 1000 ) ;
}
public void stopTimerTask () {
if ( timer != null ) {
timer .cancel() ;
timer = null;
}
}
public void initializeTimerTask () {
timerTask = new TimerTask() {
public void run () {
handler .post( new Runnable() {
public void run () {
createNotification() ;
}
}) ;
}
} ;
}
private void createNotification () {
NotificationManager mNotificationManager = (NotificationManager)getSystemService( NOTIFICATION_SERVICE ) ;
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext() , default_notification_channel_id ) ;
mBuilder.setContentTitle( "My Notification" ) ;
mBuilder.setContentText( "Notification Listener Service Example" ) ;
mBuilder.setTicker( "Notification Listener Service Example" ) ;
mBuilder.setSmallIcon(R.drawable. ic_launcher_foreground ) ;
mBuilder.setAutoCancel( true ) ;
if (android.os.Build.VERSION. SDK_INT >= android.os.Build.VERSION_CODES. O ) {
int importance = NotificationManager. IMPORTANCE_HIGH ;
NotificationChannel notificationChannel = new NotificationChannel( NOTIFICATION_CHANNEL_ID , "NOTIFICATION_CHANNEL_NAME" , importance) ;
mBuilder.setChannelId( NOTIFICATION_CHANNEL_ID ) ;
assert mNotificationManager != null;
mNotificationManager.createNotificationChannel(notificationChannel) ;
}
assert mNotificationManager != null;
mNotificationManager.notify(( int ) System. currentTimeMillis () , mBuilder.build()) ;
}
}
Step 5 − Add the following code to AndroidManifest.xml
<? xml version = "1.0" encoding = "utf-8" ?>
<manifest xmlns: android = "http://schemas.android.com/apk/res/android"
package = "app.tutorialspoint.com.notifyme" >
<uses-permission android :name = "android.permission.VIBRATE" />
<application
android :allowBackup = "true"
android :icon = "@mipmap/ic_launcher"
android :label = "@string/app_name"
android :roundIcon = "@mipmap/ic_launcher_round"
android :supportsRtl = "true"
android :theme = "@style/AppTheme" >
<activity android :name = ".MainActivity" >
<intent-filter>
<action android :name = "android.intent.action.MAIN" />
<category android :name = "android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android :name = ".NotificationService"
android :label = "@string/app_name" >
<intent-filter>
<action
android :name = "app.tutorialspoint.com.notifyme.NotificationService" />
<category android :name = "android.intent.category.DEFAULT" />
</intent-filter>
</service>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
Click here to download the project code | [
{
"code": null,
"e": 1145,
"s": 1062,
"text": "This example demonstrate about How to Show android notification every five minutes"
},
{
"code": null,
"e": 1274,
"s": 1145,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1339,
"s": 1274,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1923,
"s": 1339,
"text": "<? xml version = \"1.0\" encoding = \"utf-8\" ?>\n<RelativeLayout xmlns: android = \"http://schemas.android.com/apk/res/android\"\n xmlns: tools = \"http://schemas.android.com/tools\"\n android :layout_width = \"match_parent\"\n android :layout_height = \"match_parent\"\n android :padding = \"16dp\"\n tools :context = \".MainActivity\" >\n <Button\n android :layout_width = \"match_parent\"\n android :layout_height = \"wrap_content\"\n android :layout_centerInParent = \"true\"\n android :onClick = \"closeApp\"\n android :text = \"close App for notification\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 1975,
"s": 1923,
"text": "Step 3 − Add the following code to src/MainActivity"
},
{
"code": null,
"e": 2579,
"s": 1975,
"text": "package app.tutorialspoint.com.notifyme ;\nimport android.content.Intent ;\nimport android.os.Bundle ;\nimport android.support.v7.app.AppCompatActivity ;\nimport android.view.View ;\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate (Bundle savedInstanceState) {\n super .onCreate(savedInstanceState) ;\n setContentView(R.layout. activity_main ) ;\n }\n @Override\n protected void onStop () {\n super .onStop() ;\n startService( new Intent( this, NotificationService. class )) ;\n }\n public void closeApp (View view) {\n finish() ;\n }\n}"
},
{
"code": null,
"e": 2638,
"s": 2579,
"text": "Step 4 − Add the following code to src/NotificationService"
},
{
"code": null,
"e": 5748,
"s": 2638,
"text": "package app.tutorialspoint.com.notifyme ;\nimport android.app.NotificationChannel ;\nimport android.app.NotificationManager ;\nimport android.app.Service ;\nimport android.content.Intent ;\nimport android.os.Handler ;\nimport android.os.IBinder ;\nimport android.support.v4.app.NotificationCompat ;\nimport android.util.Log ;\nimport java.util.Timer ;\nimport java.util.TimerTask ;\npublic class NotificationService extends Service {\n public static final String NOTIFICATION_CHANNEL_ID = \"10001\" ;\n private final static String default_notification_channel_id = \"default\" ;\n Timer timer ;\n TimerTask timerTask ;\n String TAG = \"Timers\" ;\n int Your_X_SECS = 5 ;\n @Override\n public IBinder onBind (Intent arg0) {\n return null;\n }\n @Override\n public int onStartCommand (Intent intent , int flags , int startId) {\n Log. e ( TAG , \"onStartCommand\" ) ;\n super .onStartCommand(intent , flags , startId) ;\n startTimer() ;\n return START_STICKY ;\n }\n @Override\n public void onCreate () {\n Log. e ( TAG , \"onCreate\" ) ;\n }\n @Override\n public void onDestroy () {\n Log. e ( TAG , \"onDestroy\" ) ;\n stopTimerTask() ;\n super .onDestroy() ;\n }\n //we are going to use a handler to be able to run in our TimerTask\n final Handler handler = new Handler() ;\n public void startTimer () {\n timer = new Timer() ;\n initializeTimerTask() ;\n timer .schedule( timerTask , 500000 , Your_X_SECS * 1000 ) ;\n }\n public void stopTimerTask () {\n if ( timer != null ) {\n timer .cancel() ;\n timer = null;\n }\n }\n public void initializeTimerTask () {\n timerTask = new TimerTask() {\n public void run () {\n handler .post( new Runnable() {\n public void run () {\n createNotification() ;\n }\n }) ;\n }\n } ;\n }\n private void createNotification () {\n NotificationManager mNotificationManager = (NotificationManager)getSystemService( NOTIFICATION_SERVICE ) ; \n NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext() , default_notification_channel_id ) ;\n mBuilder.setContentTitle( \"My Notification\" ) ;\n mBuilder.setContentText( \"Notification Listener Service Example\" ) ;\n mBuilder.setTicker( \"Notification Listener Service Example\" ) ;\n mBuilder.setSmallIcon(R.drawable. ic_launcher_foreground ) ;\n mBuilder.setAutoCancel( true ) ;\n if (android.os.Build.VERSION. SDK_INT >= android.os.Build.VERSION_CODES. O ) {\n int importance = NotificationManager. IMPORTANCE_HIGH ;\n NotificationChannel notificationChannel = new NotificationChannel( NOTIFICATION_CHANNEL_ID , \"NOTIFICATION_CHANNEL_NAME\" , importance) ;\n mBuilder.setChannelId( NOTIFICATION_CHANNEL_ID ) ;\n assert mNotificationManager != null;\n mNotificationManager.createNotificationChannel(notificationChannel) ;\n }\n assert mNotificationManager != null;\n mNotificationManager.notify(( int ) System. currentTimeMillis () , mBuilder.build()) ;\n }\n}"
},
{
"code": null,
"e": 5803,
"s": 5748,
"text": "Step 5 − Add the following code to AndroidManifest.xml"
},
{
"code": null,
"e": 6963,
"s": 5803,
"text": "<? xml version = \"1.0\" encoding = \"utf-8\" ?>\n<manifest xmlns: android = \"http://schemas.android.com/apk/res/android\"\n package = \"app.tutorialspoint.com.notifyme\" >\n <uses-permission android :name = \"android.permission.VIBRATE\" />\n <application\n android :allowBackup = \"true\"\n android :icon = \"@mipmap/ic_launcher\"\n android :label = \"@string/app_name\"\n android :roundIcon = \"@mipmap/ic_launcher_round\"\n android :supportsRtl = \"true\"\n android :theme = \"@style/AppTheme\" >\n <activity android :name = \".MainActivity\" >\n <intent-filter>\n <action android :name = \"android.intent.action.MAIN\" />\n <category android :name = \"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n <service\n android :name = \".NotificationService\"\n android :label = \"@string/app_name\" >\n <intent-filter>\n <action\n android :name = \"app.tutorialspoint.com.notifyme.NotificationService\" />\n <category android :name = \"android.intent.category.DEFAULT\" />\n </intent-filter>\n </service>\n </application>\n</manifest>"
},
{
"code": null,
"e": 7310,
"s": 6963,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −"
},
{
"code": null,
"e": 7352,
"s": 7310,
"text": "Click here to download the project code"
}
] |
Get the List of Arguments of a Function in R Programming – args() Function | 12 Jun, 2020
args() function in R Language is used to get the required arguments by a function. It takes function name as arguments and returns the arguments that are required by that function.
Syntax: args(name)
Parameters:name: Function name
Returns:
For a closure: Formal Argument list but with NULL body
For a Primitive Function: A closure with usage and a NULL body
For a non-function: NULL in case of not a function.
Example 1:
# R program to get arguments of a function # Calling args() Functionargs(append)args(sin)args(paste)
Output:
function (x, values, after = length(x))
NULL
function (x)
NULL
function (..., sep = " ", collapse = NULL)
NULL
Example 2:
# R program to get arguments of a function # Calling args() Functionargs(1)args(10)
Output:
NULL
NULL
The above code returns NULL because the names passed to args() function are not actual functions.
R-Functions
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Filter data by multiple conditions in R using Dplyr
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Loops in R (for, while, repeat)
Group by function in R using Dplyr
How to change Row Names of DataFrame in R ?
How to Change Axis Scales in R Plots?
How to filter R DataFrame by values in a column?
R - if statement
Remove rows with NA in one column of R DataFrame | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n12 Jun, 2020"
},
{
"code": null,
"e": 209,
"s": 28,
"text": "args() function in R Language is used to get the required arguments by a function. It takes function name as arguments and returns the arguments that are required by that function."
},
{
"code": null,
"e": 228,
"s": 209,
"text": "Syntax: args(name)"
},
{
"code": null,
"e": 259,
"s": 228,
"text": "Parameters:name: Function name"
},
{
"code": null,
"e": 268,
"s": 259,
"text": "Returns:"
},
{
"code": null,
"e": 323,
"s": 268,
"text": "For a closure: Formal Argument list but with NULL body"
},
{
"code": null,
"e": 386,
"s": 323,
"text": "For a Primitive Function: A closure with usage and a NULL body"
},
{
"code": null,
"e": 438,
"s": 386,
"text": "For a non-function: NULL in case of not a function."
},
{
"code": null,
"e": 449,
"s": 438,
"text": "Example 1:"
},
{
"code": "# R program to get arguments of a function # Calling args() Functionargs(append)args(sin)args(paste)",
"e": 551,
"s": 449,
"text": null
},
{
"code": null,
"e": 559,
"s": 551,
"text": "Output:"
},
{
"code": null,
"e": 674,
"s": 559,
"text": "function (x, values, after = length(x)) \nNULL\nfunction (x) \nNULL\nfunction (..., sep = \" \", collapse = NULL) \nNULL\n"
},
{
"code": null,
"e": 685,
"s": 674,
"text": "Example 2:"
},
{
"code": "# R program to get arguments of a function # Calling args() Functionargs(1)args(10)",
"e": 770,
"s": 685,
"text": null
},
{
"code": null,
"e": 778,
"s": 770,
"text": "Output:"
},
{
"code": null,
"e": 789,
"s": 778,
"text": "NULL\nNULL\n"
},
{
"code": null,
"e": 887,
"s": 789,
"text": "The above code returns NULL because the names passed to args() function are not actual functions."
},
{
"code": null,
"e": 899,
"s": 887,
"text": "R-Functions"
},
{
"code": null,
"e": 910,
"s": 899,
"text": "R Language"
},
{
"code": null,
"e": 1008,
"s": 910,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1060,
"s": 1008,
"text": "Filter data by multiple conditions in R using Dplyr"
},
{
"code": null,
"e": 1112,
"s": 1060,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 1170,
"s": 1112,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 1202,
"s": 1170,
"text": "Loops in R (for, while, repeat)"
},
{
"code": null,
"e": 1237,
"s": 1202,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 1281,
"s": 1237,
"text": "How to change Row Names of DataFrame in R ?"
},
{
"code": null,
"e": 1319,
"s": 1281,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 1368,
"s": 1319,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 1385,
"s": 1368,
"text": "R - if statement"
}
] |
Tensorflow.js tf.train.sgd() Function | 14 Aug, 2021
Tensorflow.js is an open-source library that is developed by Google for running machine learning models as well as deep learning neural networks in the browser or node environment.
The .train.sgd() function is used to build a tf.SGDOptimizer which utilizes stochastic gradient descent.
Syntax:
tf.train.sgd(learningRate)
Parameters:
learningRate: The stated learning rate which is used in favor of the SGD algorithm. It is of type number.
Return Value: It returns tf.SGDOptimizer.
Example 1:
Javascript
// Importing the tensorflow.js libraryimport * as tf from "@tensorflow/tfjs" // Declaring learningRateconst learning_rate = 0.02; // Calling train.sgd() methodconst res = tf.train.sgd(learning_rate); // Printing outputconsole.log(res);
Output:
{
"learningRate": 0.02,
"c": {
"kept": true,
"isDisposedInternal": false,
"shape": [],
"dtype": "float32",
"size": 1,
"strides": [],
"dataId": {
"id": 1298
},
"id": 1192,
"rankType": "0",
"scopeId": 1251
}
}
Example 2:
Javascript
// Importing the tensorflow.js libraryimport * as tf from "@tensorflow/tfjs" // Calling train.sgd() and sin() methodconsole.log(JSON.stringify(tf.train.sgd(tf.sin(45))));
Output:
{"learningRate":{"kept":false,"isDisposedInternal":false,"shape":[],
"dtype":"float32","size":1,"strides":[],"dataId":{"id":1316},"id":1207,
"rankType":"0","scopeId":1269},"c":{"kept":true,"isDisposedInternal":false,
"shape":[],"dtype":"float32","size":1,"strides":[],"dataId":{"id":1318},
"id":1208,"rankType":"0","scopeId":1269}}
Reference: https://js.tensorflow.org/api/latest/#train.sgd
Picked
Tensorflow.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n14 Aug, 2021"
},
{
"code": null,
"e": 209,
"s": 28,
"text": "Tensorflow.js is an open-source library that is developed by Google for running machine learning models as well as deep learning neural networks in the browser or node environment."
},
{
"code": null,
"e": 314,
"s": 209,
"text": "The .train.sgd() function is used to build a tf.SGDOptimizer which utilizes stochastic gradient descent."
},
{
"code": null,
"e": 322,
"s": 314,
"text": "Syntax:"
},
{
"code": null,
"e": 349,
"s": 322,
"text": "tf.train.sgd(learningRate)"
},
{
"code": null,
"e": 361,
"s": 349,
"text": "Parameters:"
},
{
"code": null,
"e": 467,
"s": 361,
"text": "learningRate: The stated learning rate which is used in favor of the SGD algorithm. It is of type number."
},
{
"code": null,
"e": 509,
"s": 467,
"text": "Return Value: It returns tf.SGDOptimizer."
},
{
"code": null,
"e": 522,
"s": 511,
"text": "Example 1:"
},
{
"code": null,
"e": 533,
"s": 522,
"text": "Javascript"
},
{
"code": "// Importing the tensorflow.js libraryimport * as tf from \"@tensorflow/tfjs\" // Declaring learningRateconst learning_rate = 0.02; // Calling train.sgd() methodconst res = tf.train.sgd(learning_rate); // Printing outputconsole.log(res);",
"e": 772,
"s": 533,
"text": null
},
{
"code": null,
"e": 780,
"s": 772,
"text": "Output:"
},
{
"code": null,
"e": 1044,
"s": 780,
"text": "{\n \"learningRate\": 0.02,\n \"c\": {\n \"kept\": true,\n \"isDisposedInternal\": false,\n \"shape\": [],\n \"dtype\": \"float32\",\n \"size\": 1,\n \"strides\": [],\n \"dataId\": {\n \"id\": 1298\n },\n \"id\": 1192,\n \"rankType\": \"0\",\n \"scopeId\": 1251\n }\n}"
},
{
"code": null,
"e": 1055,
"s": 1044,
"text": "Example 2:"
},
{
"code": null,
"e": 1066,
"s": 1055,
"text": "Javascript"
},
{
"code": "// Importing the tensorflow.js libraryimport * as tf from \"@tensorflow/tfjs\" // Calling train.sgd() and sin() methodconsole.log(JSON.stringify(tf.train.sgd(tf.sin(45))));",
"e": 1238,
"s": 1066,
"text": null
},
{
"code": null,
"e": 1246,
"s": 1238,
"text": "Output:"
},
{
"code": null,
"e": 1578,
"s": 1246,
"text": "{\"learningRate\":{\"kept\":false,\"isDisposedInternal\":false,\"shape\":[],\n\"dtype\":\"float32\",\"size\":1,\"strides\":[],\"dataId\":{\"id\":1316},\"id\":1207,\n\"rankType\":\"0\",\"scopeId\":1269},\"c\":{\"kept\":true,\"isDisposedInternal\":false,\n\"shape\":[],\"dtype\":\"float32\",\"size\":1,\"strides\":[],\"dataId\":{\"id\":1318},\n\"id\":1208,\"rankType\":\"0\",\"scopeId\":1269}}"
},
{
"code": null,
"e": 1637,
"s": 1578,
"text": "Reference: https://js.tensorflow.org/api/latest/#train.sgd"
},
{
"code": null,
"e": 1644,
"s": 1637,
"text": "Picked"
},
{
"code": null,
"e": 1658,
"s": 1644,
"text": "Tensorflow.js"
},
{
"code": null,
"e": 1669,
"s": 1658,
"text": "JavaScript"
},
{
"code": null,
"e": 1686,
"s": 1669,
"text": "Web Technologies"
}
] |
Difference between node.js require and ES6 import and export | 09 Mar, 2022
Node.js follows the commonJS module system, and it require to include modules that exist in separate files and for that purpose it has methods like “require” and “ES6 import and export” are available in node.js.
Require: It is the builtin function and it is the easiest way to include modules that exist in separate files. The basic functionality of require is that it reads a JavaScript file, executes the file, and then proceeds to return the export object. It not only allows you to add built-in core Node modules but also community-based modules (node_modules), and local modules in the desired program. There are various inbuilt modules in a node like – HTTP module, URL module, query string module, path module and a lot more.
Syntax:
To including inbuilt module is as follows:const express = require('express');
const express = require('express');
To including local module is as follows. For an instance, you require ‘abc’ module, without specifying a path.require('abc');
require('abc');
Example: Node will look for abc.js in all the paths specified by module.paths in order.
Input:require('abc');
require('abc');
Output:If node can’t find it:Error: Cannot find module 'abc' at Function.Module._resolveFilename (module.js:470:15) at Function.Module._load (module.js:418:25) at Module.require (module.js:498:17) at require (internal/module.js:20:19) at repl:1:1 at ContextifyScript.Script.runInThisContext (vm.js:23:33) at REPLServer.defaultEval (repl.js:336:29) at bound (domain.js:280:14) at REPLServer.runBound [as eval] (domain.js:293:12) at REPLServer.onLine (repl.js:533:10)If node find it:// It is the content of the fileGeeksforgeeks example for require
If node can’t find it:Error: Cannot find module 'abc' at Function.Module._resolveFilename (module.js:470:15) at Function.Module._load (module.js:418:25) at Module.require (module.js:498:17) at require (internal/module.js:20:19) at repl:1:1 at ContextifyScript.Script.runInThisContext (vm.js:23:33) at REPLServer.defaultEval (repl.js:336:29) at bound (domain.js:280:14) at REPLServer.runBound [as eval] (domain.js:293:12) at REPLServer.onLine (repl.js:533:10)
Error: Cannot find module 'abc' at Function.Module._resolveFilename (module.js:470:15) at Function.Module._load (module.js:418:25) at Module.require (module.js:498:17) at require (internal/module.js:20:19) at repl:1:1 at ContextifyScript.Script.runInThisContext (vm.js:23:33) at REPLServer.defaultEval (repl.js:336:29) at bound (domain.js:280:14) at REPLServer.runBound [as eval] (domain.js:293:12) at REPLServer.onLine (repl.js:533:10)
If node find it:// It is the content of the fileGeeksforgeeks example for require
// It is the content of the fileGeeksforgeeks example for require
ES6 Import & Export: These statements are used to refer to an ES module. Other file types can’t be imported with these statements. They are permitted only in ES modules and the specifier of this statement can either be a URL-style relative path or a package name.
Whereas Export statements allow the user to export his created objects and methods to other programs. For instance, if you assign a string literal then it will expose that string literal as a module.
Syntax:
For importing file.// Importing submodule from
// 'es-module-package/private-module.js';
import './private-module.js';
// Importing submodule from
// 'es-module-package/private-module.js';
import './private-module.js';
For exporting file.module.exports = 'A Computer Science Portal';
module.exports = 'A Computer Science Portal';
Example: Create two JS file one is for importing and another one is for exporting or you can use any module to import so export one will not be required.
Export File name Message.js// Exporting modulemodule.exports = 'Hello Geek';ImportFile name Display.js// Importing modulevar msg = import('./Message.js');console.log(msg);</li> <li><strong>Output:</strong><div class="noIdeBtnDiv">Hello Geek
// Exporting modulemodule.exports = 'Hello Geek';
ImportFile name Display.js
// Importing modulevar msg = import('./Message.js');console.log(msg);</li> <li><strong>Output:</strong><div class="noIdeBtnDiv">Hello Geek
Difference between node.js require and ES6 import and export: Although require function and ES6 import and export share a lot in common and seem to perform the same function in code but they are different in many ways.
NOTE: You must note that you can’t use require and import at the same time in your node program and it is more preferred to use require instead of import as you are required to use the experimental module flag feature to run import program.
chusapkrerkkiat
kothavvsaakash
ES6
Node.js-Misc
Picked
JavaScript
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n09 Mar, 2022"
},
{
"code": null,
"e": 264,
"s": 52,
"text": "Node.js follows the commonJS module system, and it require to include modules that exist in separate files and for that purpose it has methods like “require” and “ES6 import and export” are available in node.js."
},
{
"code": null,
"e": 785,
"s": 264,
"text": "Require: It is the builtin function and it is the easiest way to include modules that exist in separate files. The basic functionality of require is that it reads a JavaScript file, executes the file, and then proceeds to return the export object. It not only allows you to add built-in core Node modules but also community-based modules (node_modules), and local modules in the desired program. There are various inbuilt modules in a node like – HTTP module, URL module, query string module, path module and a lot more."
},
{
"code": null,
"e": 793,
"s": 785,
"text": "Syntax:"
},
{
"code": null,
"e": 871,
"s": 793,
"text": "To including inbuilt module is as follows:const express = require('express');"
},
{
"code": null,
"e": 907,
"s": 871,
"text": "const express = require('express');"
},
{
"code": null,
"e": 1033,
"s": 907,
"text": "To including local module is as follows. For an instance, you require ‘abc’ module, without specifying a path.require('abc');"
},
{
"code": null,
"e": 1049,
"s": 1033,
"text": "require('abc');"
},
{
"code": null,
"e": 1137,
"s": 1049,
"text": "Example: Node will look for abc.js in all the paths specified by module.paths in order."
},
{
"code": null,
"e": 1159,
"s": 1137,
"text": "Input:require('abc');"
},
{
"code": "require('abc');",
"e": 1175,
"s": 1159,
"text": null
},
{
"code": null,
"e": 1752,
"s": 1175,
"text": "Output:If node can’t find it:Error: Cannot find module 'abc' at Function.Module._resolveFilename (module.js:470:15) at Function.Module._load (module.js:418:25) at Module.require (module.js:498:17) at require (internal/module.js:20:19) at repl:1:1 at ContextifyScript.Script.runInThisContext (vm.js:23:33) at REPLServer.defaultEval (repl.js:336:29) at bound (domain.js:280:14) at REPLServer.runBound [as eval] (domain.js:293:12) at REPLServer.onLine (repl.js:533:10)If node find it:// It is the content of the fileGeeksforgeeks example for require"
},
{
"code": null,
"e": 2241,
"s": 1752,
"text": "If node can’t find it:Error: Cannot find module 'abc' at Function.Module._resolveFilename (module.js:470:15) at Function.Module._load (module.js:418:25) at Module.require (module.js:498:17) at require (internal/module.js:20:19) at repl:1:1 at ContextifyScript.Script.runInThisContext (vm.js:23:33) at REPLServer.defaultEval (repl.js:336:29) at bound (domain.js:280:14) at REPLServer.runBound [as eval] (domain.js:293:12) at REPLServer.onLine (repl.js:533:10)"
},
{
"code": "Error: Cannot find module 'abc' at Function.Module._resolveFilename (module.js:470:15) at Function.Module._load (module.js:418:25) at Module.require (module.js:498:17) at require (internal/module.js:20:19) at repl:1:1 at ContextifyScript.Script.runInThisContext (vm.js:23:33) at REPLServer.defaultEval (repl.js:336:29) at bound (domain.js:280:14) at REPLServer.runBound [as eval] (domain.js:293:12) at REPLServer.onLine (repl.js:533:10)",
"e": 2708,
"s": 2241,
"text": null
},
{
"code": null,
"e": 2790,
"s": 2708,
"text": "If node find it:// It is the content of the fileGeeksforgeeks example for require"
},
{
"code": "// It is the content of the fileGeeksforgeeks example for require",
"e": 2856,
"s": 2790,
"text": null
},
{
"code": null,
"e": 3120,
"s": 2856,
"text": "ES6 Import & Export: These statements are used to refer to an ES module. Other file types can’t be imported with these statements. They are permitted only in ES modules and the specifier of this statement can either be a URL-style relative path or a package name."
},
{
"code": null,
"e": 3320,
"s": 3120,
"text": "Whereas Export statements allow the user to export his created objects and methods to other programs. For instance, if you assign a string literal then it will expose that string literal as a module."
},
{
"code": null,
"e": 3328,
"s": 3320,
"text": "Syntax:"
},
{
"code": null,
"e": 3448,
"s": 3328,
"text": "For importing file.// Importing submodule from \n// 'es-module-package/private-module.js';\nimport './private-module.js';"
},
{
"code": null,
"e": 3549,
"s": 3448,
"text": "// Importing submodule from \n// 'es-module-package/private-module.js';\nimport './private-module.js';"
},
{
"code": null,
"e": 3614,
"s": 3549,
"text": "For exporting file.module.exports = 'A Computer Science Portal';"
},
{
"code": null,
"e": 3660,
"s": 3614,
"text": "module.exports = 'A Computer Science Portal';"
},
{
"code": null,
"e": 3814,
"s": 3660,
"text": "Example: Create two JS file one is for importing and another one is for exporting or you can use any module to import so export one will not be required."
},
{
"code": null,
"e": 4060,
"s": 3814,
"text": "Export File name Message.js// Exporting modulemodule.exports = 'Hello Geek';ImportFile name Display.js// Importing modulevar msg = import('./Message.js');console.log(msg);</li> <li><strong>Output:</strong><div class=\"noIdeBtnDiv\">Hello Geek"
},
{
"code": "// Exporting modulemodule.exports = 'Hello Geek';",
"e": 4110,
"s": 4060,
"text": null
},
{
"code": null,
"e": 4137,
"s": 4110,
"text": "ImportFile name Display.js"
},
{
"code": "// Importing modulevar msg = import('./Message.js');console.log(msg);</li> <li><strong>Output:</strong><div class=\"noIdeBtnDiv\">Hello Geek",
"e": 4281,
"s": 4137,
"text": null
},
{
"code": null,
"e": 4500,
"s": 4281,
"text": "Difference between node.js require and ES6 import and export: Although require function and ES6 import and export share a lot in common and seem to perform the same function in code but they are different in many ways."
},
{
"code": null,
"e": 4741,
"s": 4500,
"text": "NOTE: You must note that you can’t use require and import at the same time in your node program and it is more preferred to use require instead of import as you are required to use the experimental module flag feature to run import program."
},
{
"code": null,
"e": 4757,
"s": 4741,
"text": "chusapkrerkkiat"
},
{
"code": null,
"e": 4772,
"s": 4757,
"text": "kothavvsaakash"
},
{
"code": null,
"e": 4776,
"s": 4772,
"text": "ES6"
},
{
"code": null,
"e": 4789,
"s": 4776,
"text": "Node.js-Misc"
},
{
"code": null,
"e": 4796,
"s": 4789,
"text": "Picked"
},
{
"code": null,
"e": 4807,
"s": 4796,
"text": "JavaScript"
},
{
"code": null,
"e": 4815,
"s": 4807,
"text": "Node.js"
},
{
"code": null,
"e": 4832,
"s": 4815,
"text": "Web Technologies"
}
] |
How to Install PSAD on Ubuntu Linux? | 07 Jun, 2022
PSAD(Port Scan Attack Detection) is used to block post scanning on the server. psad tool keeps on monitoring firewall(iptables)logs to determine port scan or any other attack occurred. If some successful attack on the server happens psad also takes action to detect the threat. This is a collection of lightweight system daemons that run on a Linux system.
Features:
This supports both ipv4 and ipv6 logs generated by iptablesFree and distributed under the GNU General Public LicenseEmail notifications with TCP, UDP, ICMP scan characteristic, reverse DNSAutoblock suspicious IP addresses via iptables and TCP wrappers based on scan level
This supports both ipv4 and ipv6 logs generated by iptables
Free and distributed under the GNU General Public License
Email notifications with TCP, UDP, ICMP scan characteristic, reverse DNS
Autoblock suspicious IP addresses via iptables and TCP wrappers based on scan level
Before installing, update, and upgrade the system.
The command for update:
sudo apt update
The Command for upgrade:
sudo apt upgrade
Installing PSAD:
sudo apt install psad
Psad requires many dependencies that are installed automatically from the Ubuntu repository. So during the installation, we will get a pop-up like in the below image it is a psad prompt for mail server configuration.
Configuration:
PSAD uses firewall (iptables) logs to detect any malicious activity in the machine. So to enable logging of packets on input & forward chains of iptables. commands are given below
sudo iptables -A INPUT -j LOG
sudo iptables -A FORWARD -j LOG
Hereafter executing the above two commands you will not get any output. Like in the below image
After enabling the logs using the above commands run the following command to list the current configuration of iptables:
sudo iptables -L
After executing the above command you will get the output as in the below Screenshot:
Configuring PSAD:
By default, Psad stores their configuration files, snort rules & signatures are under /etc/psad directory. Let us start by editing the main psad configuration /etc/psad/psad.conf, this has many parameters to change while deploying to the production server. So let’s not dive so deep into the concept here we will change few things in PSAD so that it detects iptables logs and takes necessary action to detect the attack.
nano /etc/psad/psad.conf
After executing the above command you will get the output as in the below Screenshot:
So Change the file as given below:
EMAIL_ADDRESSES root@localhost; ##change it your email id to get psad alerts
HOSTNAME test-machine; # your host machine name
HOME_NET 192.168.154.0/24; # Set LAN network
EXTERNAL_NET any; # Set Wan network
ENABLE_SYSLOG_FILE Y; #by default set yes
One of the main configurations of PSAD is setting the IPT_SYSLOG_FILE parameter. by default it searches for logs in /var/log/messages, but in ubuntu, it is in /var/log/syslog so we have to change the path so that PSAD detects malicious activity.
IPT_SYSLOG_FILE /var/log/syslog; #change it from /message to /syslog
Here we will be using PSAD as IDS/IPS, so enable it. This will automatically change the iptables rules to block scan from the attacker.
ENABLE_AUTO_IDS Y; # disable by default
So after doing the changes in your psad.conf which I have in the above lines(like changing: email address, hostname,home_net, External_net, IPT_SYSLOG_FILE, ENABLE_AUTO_IDS) just save your file and exit it.
So now the basic configuration psad file is completed. Now we can update the signatures so that it can correctly recognize known attack types.
sudo psad --sig-update
After executing the command you will get a result like in the below screenshot:
So now to start the PSAD use the following command:
Command: /etc/init.d/psad start
This will start the PSAD tool As you see in the below screenshot
We can stop the psad tool by just replacing the start with a stop in the above command.
nikhatkhan11
Picked
How To
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Set Git Username and Password in GitBash?
How to Install Jupyter Notebook on MacOS?
How to Install and Use NVM on Windows?
How to Install Python Packages for AWS Lambda Layers?
How to Permanently Disable Swap in Linux?
Sed Command in Linux/Unix with examples
AWK command in Unix/Linux with examples
grep command in Unix/Linux
cut command in Linux with examples
cp command in Linux with examples | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n07 Jun, 2022"
},
{
"code": null,
"e": 385,
"s": 28,
"text": "PSAD(Port Scan Attack Detection) is used to block post scanning on the server. psad tool keeps on monitoring firewall(iptables)logs to determine port scan or any other attack occurred. If some successful attack on the server happens psad also takes action to detect the threat. This is a collection of lightweight system daemons that run on a Linux system."
},
{
"code": null,
"e": 395,
"s": 385,
"text": "Features:"
},
{
"code": null,
"e": 667,
"s": 395,
"text": "This supports both ipv4 and ipv6 logs generated by iptablesFree and distributed under the GNU General Public LicenseEmail notifications with TCP, UDP, ICMP scan characteristic, reverse DNSAutoblock suspicious IP addresses via iptables and TCP wrappers based on scan level"
},
{
"code": null,
"e": 727,
"s": 667,
"text": "This supports both ipv4 and ipv6 logs generated by iptables"
},
{
"code": null,
"e": 785,
"s": 727,
"text": "Free and distributed under the GNU General Public License"
},
{
"code": null,
"e": 858,
"s": 785,
"text": "Email notifications with TCP, UDP, ICMP scan characteristic, reverse DNS"
},
{
"code": null,
"e": 942,
"s": 858,
"text": "Autoblock suspicious IP addresses via iptables and TCP wrappers based on scan level"
},
{
"code": null,
"e": 993,
"s": 942,
"text": "Before installing, update, and upgrade the system."
},
{
"code": null,
"e": 1018,
"s": 993,
"text": "The command for update: "
},
{
"code": null,
"e": 1035,
"s": 1018,
"text": "sudo apt update "
},
{
"code": null,
"e": 1060,
"s": 1035,
"text": "The Command for upgrade:"
},
{
"code": null,
"e": 1078,
"s": 1060,
"text": "sudo apt upgrade "
},
{
"code": null,
"e": 1095,
"s": 1078,
"text": "Installing PSAD:"
},
{
"code": null,
"e": 1117,
"s": 1095,
"text": "sudo apt install psad"
},
{
"code": null,
"e": 1334,
"s": 1117,
"text": "Psad requires many dependencies that are installed automatically from the Ubuntu repository. So during the installation, we will get a pop-up like in the below image it is a psad prompt for mail server configuration."
},
{
"code": null,
"e": 1349,
"s": 1334,
"text": "Configuration:"
},
{
"code": null,
"e": 1531,
"s": 1349,
"text": "PSAD uses firewall (iptables) logs to detect any malicious activity in the machine. So to enable logging of packets on input & forward chains of iptables. commands are given below "
},
{
"code": null,
"e": 1594,
"s": 1531,
"text": "sudo iptables -A INPUT -j LOG\nsudo iptables -A FORWARD -j LOG "
},
{
"code": null,
"e": 1691,
"s": 1594,
"text": "Hereafter executing the above two commands you will not get any output. Like in the below image "
},
{
"code": null,
"e": 1813,
"s": 1691,
"text": "After enabling the logs using the above commands run the following command to list the current configuration of iptables:"
},
{
"code": null,
"e": 1830,
"s": 1813,
"text": "sudo iptables -L"
},
{
"code": null,
"e": 1916,
"s": 1830,
"text": "After executing the above command you will get the output as in the below Screenshot:"
},
{
"code": null,
"e": 1934,
"s": 1916,
"text": "Configuring PSAD:"
},
{
"code": null,
"e": 2356,
"s": 1934,
"text": "By default, Psad stores their configuration files, snort rules & signatures are under /etc/psad directory. Let us start by editing the main psad configuration /etc/psad/psad.conf, this has many parameters to change while deploying to the production server. So let’s not dive so deep into the concept here we will change few things in PSAD so that it detects iptables logs and takes necessary action to detect the attack."
},
{
"code": null,
"e": 2381,
"s": 2356,
"text": "nano /etc/psad/psad.conf"
},
{
"code": null,
"e": 2467,
"s": 2381,
"text": "After executing the above command you will get the output as in the below Screenshot:"
},
{
"code": null,
"e": 2502,
"s": 2467,
"text": "So Change the file as given below:"
},
{
"code": null,
"e": 2788,
"s": 2502,
"text": "EMAIL_ADDRESSES root@localhost; ##change it your email id to get psad alerts \n\nHOSTNAME test-machine; # your host machine name \n\nHOME_NET 192.168.154.0/24; # Set LAN network \n\nEXTERNAL_NET any; # Set Wan network \n\nENABLE_SYSLOG_FILE Y; #by default set yes"
},
{
"code": null,
"e": 3037,
"s": 2788,
"text": "One of the main configurations of PSAD is setting the IPT_SYSLOG_FILE parameter. by default it searches for logs in /var/log/messages, but in ubuntu, it is in /var/log/syslog so we have to change the path so that PSAD detects malicious activity."
},
{
"code": null,
"e": 3118,
"s": 3037,
"text": "IPT_SYSLOG_FILE /var/log/syslog; #change it from /message to /syslog"
},
{
"code": null,
"e": 3255,
"s": 3118,
"text": "Here we will be using PSAD as IDS/IPS, so enable it. This will automatically change the iptables rules to block scan from the attacker."
},
{
"code": null,
"e": 3303,
"s": 3255,
"text": "ENABLE_AUTO_IDS Y; # disable by default"
},
{
"code": null,
"e": 3511,
"s": 3303,
"text": "So after doing the changes in your psad.conf which I have in the above lines(like changing: email address, hostname,home_net, External_net, IPT_SYSLOG_FILE, ENABLE_AUTO_IDS) just save your file and exit it."
},
{
"code": null,
"e": 3654,
"s": 3511,
"text": "So now the basic configuration psad file is completed. Now we can update the signatures so that it can correctly recognize known attack types."
},
{
"code": null,
"e": 3677,
"s": 3654,
"text": "sudo psad --sig-update"
},
{
"code": null,
"e": 3757,
"s": 3677,
"text": "After executing the command you will get a result like in the below screenshot:"
},
{
"code": null,
"e": 3809,
"s": 3757,
"text": "So now to start the PSAD use the following command:"
},
{
"code": null,
"e": 3841,
"s": 3809,
"text": "Command: /etc/init.d/psad start"
},
{
"code": null,
"e": 3907,
"s": 3841,
"text": "This will start the PSAD tool As you see in the below screenshot "
},
{
"code": null,
"e": 3995,
"s": 3907,
"text": "We can stop the psad tool by just replacing the start with a stop in the above command."
},
{
"code": null,
"e": 4008,
"s": 3995,
"text": "nikhatkhan11"
},
{
"code": null,
"e": 4015,
"s": 4008,
"text": "Picked"
},
{
"code": null,
"e": 4022,
"s": 4015,
"text": "How To"
},
{
"code": null,
"e": 4033,
"s": 4022,
"text": "Linux-Unix"
},
{
"code": null,
"e": 4131,
"s": 4033,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4180,
"s": 4131,
"text": "How to Set Git Username and Password in GitBash?"
},
{
"code": null,
"e": 4222,
"s": 4180,
"text": "How to Install Jupyter Notebook on MacOS?"
},
{
"code": null,
"e": 4261,
"s": 4222,
"text": "How to Install and Use NVM on Windows?"
},
{
"code": null,
"e": 4315,
"s": 4261,
"text": "How to Install Python Packages for AWS Lambda Layers?"
},
{
"code": null,
"e": 4357,
"s": 4315,
"text": "How to Permanently Disable Swap in Linux?"
},
{
"code": null,
"e": 4397,
"s": 4357,
"text": "Sed Command in Linux/Unix with examples"
},
{
"code": null,
"e": 4437,
"s": 4397,
"text": "AWK command in Unix/Linux with examples"
},
{
"code": null,
"e": 4464,
"s": 4437,
"text": "grep command in Unix/Linux"
},
{
"code": null,
"e": 4499,
"s": 4464,
"text": "cut command in Linux with examples"
}
] |
Create a customized data structure which evaluates functions in O(1) | 02 Sep, 2021
Create a customized data structure such that it has functions :- GetLastElement(); RemoveLastElement(); AddElement() GetMin()
All the functions should be of O(1)Question Source : amazon interview questions
Approach : 1) create a custom stack of type structure with two elements, (element, min_till_now) 2) implement the functions on this custom data type
C++
Java
Python3
C#
Javascript
// program to demonstrate customized data structure// which supports functions in O(1)#include <iostream>#include <vector>using namespace std;const int MAXX = 1000; // class stackclass stack { int minn; int size; public: stack() { minn = 99999; size = -1; } vector<pair<int, int> > arr; int GetLastElement(); int RemoveLastElement(); int AddElement(int element); int GetMin();}; // utility function for adding a new elementint stack::AddElement(int element){ if (size > MAXX) { cout << "stack overflow, max size reached!\n"; return 0; } if (element < minn) minn = element; arr.push_back(make_pair(element, minn)); size++; return 1;} // utility function for returning last element of stackint stack::GetLastElement(){ if (size == -1) { cout << "No elements in stack\n"; return 0; } return arr[size].first;} // utility function for removing last element successfully;int stack::RemoveLastElement(){ if (size == -1) { cout << "stack empty!!!\n"; return 0; } // updating minimum element if (size > 0 && arr[size - 1].second > arr[size].second) { minn = arr[size - 1].second; } arr.pop_back(); size -= 1; return 1;} // utility function for returning min element till now;int stack::GetMin(){ if (size == -1) { cout << "stack empty!!\n"; return 0; } return arr[size].second;} // Driver codeint main(){ stack s; int success = s.AddElement(5); if (success == 1) cout << "5 inserted successfully\n"; success = s.AddElement(7); if (success == 1) cout << "7 inserted successfully\n"; success = s.AddElement(3); if (success == 1) cout << "3 inserted successfully\n"; int min1 = s.GetMin(); cout << "min element :: " << min1 << endl; success = s.RemoveLastElement(); if (success == 1) cout << "removed successfully\n"; success = s.AddElement(2); if (success == 1) cout << "2 inserted successfully\n"; success = s.AddElement(9); if (success == 1) cout << "9 inserted successfully\n"; int last = s.GetLastElement(); cout << "Last element :: " << last << endl; success = s.AddElement(0); if (success == 1) cout << "0 inserted successfully\n"; min1 = s.GetMin(); cout << "min element :: " << min1 << endl; success = s.RemoveLastElement(); if (success == 1) cout << "removed successfully\n"; success = s.AddElement(11); if (success == 1) cout << "11 inserted successfully\n"; min1 = s.GetMin(); cout << "min element :: " << min1 << endl; return 0;}
// program to demonstrate customized data structure// which supports functions in O(1)import java.util.ArrayList;public class Gfg{ // class Pair static class Pair{ int element; int minElement; public Pair(int element, int minElement) { this.element = element; this.minElement = minElement; } } int min; ArrayList<Pair> stack = new ArrayList<>(); public Gfg() { this.min = Integer.MAX_VALUE; } // utility function for adding a new element void addElement(int x) { if(stack.size() == 0 || x < min) { min=x; } Pair pair = new Pair(x,min); stack.add(pair); System.out.println(x + " inserted successfully"); } // utility function for returning last element of stack int getLastElement() { if (stack.size() == 0) { System.out.println("UnderFlow Error"); return -1; } else { return stack.get(stack.size() - 1).element; } } // utility function for removing last element successfully; void removeLastElement() { if (stack.size() == 0) { System.out.println("UnderFlow Error"); } else if (stack.size() > 1) { min=stack.get(stack.size() - 2).minElement; } else { min=Integer.MAX_VALUE; } stack.remove(stack.size() - 1); System.out.println("removed successfully"); } // utility function for returning min element till now; int getMin() { if (stack.size() == 0) { System.out.println("UnderFlow Error"); return -1; } return stack.get(stack.size() - 1).minElement; } // Driver Code public static void main(String[] args) { Gfg newStack = new Gfg(); newStack.addElement(5); newStack.addElement(7); newStack.addElement(3); System.out.println("min element :: "+newStack.getMin()); newStack.removeLastElement(); newStack.addElement(2); newStack.addElement(9); System.out.println("last element :: "+newStack.getLastElement()); newStack.addElement(0); System.out.println("min element :: "+newStack.getMin()); newStack.removeLastElement(); newStack.addElement(11); System.out.println("min element :: "+newStack.getMin()); }} // This code is contributed by AkashYadav4.
# Program to demonstrate customized data structure# which supports functions in O(1)import sys stack = []Min = sys.maxsize # Utility function for adding a new elementdef addElement(x): global Min, stack if (len(stack) == 0 or x < Min): Min = x pair = [x, Min] stack.append(pair) print(x, "inserted successfully") # Utility function for returning last# element of stackdef getLastElement(): global Min, stack if (len(stack) == 0): print("UnderFlow Error") return -1 else: return stack[-1][0] # Utility function for removing last# element successfully;def removeLastElement(): global Min, stack if (len(stack) == 0): print("UnderFlow Error") elif (len(stack) > 1): Min = stack[-2][1] else: Min = sys.maxsize stack.pop() print("removed successfully") # Utility function for returning min# element till now;def getMin(): global Min, stack if (len(stack) == 0): print("UnderFlow Error") return -1 return stack[-1][1] # Driver codeaddElement(5)addElement(7)addElement(3)print("min element ::", getMin())removeLastElement()addElement(2)addElement(9)print("Last element ::", getLastElement())addElement(0)print("min element ::", getMin())removeLastElement()addElement(11)print("min element ::", getMin()) # This code is contributed by mukesh07
// program to demonstrate customized data structure// which supports functions in O(1)using System;using System.Collections.Generic;class GFG { static List<Tuple<int,int>> stack = new List<Tuple<int,int>>(); static int min = Int32.MaxValue; // utility function for adding a new element static void addElement(int x) { if(stack.Count == 0 || x < min) { min=x; } Tuple<int,int> pair = new Tuple<int,int>(x,min); stack.Add(pair); Console.WriteLine(x + " inserted successfully"); } // utility function for returning last element of stack static int getLastElement() { if (stack.Count == 0) { Console.WriteLine("UnderFlow Error"); return -1; } else { return stack[stack.Count - 1].Item1; } } // utility function for removing last element successfully; static void removeLastElement() { if (stack.Count == 0) { Console.WriteLine("UnderFlow Error"); } else if (stack.Count > 1) { min=stack[stack.Count - 2].Item2; } else { min=Int32.MaxValue; } stack.RemoveAt(stack.Count - 1); Console.WriteLine("removed successfully"); } // utility function for returning min element till now; static int getMin() { if (stack.Count == 0) { Console.WriteLine("UnderFlow Error"); return -1; } return stack[stack.Count - 1].Item2; } static void Main() { addElement(5); addElement(7); addElement(3); Console.WriteLine("min element :: "+getMin()); removeLastElement(); addElement(2); addElement(9); Console.WriteLine("Last element :: "+getLastElement()); addElement(0); Console.WriteLine("min element :: "+getMin()); removeLastElement(); addElement(11); Console.WriteLine("min element :: "+getMin()); }} // This code is contributed by divyeshrabadiya07.
<script> // program to demonstrate customized data structure // which supports functions in O(1) let min; let stack = []; min = Number.MAX_VALUE // utility function for adding a new element function addElement(x) { if(stack.length == 0 || x < min) { min=x; } let pair = [x,min]; stack.push(pair); document.write(x + " inserted successfully" + "</br>"); } // utility function for returning last element of stack function getLastElement() { if (stack.length == 0) { document.write("UnderFlow Error" + "</br>"); return -1; } else { return stack[stack.length - 1][0]; } } // utility function for removing last element successfully; function removeLastElement() { if (stack.length == 0) { document.write("UnderFlow Error" + "</br>"); } else if (stack.length > 1) { min=stack[stack.length - 2][1]; } else { min=Number.MAX_VALUE; } stack.pop(); document.write("removed successfully" + "</br>"); } // utility function for returning min element till now; function getMin() { if (stack.length == 0) { document.write("UnderFlow Error" + "</br>"); return -1; } return stack[stack.length - 1][1]; } addElement(5); addElement(7); addElement(3); document.write("min element :: "+getMin() + "</br>"); removeLastElement(); addElement(2); addElement(9); document.write("Last element :: "+getLastElement() + "</br>"); addElement(0); document.write("min element :: "+getMin() + "</br>"); removeLastElement(); addElement(11); document.write("min element :: "+getMin() + "</br>"); // This code is contributed by rameshtravel07.</script>
Output:
5 inserted successfully
7 inserted successfully
3 inserted successfully
min element :: 3
removed successfully
2 inserted successfully
9 inserted successfully
Last element :: 9
0 inserted successfully
min element :: 0
removed successfully
11 inserted successfully
min element :: 2
Time complexity : Each function runs in O(1)This article is contributed by Mandeep Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
AakashYadav4
rameshtravel07
mukesh07
divyeshrabadiya07
Amazon
Stack
Amazon
Stack
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stack in Python
Stack Class in Java
Check for Balanced Brackets in an expression (well-formedness) using Stack
Introduction to Data Structures
Stack | Set 2 (Infix to Postfix)
Inorder Tree Traversal without Recursion
Program for Tower of Hanoi
What is Data Structure: Types, Classifications and Applications
Merge Overlapping Intervals
Implement a stack using singly linked list | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n02 Sep, 2021"
},
{
"code": null,
"e": 178,
"s": 52,
"text": "Create a customized data structure such that it has functions :- GetLastElement(); RemoveLastElement(); AddElement() GetMin()"
},
{
"code": null,
"e": 258,
"s": 178,
"text": "All the functions should be of O(1)Question Source : amazon interview questions"
},
{
"code": null,
"e": 408,
"s": 258,
"text": "Approach : 1) create a custom stack of type structure with two elements, (element, min_till_now) 2) implement the functions on this custom data type "
},
{
"code": null,
"e": 412,
"s": 408,
"text": "C++"
},
{
"code": null,
"e": 417,
"s": 412,
"text": "Java"
},
{
"code": null,
"e": 425,
"s": 417,
"text": "Python3"
},
{
"code": null,
"e": 428,
"s": 425,
"text": "C#"
},
{
"code": null,
"e": 439,
"s": 428,
"text": "Javascript"
},
{
"code": "// program to demonstrate customized data structure// which supports functions in O(1)#include <iostream>#include <vector>using namespace std;const int MAXX = 1000; // class stackclass stack { int minn; int size; public: stack() { minn = 99999; size = -1; } vector<pair<int, int> > arr; int GetLastElement(); int RemoveLastElement(); int AddElement(int element); int GetMin();}; // utility function for adding a new elementint stack::AddElement(int element){ if (size > MAXX) { cout << \"stack overflow, max size reached!\\n\"; return 0; } if (element < minn) minn = element; arr.push_back(make_pair(element, minn)); size++; return 1;} // utility function for returning last element of stackint stack::GetLastElement(){ if (size == -1) { cout << \"No elements in stack\\n\"; return 0; } return arr[size].first;} // utility function for removing last element successfully;int stack::RemoveLastElement(){ if (size == -1) { cout << \"stack empty!!!\\n\"; return 0; } // updating minimum element if (size > 0 && arr[size - 1].second > arr[size].second) { minn = arr[size - 1].second; } arr.pop_back(); size -= 1; return 1;} // utility function for returning min element till now;int stack::GetMin(){ if (size == -1) { cout << \"stack empty!!\\n\"; return 0; } return arr[size].second;} // Driver codeint main(){ stack s; int success = s.AddElement(5); if (success == 1) cout << \"5 inserted successfully\\n\"; success = s.AddElement(7); if (success == 1) cout << \"7 inserted successfully\\n\"; success = s.AddElement(3); if (success == 1) cout << \"3 inserted successfully\\n\"; int min1 = s.GetMin(); cout << \"min element :: \" << min1 << endl; success = s.RemoveLastElement(); if (success == 1) cout << \"removed successfully\\n\"; success = s.AddElement(2); if (success == 1) cout << \"2 inserted successfully\\n\"; success = s.AddElement(9); if (success == 1) cout << \"9 inserted successfully\\n\"; int last = s.GetLastElement(); cout << \"Last element :: \" << last << endl; success = s.AddElement(0); if (success == 1) cout << \"0 inserted successfully\\n\"; min1 = s.GetMin(); cout << \"min element :: \" << min1 << endl; success = s.RemoveLastElement(); if (success == 1) cout << \"removed successfully\\n\"; success = s.AddElement(11); if (success == 1) cout << \"11 inserted successfully\\n\"; min1 = s.GetMin(); cout << \"min element :: \" << min1 << endl; return 0;}",
"e": 3104,
"s": 439,
"text": null
},
{
"code": "// program to demonstrate customized data structure// which supports functions in O(1)import java.util.ArrayList;public class Gfg{ // class Pair static class Pair{ int element; int minElement; public Pair(int element, int minElement) { this.element = element; this.minElement = minElement; } } int min; ArrayList<Pair> stack = new ArrayList<>(); public Gfg() { this.min = Integer.MAX_VALUE; } // utility function for adding a new element void addElement(int x) { if(stack.size() == 0 || x < min) { min=x; } Pair pair = new Pair(x,min); stack.add(pair); System.out.println(x + \" inserted successfully\"); } // utility function for returning last element of stack int getLastElement() { if (stack.size() == 0) { System.out.println(\"UnderFlow Error\"); return -1; } else { return stack.get(stack.size() - 1).element; } } // utility function for removing last element successfully; void removeLastElement() { if (stack.size() == 0) { System.out.println(\"UnderFlow Error\"); } else if (stack.size() > 1) { min=stack.get(stack.size() - 2).minElement; } else { min=Integer.MAX_VALUE; } stack.remove(stack.size() - 1); System.out.println(\"removed successfully\"); } // utility function for returning min element till now; int getMin() { if (stack.size() == 0) { System.out.println(\"UnderFlow Error\"); return -1; } return stack.get(stack.size() - 1).minElement; } // Driver Code public static void main(String[] args) { Gfg newStack = new Gfg(); newStack.addElement(5); newStack.addElement(7); newStack.addElement(3); System.out.println(\"min element :: \"+newStack.getMin()); newStack.removeLastElement(); newStack.addElement(2); newStack.addElement(9); System.out.println(\"last element :: \"+newStack.getLastElement()); newStack.addElement(0); System.out.println(\"min element :: \"+newStack.getMin()); newStack.removeLastElement(); newStack.addElement(11); System.out.println(\"min element :: \"+newStack.getMin()); }} // This code is contributed by AkashYadav4.",
"e": 5280,
"s": 3104,
"text": null
},
{
"code": "# Program to demonstrate customized data structure# which supports functions in O(1)import sys stack = []Min = sys.maxsize # Utility function for adding a new elementdef addElement(x): global Min, stack if (len(stack) == 0 or x < Min): Min = x pair = [x, Min] stack.append(pair) print(x, \"inserted successfully\") # Utility function for returning last# element of stackdef getLastElement(): global Min, stack if (len(stack) == 0): print(\"UnderFlow Error\") return -1 else: return stack[-1][0] # Utility function for removing last# element successfully;def removeLastElement(): global Min, stack if (len(stack) == 0): print(\"UnderFlow Error\") elif (len(stack) > 1): Min = stack[-2][1] else: Min = sys.maxsize stack.pop() print(\"removed successfully\") # Utility function for returning min# element till now;def getMin(): global Min, stack if (len(stack) == 0): print(\"UnderFlow Error\") return -1 return stack[-1][1] # Driver codeaddElement(5)addElement(7)addElement(3)print(\"min element ::\", getMin())removeLastElement()addElement(2)addElement(9)print(\"Last element ::\", getLastElement())addElement(0)print(\"min element ::\", getMin())removeLastElement()addElement(11)print(\"min element ::\", getMin()) # This code is contributed by mukesh07",
"e": 6669,
"s": 5280,
"text": null
},
{
"code": "// program to demonstrate customized data structure// which supports functions in O(1)using System;using System.Collections.Generic;class GFG { static List<Tuple<int,int>> stack = new List<Tuple<int,int>>(); static int min = Int32.MaxValue; // utility function for adding a new element static void addElement(int x) { if(stack.Count == 0 || x < min) { min=x; } Tuple<int,int> pair = new Tuple<int,int>(x,min); stack.Add(pair); Console.WriteLine(x + \" inserted successfully\"); } // utility function for returning last element of stack static int getLastElement() { if (stack.Count == 0) { Console.WriteLine(\"UnderFlow Error\"); return -1; } else { return stack[stack.Count - 1].Item1; } } // utility function for removing last element successfully; static void removeLastElement() { if (stack.Count == 0) { Console.WriteLine(\"UnderFlow Error\"); } else if (stack.Count > 1) { min=stack[stack.Count - 2].Item2; } else { min=Int32.MaxValue; } stack.RemoveAt(stack.Count - 1); Console.WriteLine(\"removed successfully\"); } // utility function for returning min element till now; static int getMin() { if (stack.Count == 0) { Console.WriteLine(\"UnderFlow Error\"); return -1; } return stack[stack.Count - 1].Item2; } static void Main() { addElement(5); addElement(7); addElement(3); Console.WriteLine(\"min element :: \"+getMin()); removeLastElement(); addElement(2); addElement(9); Console.WriteLine(\"Last element :: \"+getLastElement()); addElement(0); Console.WriteLine(\"min element :: \"+getMin()); removeLastElement(); addElement(11); Console.WriteLine(\"min element :: \"+getMin()); }} // This code is contributed by divyeshrabadiya07.",
"e": 8495,
"s": 6669,
"text": null
},
{
"code": "<script> // program to demonstrate customized data structure // which supports functions in O(1) let min; let stack = []; min = Number.MAX_VALUE // utility function for adding a new element function addElement(x) { if(stack.length == 0 || x < min) { min=x; } let pair = [x,min]; stack.push(pair); document.write(x + \" inserted successfully\" + \"</br>\"); } // utility function for returning last element of stack function getLastElement() { if (stack.length == 0) { document.write(\"UnderFlow Error\" + \"</br>\"); return -1; } else { return stack[stack.length - 1][0]; } } // utility function for removing last element successfully; function removeLastElement() { if (stack.length == 0) { document.write(\"UnderFlow Error\" + \"</br>\"); } else if (stack.length > 1) { min=stack[stack.length - 2][1]; } else { min=Number.MAX_VALUE; } stack.pop(); document.write(\"removed successfully\" + \"</br>\"); } // utility function for returning min element till now; function getMin() { if (stack.length == 0) { document.write(\"UnderFlow Error\" + \"</br>\"); return -1; } return stack[stack.length - 1][1]; } addElement(5); addElement(7); addElement(3); document.write(\"min element :: \"+getMin() + \"</br>\"); removeLastElement(); addElement(2); addElement(9); document.write(\"Last element :: \"+getLastElement() + \"</br>\"); addElement(0); document.write(\"min element :: \"+getMin() + \"</br>\"); removeLastElement(); addElement(11); document.write(\"min element :: \"+getMin() + \"</br>\"); // This code is contributed by rameshtravel07.</script>",
"e": 10334,
"s": 8495,
"text": null
},
{
"code": null,
"e": 10343,
"s": 10334,
"text": "Output: "
},
{
"code": null,
"e": 10626,
"s": 10343,
"text": "5 inserted successfully\n7 inserted successfully\n3 inserted successfully\nmin element :: 3\nremoved successfully\n2 inserted successfully\n9 inserted successfully\nLast element :: 9\n0 inserted successfully\nmin element :: 0\nremoved successfully\n11 inserted successfully\nmin element :: 2"
},
{
"code": null,
"e": 11092,
"s": 10626,
"text": "Time complexity : Each function runs in O(1)This article is contributed by Mandeep Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 11105,
"s": 11092,
"text": "AakashYadav4"
},
{
"code": null,
"e": 11120,
"s": 11105,
"text": "rameshtravel07"
},
{
"code": null,
"e": 11129,
"s": 11120,
"text": "mukesh07"
},
{
"code": null,
"e": 11147,
"s": 11129,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 11154,
"s": 11147,
"text": "Amazon"
},
{
"code": null,
"e": 11160,
"s": 11154,
"text": "Stack"
},
{
"code": null,
"e": 11167,
"s": 11160,
"text": "Amazon"
},
{
"code": null,
"e": 11173,
"s": 11167,
"text": "Stack"
},
{
"code": null,
"e": 11271,
"s": 11173,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 11287,
"s": 11271,
"text": "Stack in Python"
},
{
"code": null,
"e": 11307,
"s": 11287,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 11382,
"s": 11307,
"text": "Check for Balanced Brackets in an expression (well-formedness) using Stack"
},
{
"code": null,
"e": 11414,
"s": 11382,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 11447,
"s": 11414,
"text": "Stack | Set 2 (Infix to Postfix)"
},
{
"code": null,
"e": 11488,
"s": 11447,
"text": "Inorder Tree Traversal without Recursion"
},
{
"code": null,
"e": 11515,
"s": 11488,
"text": "Program for Tower of Hanoi"
},
{
"code": null,
"e": 11579,
"s": 11515,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 11607,
"s": 11579,
"text": "Merge Overlapping Intervals"
}
] |
Working with Docker Swarm | If you are working on a microservice architecture, where you need to work on different project components on different machines and create a master slave architecture where the master nodes control the slave nodes, deploying your project through Docker Swarm might save you a lot of time, effort and resources.
Docker Swarm is basically a cluster of physical or virtual machines called nodes which run docker containers separately and you can configure all these nodes to join a cluster managed by the master node called the swarm manager. It is an orchestration tool which allows you to manage multiple Docker Containers deployed on different machines. This type of architecture helps you to manage your resources properly and work efficiently. It helps in automatic load balancing while allowing you to leverage the power of Docker Containers and guarantees high service availability.
In general, there are two service modes available for any Docker Swarm. One is Replicated Service mode which allows you to specify the number of replicable tasks to the manager which assigns them to all the available nodes. The other one is the Global Service mode which allocates a sequence of tasks to different nodes based on their availability, ability and requirements.
In this article, we are going to discuss some of the most basic and important Docker Swarm Commands that will help you to kickstart your Swarm project.
Create 6 Docker Machines with the hyperv driver with one of them working as the Swarm manager while the other 5 working as the worker nodes.
sudo docker-machine create −−driver hyperv manager
sudo docker−machine create −−driver hyperv worker1
sudo docker−machine create −−driver hyperv worker2
sudo docker−machine create −−driver hyperv worker3
sudo docker−machine create −−driver hyperv worker4
sudo docker−machine create −−driver hyperv worker5
Use the ls command to confirm whether the machines have been created or not.
sudo docker−machine ls
Copy the manager’s IP address.
sudo docker−machine ip manager
SSH into the manager node.
sudo docker−machine ssh manager
Now, you are inside the manager prompt. To initialize the swarm, perform these steps.
docker swarm init −−advertise−addr <manager−ip>
Check the Docker Swarm status inside the manager node using the following command.
docker node ls
It displays that currently there is only one leader node called manager.
Inside the SSH session of manager node, to find out the command and token to join as a Worker or Manager node, you can use these commands.
docker swarm join−token worker
docker swarm join−token manager
The above commands outputs the specific commands that you would require to either join the cluster as a worker or a manager.
We will now see how to add worker nodes to the cluster under manager.
While keeping the manager SSH session open, fire up another terminal and start the worker1 SSH session using the following command.
sudo docker−machine ssh worker1
Once you are inside the SSH session of worker1, copy the command that was generated for joining in as a worker from the manager terminal and paste it inside the SSH session of the worker1. After successful execution, you will find the message “This node joined the swarm as a worker” being displayed. Do the same thing for the other 4 workers as well. After you have created the cluster with 1 manager and 5 workers, you can confirm the same by typing the following command inside the SSH session of the manager
docker node ls
After creating the Swarm cluster, you are now ready to launch a service. We only need to tell the manager node that we are going to launch a service (running containers) and the manager automatically assigns the distribution, execution of commands and scheduling of the containers. In this example, we will launch 4 replicas of the nginx container and expose it to port 80.
Inside the manager SSH session, execute the following command.
docker service create −−replicas 5 −p 80:80 −−name web nginx
The orchestration layer is now working. After waiting for some time, you can execute this command inside the manager SSH session to confirm the same.
docker service ps web
To access the service, you can execute the worker or the manager ip inside the browser of any of the worker or manager nodes no matter if it has a container running or not.
Currently, you have 5 containers of nginx running in your swarm cluster. To scale up to 7 containers, use this command inside the manager SSH session.
docker service scale web=7
Confirm the same using this command.
docker service ps web
To conclude, in this article we discussed how to create and deploy a Docker Swarm Cluster by creating different virtual machines and assigning manager and worker roles to the nodes. We also discussed how to create and launch an nginx service and scaled it up and tried to access it using any of the nodes. If you are a Docker developer or you are using Docker in your microservice project, it is sort of mandatory that you have a good grasp on Swarm clusters in order to scale up your project and perform efficient utilization of resources. Creating, launching, deploying and maintaining Docker Swarm cluster nodes is very essential in order to contribute to successfully maintaining a large project and distributed project. | [
{
"code": null,
"e": 1498,
"s": 1187,
"text": "If you are working on a microservice architecture, where you need to work on different project components on different machines and create a master slave architecture where the master nodes control the slave nodes, deploying your project through Docker Swarm might save you a lot of time, effort and resources."
},
{
"code": null,
"e": 2074,
"s": 1498,
"text": "Docker Swarm is basically a cluster of physical or virtual machines called nodes which run docker containers separately and you can configure all these nodes to join a cluster managed by the master node called the swarm manager. It is an orchestration tool which allows you to manage multiple Docker Containers deployed on different machines. This type of architecture helps you to manage your resources properly and work efficiently. It helps in automatic load balancing while allowing you to leverage the power of Docker Containers and guarantees high service availability."
},
{
"code": null,
"e": 2449,
"s": 2074,
"text": "In general, there are two service modes available for any Docker Swarm. One is Replicated Service mode which allows you to specify the number of replicable tasks to the manager which assigns them to all the available nodes. The other one is the Global Service mode which allocates a sequence of tasks to different nodes based on their availability, ability and requirements."
},
{
"code": null,
"e": 2601,
"s": 2449,
"text": "In this article, we are going to discuss some of the most basic and important Docker Swarm Commands that will help you to kickstart your Swarm project."
},
{
"code": null,
"e": 2742,
"s": 2601,
"text": "Create 6 Docker Machines with the hyperv driver with one of them working as the Swarm manager while the other 5 working as the worker nodes."
},
{
"code": null,
"e": 3049,
"s": 2742,
"text": "sudo docker-machine create −−driver hyperv manager\n\nsudo docker−machine create −−driver hyperv worker1\nsudo docker−machine create −−driver hyperv worker2\nsudo docker−machine create −−driver hyperv worker3\nsudo docker−machine create −−driver hyperv worker4\nsudo docker−machine create −−driver hyperv worker5"
},
{
"code": null,
"e": 3126,
"s": 3049,
"text": "Use the ls command to confirm whether the machines have been created or not."
},
{
"code": null,
"e": 3149,
"s": 3126,
"text": "sudo docker−machine ls"
},
{
"code": null,
"e": 3180,
"s": 3149,
"text": "Copy the manager’s IP address."
},
{
"code": null,
"e": 3211,
"s": 3180,
"text": "sudo docker−machine ip manager"
},
{
"code": null,
"e": 3238,
"s": 3211,
"text": "SSH into the manager node."
},
{
"code": null,
"e": 3271,
"s": 3238,
"text": "sudo docker−machine ssh manager\n"
},
{
"code": null,
"e": 3357,
"s": 3271,
"text": "Now, you are inside the manager prompt. To initialize the swarm, perform these steps."
},
{
"code": null,
"e": 3405,
"s": 3357,
"text": "docker swarm init −−advertise−addr <manager−ip>"
},
{
"code": null,
"e": 3488,
"s": 3405,
"text": "Check the Docker Swarm status inside the manager node using the following command."
},
{
"code": null,
"e": 3503,
"s": 3488,
"text": "docker node ls"
},
{
"code": null,
"e": 3576,
"s": 3503,
"text": "It displays that currently there is only one leader node called manager."
},
{
"code": null,
"e": 3715,
"s": 3576,
"text": "Inside the SSH session of manager node, to find out the command and token to join as a Worker or Manager node, you can use these commands."
},
{
"code": null,
"e": 3778,
"s": 3715,
"text": "docker swarm join−token worker\ndocker swarm join−token manager"
},
{
"code": null,
"e": 3903,
"s": 3778,
"text": "The above commands outputs the specific commands that you would require to either join the cluster as a worker or a manager."
},
{
"code": null,
"e": 3973,
"s": 3903,
"text": "We will now see how to add worker nodes to the cluster under manager."
},
{
"code": null,
"e": 4105,
"s": 3973,
"text": "While keeping the manager SSH session open, fire up another terminal and start the worker1 SSH session using the following command."
},
{
"code": null,
"e": 4137,
"s": 4105,
"text": "sudo docker−machine ssh worker1"
},
{
"code": null,
"e": 4649,
"s": 4137,
"text": "Once you are inside the SSH session of worker1, copy the command that was generated for joining in as a worker from the manager terminal and paste it inside the SSH session of the worker1. After successful execution, you will find the message “This node joined the swarm as a worker” being displayed. Do the same thing for the other 4 workers as well. After you have created the cluster with 1 manager and 5 workers, you can confirm the same by typing the following command inside the SSH session of the manager"
},
{
"code": null,
"e": 4664,
"s": 4649,
"text": "docker node ls"
},
{
"code": null,
"e": 5038,
"s": 4664,
"text": "After creating the Swarm cluster, you are now ready to launch a service. We only need to tell the manager node that we are going to launch a service (running containers) and the manager automatically assigns the distribution, execution of commands and scheduling of the containers. In this example, we will launch 4 replicas of the nginx container and expose it to port 80."
},
{
"code": null,
"e": 5101,
"s": 5038,
"text": "Inside the manager SSH session, execute the following command."
},
{
"code": null,
"e": 5163,
"s": 5101,
"text": "docker service create −−replicas 5 −p 80:80 −−name web nginx\n"
},
{
"code": null,
"e": 5313,
"s": 5163,
"text": "The orchestration layer is now working. After waiting for some time, you can execute this command inside the manager SSH session to confirm the same."
},
{
"code": null,
"e": 5335,
"s": 5313,
"text": "docker service ps web"
},
{
"code": null,
"e": 5508,
"s": 5335,
"text": "To access the service, you can execute the worker or the manager ip inside the browser of any of the worker or manager nodes no matter if it has a container running or not."
},
{
"code": null,
"e": 5659,
"s": 5508,
"text": "Currently, you have 5 containers of nginx running in your swarm cluster. To scale up to 7 containers, use this command inside the manager SSH session."
},
{
"code": null,
"e": 5686,
"s": 5659,
"text": "docker service scale web=7"
},
{
"code": null,
"e": 5723,
"s": 5686,
"text": "Confirm the same using this command."
},
{
"code": null,
"e": 5745,
"s": 5723,
"text": "docker service ps web"
},
{
"code": null,
"e": 6470,
"s": 5745,
"text": "To conclude, in this article we discussed how to create and deploy a Docker Swarm Cluster by creating different virtual machines and assigning manager and worker roles to the nodes. We also discussed how to create and launch an nginx service and scaled it up and tried to access it using any of the nodes. If you are a Docker developer or you are using Docker in your microservice project, it is sort of mandatory that you have a good grasp on Swarm clusters in order to scale up your project and perform efficient utilization of resources. Creating, launching, deploying and maintaining Docker Swarm cluster nodes is very essential in order to contribute to successfully maintaining a large project and distributed project."
}
] |
Python | sympy.apart() method | 25 Jun, 2019
With the help of sympy.apart() method, we are able to do a partial fraction decomposition of a rational function and put it into a standard canonical form i.e p/q.
Syntax : sympy.apart()Return : Return the partial fraction decomposition of rational function.
Example #1 :In the given example, we can see that by using sympy.apart() method, we can do the partial fraction of rational function.
# import sympyfrom sympy import * x, y, z = symbols('x y z')gfg_exp = (x**2 + 2 * x + 1)/(x**2 + x) # Using sympy.apart() methodgfg_exp = apart(gfg_exp) print(gfg_exp)
Output :
1 + 1/x
Example #2 :
# import sympyfrom sympy import * x, y, z = symbols('x y z')gfg_exp = 1 / x + (3 * x / 2 - 2)/(x - 4) # Using sympy.apart() methodgfg_exp = apart(gfg_exp) print(gfg_exp)
Output :
3/2 + 4/(x – 4) + 1/x
SymPy
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
Python OOPs Concepts
Convert integer to string in Python
Introduction To PYTHON | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n25 Jun, 2019"
},
{
"code": null,
"e": 192,
"s": 28,
"text": "With the help of sympy.apart() method, we are able to do a partial fraction decomposition of a rational function and put it into a standard canonical form i.e p/q."
},
{
"code": null,
"e": 287,
"s": 192,
"text": "Syntax : sympy.apart()Return : Return the partial fraction decomposition of rational function."
},
{
"code": null,
"e": 421,
"s": 287,
"text": "Example #1 :In the given example, we can see that by using sympy.apart() method, we can do the partial fraction of rational function."
},
{
"code": "# import sympyfrom sympy import * x, y, z = symbols('x y z')gfg_exp = (x**2 + 2 * x + 1)/(x**2 + x) # Using sympy.apart() methodgfg_exp = apart(gfg_exp) print(gfg_exp)",
"e": 593,
"s": 421,
"text": null
},
{
"code": null,
"e": 602,
"s": 593,
"text": "Output :"
},
{
"code": null,
"e": 610,
"s": 602,
"text": "1 + 1/x"
},
{
"code": null,
"e": 623,
"s": 610,
"text": "Example #2 :"
},
{
"code": "# import sympyfrom sympy import * x, y, z = symbols('x y z')gfg_exp = 1 / x + (3 * x / 2 - 2)/(x - 4) # Using sympy.apart() methodgfg_exp = apart(gfg_exp) print(gfg_exp)",
"e": 797,
"s": 623,
"text": null
},
{
"code": null,
"e": 806,
"s": 797,
"text": "Output :"
},
{
"code": null,
"e": 828,
"s": 806,
"text": "3/2 + 4/(x – 4) + 1/x"
},
{
"code": null,
"e": 834,
"s": 828,
"text": "SymPy"
},
{
"code": null,
"e": 841,
"s": 834,
"text": "Python"
},
{
"code": null,
"e": 939,
"s": 841,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 957,
"s": 939,
"text": "Python Dictionary"
},
{
"code": null,
"e": 999,
"s": 957,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1021,
"s": 999,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1047,
"s": 1021,
"text": "Python String | replace()"
},
{
"code": null,
"e": 1079,
"s": 1047,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1108,
"s": 1079,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 1135,
"s": 1108,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1156,
"s": 1135,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1192,
"s": 1156,
"text": "Convert integer to string in Python"
}
] |
How to get coordinates from the contour in matplotlib? | To get coordinates from the contour in matplotlib, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Create lists of x, y and m with data points.
Use plt.contour(x, y, m) to create a contour plot with x, y and m data points.
Get the contour collections instance.
Get the path of the collections, and print the vertices or coordinates of the contour.
To display the figure, use show() method.
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
x = [1, 2, 3, 4]
y = [1, 2, 3, 4]
m = [[15, 14, 13, 12], [14, 12, 10, 8], [13, 10, 7, 4], [12, 8, 4, 0]]
cs = plt.contour(x, y, m)
for item in cs.collections:
for i in item.get_paths():
v = i.vertices
x = v[:, 0]
y = v[:, 1]
print(x, y)
plt.show()
It will produce the following output
In addition, it will print the coordinates of the contour on the terminal
[4.] [4.]
[4. 3.5] [3.5 4. ]
[4. 3.] [3. 4.]
[4. 3.33333333 3. 2.5 ] [2.5 3. 3.33333333 4. ]
[4. 3. 2.66666667 2. ] [2. 2.66666667 3. 4. ]
[4. 3. 2. 1.5] [1.5 2. 3. 4. ]
[4. 3. 2. 1.33333333 1. ] [1. 1.33333333 2. 3. 4. ]
[2. 1.] [1. 2.] | [
{
"code": null,
"e": 1272,
"s": 1187,
"text": "To get coordinates from the contour in matplotlib, we can take the following steps −"
},
{
"code": null,
"e": 1348,
"s": 1272,
"text": "Set the figure size and adjust the padding between and around the subplots."
},
{
"code": null,
"e": 1393,
"s": 1348,
"text": "Create lists of x, y and m with data points."
},
{
"code": null,
"e": 1472,
"s": 1393,
"text": "Use plt.contour(x, y, m) to create a contour plot with x, y and m data points."
},
{
"code": null,
"e": 1510,
"s": 1472,
"text": "Get the contour collections instance."
},
{
"code": null,
"e": 1597,
"s": 1510,
"text": "Get the path of the collections, and print the vertices or coordinates of the contour."
},
{
"code": null,
"e": 1639,
"s": 1597,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 2037,
"s": 1639,
"text": "import matplotlib.pyplot as plt\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\nx = [1, 2, 3, 4]\ny = [1, 2, 3, 4]\nm = [[15, 14, 13, 12], [14, 12, 10, 8], [13, 10, 7, 4], [12, 8, 4, 0]]\n\ncs = plt.contour(x, y, m)\n\nfor item in cs.collections:\n for i in item.get_paths():\n v = i.vertices\n x = v[:, 0]\n y = v[:, 1]\n print(x, y)\nplt.show()"
},
{
"code": null,
"e": 2074,
"s": 2037,
"text": "It will produce the following output"
},
{
"code": null,
"e": 2148,
"s": 2074,
"text": "In addition, it will print the coordinates of the contour on the terminal"
},
{
"code": null,
"e": 2426,
"s": 2148,
"text": "[4.] [4.]\n[4. 3.5] [3.5 4. ]\n[4. 3.] [3. 4.]\n[4. 3.33333333 3. 2.5 ] [2.5 3. 3.33333333 4. ]\n[4. 3. 2.66666667 2. ] [2. 2.66666667 3. 4. ]\n[4. 3. 2. 1.5] [1.5 2. 3. 4. ]\n[4. 3. 2. 1.33333333 1. ] [1. 1.33333333 2. 3. 4. ]\n[2. 1.] [1. 2.]"
}
] |
Replace every element of the array by its next element | 11 May, 2022
Given an array arr, the task is to replace each element of the array with the element that appears after it and replace the last element with -1.Examples:
Input: arr[] = {5, 1, 3, 2, 4} Output: 1 3 2 4 -1Input: arr[] = {6, 8, 32, 12, 14, 10, 25 } Output: 8 32 12 14 10 25 -1
Approach: Traverse the array from 0 to n-2 and update arr[i] = arr[i+1]. In the end set a[n-1] = -1 and print the contents of the updated array.Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
C
// C++ program to replace every element of the array// with the element that appears after it#include <bits/stdc++.h>using namespace std; // Function to print the array after replacing every element// of the array with the element that appears after itvoid updateArray(int arr[], int n){ // Update array for (int i = 0; i <= n - 2; i++) arr[i] = arr[i + 1]; // Change the last element to -1 arr[n - 1] = -1; // Print the updated array for (int i = 0; i < n; i++) cout << arr[i] << " ";} // Driver programint main(){ int arr[] = { 5, 1, 3, 2, 4 }; int N = sizeof(arr) / sizeof(arr[0]); updateArray(arr, N); return 0;}
// Java program to replace every element// of the array with the element that// appears after itclass GFG{ // Function to print the array after// replacing every element of the array// with the element that appears after itstatic void updateArray(int arr[], int n){ // Update array for (int i = 0; i <= n - 2; i++) arr[i] = arr[i + 1]; // Change the last element to -1 arr[n - 1] = -1; // Print the updated array for (int i = 0; i < n; i++) System.out.print(arr[i] + " ");} // Driver Codepublic static void main(String []args){ int arr[] = { 5, 1, 3, 2, 4 } ; int N = arr.length ; updateArray(arr, N);}} // This code is contributed by Ryuga
# Python3 program to replace every# element of the array with the# element that appears after it # Function to print the array after# replacing every element of the# array with the element that appears# after itdef updateArray(arr, n): # Update array for i in range (n - 1): arr[i] = arr[i + 1] # Change the last element to -1 arr[n - 1] = -1 # Print the updated array for i in range( n): print (arr[i], end = " ") # Driver Codeif __name__ == "__main__": arr = [ 5, 1, 3, 2, 4 ] N = len(arr) updateArray(arr, N) # This code is contributed# by ChitraNayal
// C# program to replace every element// of the array with the element that// appears after itusing System; class GFG{ // Function to print the array after// replacing every element of the array// with the element that appears after itstatic void updateArray(int[] arr, int n){ // Update array for (int i = 0; i <= n - 2; i++) arr[i] = arr[i + 1]; // Change the last element to -1 arr[n - 1] = -1; // Print the updated array for (int i = 0; i < n; i++) Console.Write(arr[i] + " ");} // Driver Codepublic static void Main(){ int[] arr = { 5, 1, 3, 2, 4 } ; int N = arr.Length ; updateArray(arr, N);}} // This code is contributed// by Akanksha Rai
<?php// PHP program to replace every element// of the array with the element that// appears after it // Function to print the array after// replacing every element of the// array with the element that appears// after itfunction updateArray(&$arr, $n){ // Update array for ($i = 0; $i <= $n - 2; $i++) $arr[$i] = $arr[$i + 1]; // Change the last element to -1 $arr[$n - 1] = -1; // Print the updated array for ($i = 0; $i < $n; $i++) { echo ($arr[$i]); echo (" "); }} // Driver Code$arr = array(5, 1, 3, 2, 4 );$N = sizeof($arr);updateArray($arr, $N); // This code is contributed// by Shivi_Aggarwal?>
<script> // Javascript program to replace every element of the array// with the element that appears after it // Function to print the array after replacing every element// of the array with the element that appears after itfunction updateArray(arr, n){ // Update array for (let i = 0; i <= n - 2; i++) arr[i] = arr[i + 1]; // Change the last element to -1 arr[n - 1] = -1; // Print the updated array for (let i = 0; i < n; i++) document.write(arr[i] + " ");} // Driver program let arr = [ 5, 1, 3, 2, 4 ]; let N = arr.length; updateArray(arr, N); //This code is contributed by Mayank Tyagi </script>
// C program to replace every element of the array// with the element that appears after it#include <stdio.h> // Function to print the array after replacing every element// of the array with the element that appears after itvoid updateArray(int arr[], int n){ // Update array for (int i = 0; i <= n - 2; i++) arr[i] = arr[i + 1]; // Change the last element to -1 arr[n - 1] = -1; // Print the updated array for (int i = 0; i < n; i++) printf("%d ",arr[i]);} // Driver programint main(){ int arr[] = { 5, 1, 3, 2, 4 }; int N = sizeof(arr) / sizeof(arr[0]); updateArray(arr, N); return 0;}
1 3 2 4 -1
Time Complexity : O(n)Auxiliary Space: O(1)
ankthon
Akanksha_Rai
ukasp
Shivi_Aggarwal
VishalBachchas
mayanktyagi1709
pankajsharmagfg
kothavvsaakash
Technical Scripter 2018
Arrays
C++ Programs
Data Structures
Technical Scripter
Data Structures
Arrays
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
Header files in C/C++ and its uses
Sorting a Map by value in C++ STL
Program to print ASCII Value of a character
How to return multiple values from a function in C or C++?
Shallow Copy and Deep Copy in C++ | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 May, 2022"
},
{
"code": null,
"e": 185,
"s": 28,
"text": "Given an array arr, the task is to replace each element of the array with the element that appears after it and replace the last element with -1.Examples: "
},
{
"code": null,
"e": 307,
"s": 185,
"text": "Input: arr[] = {5, 1, 3, 2, 4} Output: 1 3 2 4 -1Input: arr[] = {6, 8, 32, 12, 14, 10, 25 } Output: 8 32 12 14 10 25 -1 "
},
{
"code": null,
"e": 506,
"s": 309,
"text": "Approach: Traverse the array from 0 to n-2 and update arr[i] = arr[i+1]. In the end set a[n-1] = -1 and print the contents of the updated array.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 510,
"s": 506,
"text": "C++"
},
{
"code": null,
"e": 515,
"s": 510,
"text": "Java"
},
{
"code": null,
"e": 523,
"s": 515,
"text": "Python3"
},
{
"code": null,
"e": 526,
"s": 523,
"text": "C#"
},
{
"code": null,
"e": 530,
"s": 526,
"text": "PHP"
},
{
"code": null,
"e": 541,
"s": 530,
"text": "Javascript"
},
{
"code": null,
"e": 543,
"s": 541,
"text": "C"
},
{
"code": "// C++ program to replace every element of the array// with the element that appears after it#include <bits/stdc++.h>using namespace std; // Function to print the array after replacing every element// of the array with the element that appears after itvoid updateArray(int arr[], int n){ // Update array for (int i = 0; i <= n - 2; i++) arr[i] = arr[i + 1]; // Change the last element to -1 arr[n - 1] = -1; // Print the updated array for (int i = 0; i < n; i++) cout << arr[i] << \" \";} // Driver programint main(){ int arr[] = { 5, 1, 3, 2, 4 }; int N = sizeof(arr) / sizeof(arr[0]); updateArray(arr, N); return 0;}",
"e": 1206,
"s": 543,
"text": null
},
{
"code": "// Java program to replace every element// of the array with the element that// appears after itclass GFG{ // Function to print the array after// replacing every element of the array// with the element that appears after itstatic void updateArray(int arr[], int n){ // Update array for (int i = 0; i <= n - 2; i++) arr[i] = arr[i + 1]; // Change the last element to -1 arr[n - 1] = -1; // Print the updated array for (int i = 0; i < n; i++) System.out.print(arr[i] + \" \");} // Driver Codepublic static void main(String []args){ int arr[] = { 5, 1, 3, 2, 4 } ; int N = arr.length ; updateArray(arr, N);}} // This code is contributed by Ryuga",
"e": 1890,
"s": 1206,
"text": null
},
{
"code": "# Python3 program to replace every# element of the array with the# element that appears after it # Function to print the array after# replacing every element of the# array with the element that appears# after itdef updateArray(arr, n): # Update array for i in range (n - 1): arr[i] = arr[i + 1] # Change the last element to -1 arr[n - 1] = -1 # Print the updated array for i in range( n): print (arr[i], end = \" \") # Driver Codeif __name__ == \"__main__\": arr = [ 5, 1, 3, 2, 4 ] N = len(arr) updateArray(arr, N) # This code is contributed# by ChitraNayal",
"e": 2490,
"s": 1890,
"text": null
},
{
"code": "// C# program to replace every element// of the array with the element that// appears after itusing System; class GFG{ // Function to print the array after// replacing every element of the array// with the element that appears after itstatic void updateArray(int[] arr, int n){ // Update array for (int i = 0; i <= n - 2; i++) arr[i] = arr[i + 1]; // Change the last element to -1 arr[n - 1] = -1; // Print the updated array for (int i = 0; i < n; i++) Console.Write(arr[i] + \" \");} // Driver Codepublic static void Main(){ int[] arr = { 5, 1, 3, 2, 4 } ; int N = arr.Length ; updateArray(arr, N);}} // This code is contributed// by Akanksha Rai",
"e": 3179,
"s": 2490,
"text": null
},
{
"code": "<?php// PHP program to replace every element// of the array with the element that// appears after it // Function to print the array after// replacing every element of the// array with the element that appears// after itfunction updateArray(&$arr, $n){ // Update array for ($i = 0; $i <= $n - 2; $i++) $arr[$i] = $arr[$i + 1]; // Change the last element to -1 $arr[$n - 1] = -1; // Print the updated array for ($i = 0; $i < $n; $i++) { echo ($arr[$i]); echo (\" \"); }} // Driver Code$arr = array(5, 1, 3, 2, 4 );$N = sizeof($arr);updateArray($arr, $N); // This code is contributed// by Shivi_Aggarwal?>",
"e": 3831,
"s": 3179,
"text": null
},
{
"code": "<script> // Javascript program to replace every element of the array// with the element that appears after it // Function to print the array after replacing every element// of the array with the element that appears after itfunction updateArray(arr, n){ // Update array for (let i = 0; i <= n - 2; i++) arr[i] = arr[i + 1]; // Change the last element to -1 arr[n - 1] = -1; // Print the updated array for (let i = 0; i < n; i++) document.write(arr[i] + \" \");} // Driver program let arr = [ 5, 1, 3, 2, 4 ]; let N = arr.length; updateArray(arr, N); //This code is contributed by Mayank Tyagi </script>",
"e": 4476,
"s": 3831,
"text": null
},
{
"code": "// C program to replace every element of the array// with the element that appears after it#include <stdio.h> // Function to print the array after replacing every element// of the array with the element that appears after itvoid updateArray(int arr[], int n){ // Update array for (int i = 0; i <= n - 2; i++) arr[i] = arr[i + 1]; // Change the last element to -1 arr[n - 1] = -1; // Print the updated array for (int i = 0; i < n; i++) printf(\"%d \",arr[i]);} // Driver programint main(){ int arr[] = { 5, 1, 3, 2, 4 }; int N = sizeof(arr) / sizeof(arr[0]); updateArray(arr, N); return 0;}",
"e": 5110,
"s": 4476,
"text": null
},
{
"code": null,
"e": 5121,
"s": 5110,
"text": "1 3 2 4 -1"
},
{
"code": null,
"e": 5168,
"s": 5123,
"text": "Time Complexity : O(n)Auxiliary Space: O(1) "
},
{
"code": null,
"e": 5176,
"s": 5168,
"text": "ankthon"
},
{
"code": null,
"e": 5189,
"s": 5176,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 5195,
"s": 5189,
"text": "ukasp"
},
{
"code": null,
"e": 5210,
"s": 5195,
"text": "Shivi_Aggarwal"
},
{
"code": null,
"e": 5225,
"s": 5210,
"text": "VishalBachchas"
},
{
"code": null,
"e": 5241,
"s": 5225,
"text": "mayanktyagi1709"
},
{
"code": null,
"e": 5257,
"s": 5241,
"text": "pankajsharmagfg"
},
{
"code": null,
"e": 5272,
"s": 5257,
"text": "kothavvsaakash"
},
{
"code": null,
"e": 5296,
"s": 5272,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 5303,
"s": 5296,
"text": "Arrays"
},
{
"code": null,
"e": 5316,
"s": 5303,
"text": "C++ Programs"
},
{
"code": null,
"e": 5332,
"s": 5316,
"text": "Data Structures"
},
{
"code": null,
"e": 5351,
"s": 5332,
"text": "Technical Scripter"
},
{
"code": null,
"e": 5367,
"s": 5351,
"text": "Data Structures"
},
{
"code": null,
"e": 5374,
"s": 5367,
"text": "Arrays"
},
{
"code": null,
"e": 5472,
"s": 5374,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5540,
"s": 5472,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 5584,
"s": 5540,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 5616,
"s": 5584,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 5664,
"s": 5616,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 5678,
"s": 5664,
"text": "Linear Search"
},
{
"code": null,
"e": 5713,
"s": 5678,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 5747,
"s": 5713,
"text": "Sorting a Map by value in C++ STL"
},
{
"code": null,
"e": 5791,
"s": 5747,
"text": "Program to print ASCII Value of a character"
},
{
"code": null,
"e": 5850,
"s": 5791,
"text": "How to return multiple values from a function in C or C++?"
}
] |
sympy.integrals.transforms.inverse_fourier_transform() in python | 10 Jul, 2020
With the help of inverse_fourier_transform() method, we can compute the inverse fourier transformation and return the unevaluated function.
Inverse Fourier Transformation
Syntax : inverse_fourier_transform(F, k, x, **hints)
Return : Return the unevaluated function.
Example #1 :
In this example we can see that by using inverse_fourier_transform() method, we are able to compute the inverse fourier transformation which return the unevaluated function by using this method.
Python3
# import inverse_fourier_transformfrom sympy import inverse_fourier_transform, exp, sqrt, pifrom sympy.abc import x, k # Using inverse_fourier_transform()gfg = inverse_fourier_transform(sqrt(pi)*exp(-(pi * k)**2), k, x) print(gfg)
Output :
exp(-x**2)
Example #2 :
Python3
# import inverse_fourier_transformfrom sympy import inverse_fourier_transform, exp, sqrt, pifrom sympy.abc import x, k # Using inverse_fourier_transform()gfg = inverse_fourier_transform(sqrt(pi)*exp(-(pi * k)**2), k, 4) print(gfg)
Output :
exp(-16)
Python SymPy-Stats
SymPy
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
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Convert integer to string in Python
How to drop one or multiple columns in Pandas Dataframe | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n10 Jul, 2020"
},
{
"code": null,
"e": 168,
"s": 28,
"text": "With the help of inverse_fourier_transform() method, we can compute the inverse fourier transformation and return the unevaluated function."
},
{
"code": null,
"e": 199,
"s": 168,
"text": "Inverse Fourier Transformation"
},
{
"code": null,
"e": 253,
"s": 199,
"text": "Syntax : inverse_fourier_transform(F, k, x, **hints)"
},
{
"code": null,
"e": 295,
"s": 253,
"text": "Return : Return the unevaluated function."
},
{
"code": null,
"e": 308,
"s": 295,
"text": "Example #1 :"
},
{
"code": null,
"e": 503,
"s": 308,
"text": "In this example we can see that by using inverse_fourier_transform() method, we are able to compute the inverse fourier transformation which return the unevaluated function by using this method."
},
{
"code": null,
"e": 511,
"s": 503,
"text": "Python3"
},
{
"code": "# import inverse_fourier_transformfrom sympy import inverse_fourier_transform, exp, sqrt, pifrom sympy.abc import x, k # Using inverse_fourier_transform()gfg = inverse_fourier_transform(sqrt(pi)*exp(-(pi * k)**2), k, x) print(gfg)",
"e": 744,
"s": 511,
"text": null
},
{
"code": null,
"e": 753,
"s": 744,
"text": "Output :"
},
{
"code": null,
"e": 764,
"s": 753,
"text": "exp(-x**2)"
},
{
"code": null,
"e": 777,
"s": 764,
"text": "Example #2 :"
},
{
"code": null,
"e": 785,
"s": 777,
"text": "Python3"
},
{
"code": "# import inverse_fourier_transformfrom sympy import inverse_fourier_transform, exp, sqrt, pifrom sympy.abc import x, k # Using inverse_fourier_transform()gfg = inverse_fourier_transform(sqrt(pi)*exp(-(pi * k)**2), k, 4) print(gfg)",
"e": 1018,
"s": 785,
"text": null
},
{
"code": null,
"e": 1027,
"s": 1018,
"text": "Output :"
},
{
"code": null,
"e": 1036,
"s": 1027,
"text": "exp(-16)"
},
{
"code": null,
"e": 1055,
"s": 1036,
"text": "Python SymPy-Stats"
},
{
"code": null,
"e": 1061,
"s": 1055,
"text": "SymPy"
},
{
"code": null,
"e": 1068,
"s": 1061,
"text": "Python"
},
{
"code": null,
"e": 1166,
"s": 1068,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1184,
"s": 1166,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1226,
"s": 1184,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1252,
"s": 1226,
"text": "Python String | replace()"
},
{
"code": null,
"e": 1284,
"s": 1252,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1313,
"s": 1284,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 1340,
"s": 1313,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1361,
"s": 1340,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1384,
"s": 1361,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1420,
"s": 1384,
"text": "Convert integer to string in Python"
}
] |
How to Create an Onboarding Screen in Android? | 11 Jul, 2021
Hello geeks, today we are going to learn that how we can add Onboarding Screen to our android application in the android studio so that we can provide a better user experience to the user of the application.
The onboarding screen can be understood as a virtual unboxing of an application. Users go through a series of screens which finally directs users to the application interface. Goals or purposes of Onboarding screen:
Welcomes user and excite them about application ahead.
Tell the features or functions of the application.
Allow users to register or log in.
Collect information about the interests of the user(for example – when we open the Spotify application for the first time it asks the user to select singers which he/she likes).
Here is the sample video of the onboarding screen which we are going to create in this article. Note that we are going to implement this project using the Java language.
Step 1: Create a new project
Open a new project.
We will be working on Empty Activity with language as Java. Leave all other options unchanged.
You can change the name of the project at your convenience.
There will be two default files named activity_main.xml and MainActivity.java.
If you don’t know how to create a new project in Android Studio then you can refer to How to Create/Start a New Project in Android Studio?
Step 2: Navigate to Build scripts -> build.gradle(module) file and add the following dependency in it
implementation 'com.ramotion.paperonboarding:paper-onboarding:1.1.3'
After adding this dependency click on sync now to save all the changes.
Step 3: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><!-- Here frame layout is used so that different fragments of our onboarding screen can be changed within the same layout--><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/frame_layout" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"></FrameLayout>
Step 4: Working with the MainActivity.java file
Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Java
import android.graphics.Color;import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity;import androidx.fragment.app.FragmentManager;import androidx.fragment.app.FragmentTransaction; import com.ramotion.paperonboarding.PaperOnboardingFragment;import com.ramotion.paperonboarding.PaperOnboardingPage; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { private FragmentManager fragmentManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); fragmentManager = getSupportFragmentManager(); // new instance is created and data is took from an // array list known as getDataonborading final PaperOnboardingFragment paperOnboardingFragment = PaperOnboardingFragment.newInstance(getDataforOnboarding()); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); // fragmentTransaction method is used // do all the transactions or changes // between different fragments fragmentTransaction.add(R.id.frame_layout, paperOnboardingFragment); // all the changes are committed fragmentTransaction.commit(); } private ArrayList<PaperOnboardingPage> getDataforOnboarding() { // the first string is to show the main title , // second is to show the message below the // title, then color of background is passed , // then the image to show on the screen is passed // and at last icon to navigate from one screen to other PaperOnboardingPage source = new PaperOnboardingPage("Gfg", "Welcome to GeeksForGeeks", Color.parseColor("#ffb174"),R.drawable.gfgimg, R.drawable.search); PaperOnboardingPage source1 = new PaperOnboardingPage("Practice", "Practice questions from all topics", Color.parseColor("#22eaaa"),R.drawable.practice_gfg, R.drawable.training); PaperOnboardingPage source2 = new PaperOnboardingPage("", " ", Color.parseColor("#ee5a5a"),R.drawable.gfg_contribute, R.drawable.contribution); // array list is used to store // data of onbaording screen ArrayList<PaperOnboardingPage> elements = new ArrayList<>(); // all the sources(data to show on screens) // are added to array list elements.add(source); elements.add(source1); elements.add(source2); return elements; }}
Congratulations, we have successfully made the Onboarding screen for our application. The final output is shown below.
Output:
Android
Java
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Add Views Dynamically and Store Data in Arraylist in Android?
Android SDK and it's Components
Flutter - Custom Bottom Navigation Bar
How to Communicate Between Fragments in Android?
Retrofit with Kotlin Coroutine in Android
Arrays in Java
Arrays.sort() in Java with examples
Reverse a string in Java
Split() String method in Java with examples
Object Oriented Programming (OOPs) Concept in Java | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Jul, 2021"
},
{
"code": null,
"e": 236,
"s": 28,
"text": "Hello geeks, today we are going to learn that how we can add Onboarding Screen to our android application in the android studio so that we can provide a better user experience to the user of the application."
},
{
"code": null,
"e": 452,
"s": 236,
"text": "The onboarding screen can be understood as a virtual unboxing of an application. Users go through a series of screens which finally directs users to the application interface. Goals or purposes of Onboarding screen:"
},
{
"code": null,
"e": 507,
"s": 452,
"text": "Welcomes user and excite them about application ahead."
},
{
"code": null,
"e": 558,
"s": 507,
"text": "Tell the features or functions of the application."
},
{
"code": null,
"e": 593,
"s": 558,
"text": "Allow users to register or log in."
},
{
"code": null,
"e": 771,
"s": 593,
"text": "Collect information about the interests of the user(for example – when we open the Spotify application for the first time it asks the user to select singers which he/she likes)."
},
{
"code": null,
"e": 942,
"s": 771,
"text": "Here is the sample video of the onboarding screen which we are going to create in this article. Note that we are going to implement this project using the Java language. "
},
{
"code": null,
"e": 971,
"s": 942,
"text": "Step 1: Create a new project"
},
{
"code": null,
"e": 991,
"s": 971,
"text": "Open a new project."
},
{
"code": null,
"e": 1086,
"s": 991,
"text": "We will be working on Empty Activity with language as Java. Leave all other options unchanged."
},
{
"code": null,
"e": 1146,
"s": 1086,
"text": "You can change the name of the project at your convenience."
},
{
"code": null,
"e": 1225,
"s": 1146,
"text": "There will be two default files named activity_main.xml and MainActivity.java."
},
{
"code": null,
"e": 1366,
"s": 1225,
"text": "If you don’t know how to create a new project in Android Studio then you can refer to How to Create/Start a New Project in Android Studio? "
},
{
"code": null,
"e": 1468,
"s": 1366,
"text": "Step 2: Navigate to Build scripts -> build.gradle(module) file and add the following dependency in it"
},
{
"code": null,
"e": 1537,
"s": 1468,
"text": "implementation 'com.ramotion.paperonboarding:paper-onboarding:1.1.3'"
},
{
"code": null,
"e": 1609,
"s": 1537,
"text": "After adding this dependency click on sync now to save all the changes."
},
{
"code": null,
"e": 1657,
"s": 1609,
"text": "Step 3: Working with the activity_main.xml file"
},
{
"code": null,
"e": 1800,
"s": 1657,
"text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. "
},
{
"code": null,
"e": 1804,
"s": 1800,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><!-- Here frame layout is used so that different fragments of our onboarding screen can be changed within the same layout--><FrameLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:id=\"@+id/frame_layout\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"></FrameLayout>",
"e": 2261,
"s": 1804,
"text": null
},
{
"code": null,
"e": 2309,
"s": 2261,
"text": "Step 4: Working with the MainActivity.java file"
},
{
"code": null,
"e": 2499,
"s": 2309,
"text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 2504,
"s": 2499,
"text": "Java"
},
{
"code": "import android.graphics.Color;import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity;import androidx.fragment.app.FragmentManager;import androidx.fragment.app.FragmentTransaction; import com.ramotion.paperonboarding.PaperOnboardingFragment;import com.ramotion.paperonboarding.PaperOnboardingPage; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { private FragmentManager fragmentManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); fragmentManager = getSupportFragmentManager(); // new instance is created and data is took from an // array list known as getDataonborading final PaperOnboardingFragment paperOnboardingFragment = PaperOnboardingFragment.newInstance(getDataforOnboarding()); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); // fragmentTransaction method is used // do all the transactions or changes // between different fragments fragmentTransaction.add(R.id.frame_layout, paperOnboardingFragment); // all the changes are committed fragmentTransaction.commit(); } private ArrayList<PaperOnboardingPage> getDataforOnboarding() { // the first string is to show the main title , // second is to show the message below the // title, then color of background is passed , // then the image to show on the screen is passed // and at last icon to navigate from one screen to other PaperOnboardingPage source = new PaperOnboardingPage(\"Gfg\", \"Welcome to GeeksForGeeks\", Color.parseColor(\"#ffb174\"),R.drawable.gfgimg, R.drawable.search); PaperOnboardingPage source1 = new PaperOnboardingPage(\"Practice\", \"Practice questions from all topics\", Color.parseColor(\"#22eaaa\"),R.drawable.practice_gfg, R.drawable.training); PaperOnboardingPage source2 = new PaperOnboardingPage(\"\", \" \", Color.parseColor(\"#ee5a5a\"),R.drawable.gfg_contribute, R.drawable.contribution); // array list is used to store // data of onbaording screen ArrayList<PaperOnboardingPage> elements = new ArrayList<>(); // all the sources(data to show on screens) // are added to array list elements.add(source); elements.add(source1); elements.add(source2); return elements; }}",
"e": 4976,
"s": 2504,
"text": null
},
{
"code": null,
"e": 5095,
"s": 4976,
"text": "Congratulations, we have successfully made the Onboarding screen for our application. The final output is shown below."
},
{
"code": null,
"e": 5103,
"s": 5095,
"text": "Output:"
},
{
"code": null,
"e": 5111,
"s": 5103,
"text": "Android"
},
{
"code": null,
"e": 5116,
"s": 5111,
"text": "Java"
},
{
"code": null,
"e": 5121,
"s": 5116,
"text": "Java"
},
{
"code": null,
"e": 5129,
"s": 5121,
"text": "Android"
},
{
"code": null,
"e": 5227,
"s": 5129,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5296,
"s": 5227,
"text": "How to Add Views Dynamically and Store Data in Arraylist in Android?"
},
{
"code": null,
"e": 5328,
"s": 5296,
"text": "Android SDK and it's Components"
},
{
"code": null,
"e": 5367,
"s": 5328,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 5416,
"s": 5367,
"text": "How to Communicate Between Fragments in Android?"
},
{
"code": null,
"e": 5458,
"s": 5416,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 5473,
"s": 5458,
"text": "Arrays in Java"
},
{
"code": null,
"e": 5509,
"s": 5473,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 5534,
"s": 5509,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 5578,
"s": 5534,
"text": "Split() String method in Java with examples"
}
] |
Find the maximum and minimum element in a NumPy array | 13 Aug, 2021
An array can be considered as a container with the same types of elements. Python has its array module named array. We can simply import the module and create our array. But this module has some of its drawbacks. The main disadvantage is we can’t create a multidimensional array. And the data type must be the same.
To overcome these problems we use a third-party module called NumPy. Using NumPy we can create multidimensional arrays, and we also can use different data types.
Note: NumPy doesn’t come with python by default. So, we have to install it using pip. To install the module run the given command in the terminal.
pip install numpy
Now let’s create an array using NumPy. For doing this we need to import the module. Here we’re importing the module.
import numpy
Using the above command you can import the module.
Example 1: Now try to create a single-dimensional array.
arr = numpy.array([1, 2, 3, 4, 5])
Here, we create a single-dimensional NumPy array of integers. Now try to find the maximum element. To do this we have to use numpy.max(“array name”) function.
Syntax:
numpy.max(arr)
For finding the minimum element use numpy.min(“array name”) function.
Syntax:
numpy.min(arr)
Code:
Python3
# import numpy libraryimport numpy # creating a numpy array of integersarr = numpy.array([1, 5, 4, 8, 3, 7]) # finding the maximum and# minimum element in the arraymax_element = numpy.max(arr)min_element = numpy.min(arr) # printing the resultprint('maximum element in the array is: ', max_element)print('minimum element in the array is: ', min_element)
Output:
maximum element in the array is: 8
minimum element in the array is: 1
Note: You must use numeric numbers(int or float), you can’t use string.
Example 2: Now, let’s create a two-dimensional NumPy array.
arr = numpy.array([11, 5, 7],
[4, 5, 16],
[7, 81, 16]]
Now using the numpy.max() and numpy.min() functions we can find the maximum and minimum element. Here, we get the maximum and minimum value from the whole array.
Code:
Python3
# import numpy libraryimport numpy # creating a two dimensional# numpy array of integersarr = numpy.array([[11, 2, 3], [4, 5, 16], [7, 81, 22]]) # finding the maximum and# minimum element in the arraymax_element = numpy.max(arr)min_element = numpy.min(arr) # printing the resultprint('maximum element in the array is:', max_element)print('minimum element in the array is:', min_element)
Output:
maximum element in the array is: 81
minimum element in the array is: 2
Example 3: Now, if we want to find the maximum or minimum from the rows or the columns then we have to add 0 or 1. See how it works:
maximum_element = numpy.max(arr, 0)
maximum_element = numpy.max(arr, 1)
If we use 0 it will give us a list containing the maximum or minimum values from each column. Here we will get a list like [11 81 22] which have all the maximum numbers each column.
If we use 1 instead of 0, will get a list like [11 16 81], which contain the maximum number from each row.
Code:
Python3
# import numpy libraryimport numpy # creating a two dimensional# numpy array of integersarr = numpy.array([[11, 2, 3], [4, 5, 16], [7, 81, 22]]) # finding the maximum and# minimum element in the arraymax_element_column = numpy.max(arr, 0)max_element_row = numpy.max(arr, 1) min_element_column = numpy.amin(arr, 0)min_element_row = numpy.amin(arr, 1) # printing the resultprint('maximum elements in the columns of the array is:', max_element_column) print('maximum elements in the rows of the array is:', max_element_row) print('minimum elements in the columns of the array is:', min_element_column) print('minimum elements in the rows of the array is:', min_element_row)
Output:
maximum elements in the columns of the array is: [11 81 22]
maximum elements in the rows of the array is: [11 16 81]
minimum elements in the columns of the array is: [4 2 3]
minimum elements in the rows of the array is: [2 4 7]
Example 4: If we have two same shaped NumPy arrays, we can find the maximum or minimum elements. For this step, we have to numpy.maximum(array1, array2) function. It will return a list containing maximum values from each column.
Code:
Python3
# importing numpy libraryimport numpy # creating two single dimensional arraya = numpy.array([1, 4, 6, 8, 9])b = numpy.array([5, 7, 3, 9, 22]) # print maximum valueprint(numpy.maximum(a, b))
Output:
[ 5 7 6 9 22]
anikakapoor
Python numpy-Basics
Python-numpy
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
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
Introduction To PYTHON | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 Aug, 2021"
},
{
"code": null,
"e": 344,
"s": 28,
"text": "An array can be considered as a container with the same types of elements. Python has its array module named array. We can simply import the module and create our array. But this module has some of its drawbacks. The main disadvantage is we can’t create a multidimensional array. And the data type must be the same."
},
{
"code": null,
"e": 506,
"s": 344,
"text": "To overcome these problems we use a third-party module called NumPy. Using NumPy we can create multidimensional arrays, and we also can use different data types."
},
{
"code": null,
"e": 653,
"s": 506,
"text": "Note: NumPy doesn’t come with python by default. So, we have to install it using pip. To install the module run the given command in the terminal."
},
{
"code": null,
"e": 671,
"s": 653,
"text": "pip install numpy"
},
{
"code": null,
"e": 788,
"s": 671,
"text": "Now let’s create an array using NumPy. For doing this we need to import the module. Here we’re importing the module."
},
{
"code": null,
"e": 801,
"s": 788,
"text": "import numpy"
},
{
"code": null,
"e": 853,
"s": 801,
"text": "Using the above command you can import the module. "
},
{
"code": null,
"e": 911,
"s": 853,
"text": "Example 1: Now try to create a single-dimensional array. "
},
{
"code": null,
"e": 946,
"s": 911,
"text": "arr = numpy.array([1, 2, 3, 4, 5])"
},
{
"code": null,
"e": 1106,
"s": 946,
"text": "Here, we create a single-dimensional NumPy array of integers. Now try to find the maximum element. To do this we have to use numpy.max(“array name”) function. "
},
{
"code": null,
"e": 1115,
"s": 1106,
"text": "Syntax: "
},
{
"code": null,
"e": 1130,
"s": 1115,
"text": "numpy.max(arr)"
},
{
"code": null,
"e": 1200,
"s": 1130,
"text": "For finding the minimum element use numpy.min(“array name”) function."
},
{
"code": null,
"e": 1208,
"s": 1200,
"text": "Syntax:"
},
{
"code": null,
"e": 1223,
"s": 1208,
"text": "numpy.min(arr)"
},
{
"code": null,
"e": 1229,
"s": 1223,
"text": "Code:"
},
{
"code": null,
"e": 1237,
"s": 1229,
"text": "Python3"
},
{
"code": "# import numpy libraryimport numpy # creating a numpy array of integersarr = numpy.array([1, 5, 4, 8, 3, 7]) # finding the maximum and# minimum element in the arraymax_element = numpy.max(arr)min_element = numpy.min(arr) # printing the resultprint('maximum element in the array is: ', max_element)print('minimum element in the array is: ', min_element)",
"e": 1600,
"s": 1237,
"text": null
},
{
"code": null,
"e": 1609,
"s": 1600,
"text": "Output: "
},
{
"code": null,
"e": 1682,
"s": 1609,
"text": "maximum element in the array is: 8 \nminimum element in the array is: 1"
},
{
"code": null,
"e": 1754,
"s": 1682,
"text": "Note: You must use numeric numbers(int or float), you can’t use string."
},
{
"code": null,
"e": 1815,
"s": 1754,
"text": "Example 2: Now, let’s create a two-dimensional NumPy array. "
},
{
"code": null,
"e": 1886,
"s": 1815,
"text": "arr = numpy.array([11, 5, 7],\n [4, 5, 16],\n [7, 81, 16]]"
},
{
"code": null,
"e": 2048,
"s": 1886,
"text": "Now using the numpy.max() and numpy.min() functions we can find the maximum and minimum element. Here, we get the maximum and minimum value from the whole array."
},
{
"code": null,
"e": 2055,
"s": 2048,
"text": "Code: "
},
{
"code": null,
"e": 2063,
"s": 2055,
"text": "Python3"
},
{
"code": "# import numpy libraryimport numpy # creating a two dimensional# numpy array of integersarr = numpy.array([[11, 2, 3], [4, 5, 16], [7, 81, 22]]) # finding the maximum and# minimum element in the arraymax_element = numpy.max(arr)min_element = numpy.min(arr) # printing the resultprint('maximum element in the array is:', max_element)print('minimum element in the array is:', min_element)",
"e": 2501,
"s": 2063,
"text": null
},
{
"code": null,
"e": 2510,
"s": 2501,
"text": "Output: "
},
{
"code": null,
"e": 2581,
"s": 2510,
"text": "maximum element in the array is: 81\nminimum element in the array is: 2"
},
{
"code": null,
"e": 2715,
"s": 2581,
"text": "Example 3: Now, if we want to find the maximum or minimum from the rows or the columns then we have to add 0 or 1. See how it works: "
},
{
"code": null,
"e": 2787,
"s": 2715,
"text": "maximum_element = numpy.max(arr, 0)\nmaximum_element = numpy.max(arr, 1)"
},
{
"code": null,
"e": 2970,
"s": 2787,
"text": "If we use 0 it will give us a list containing the maximum or minimum values from each column. Here we will get a list like [11 81 22] which have all the maximum numbers each column. "
},
{
"code": null,
"e": 3077,
"s": 2970,
"text": "If we use 1 instead of 0, will get a list like [11 16 81], which contain the maximum number from each row."
},
{
"code": null,
"e": 3084,
"s": 3077,
"text": "Code: "
},
{
"code": null,
"e": 3092,
"s": 3084,
"text": "Python3"
},
{
"code": "# import numpy libraryimport numpy # creating a two dimensional# numpy array of integersarr = numpy.array([[11, 2, 3], [4, 5, 16], [7, 81, 22]]) # finding the maximum and# minimum element in the arraymax_element_column = numpy.max(arr, 0)max_element_row = numpy.max(arr, 1) min_element_column = numpy.amin(arr, 0)min_element_row = numpy.amin(arr, 1) # printing the resultprint('maximum elements in the columns of the array is:', max_element_column) print('maximum elements in the rows of the array is:', max_element_row) print('minimum elements in the columns of the array is:', min_element_column) print('minimum elements in the rows of the array is:', min_element_row)",
"e": 3824,
"s": 3092,
"text": null
},
{
"code": null,
"e": 3833,
"s": 3824,
"text": "Output: "
},
{
"code": null,
"e": 4061,
"s": 3833,
"text": "maximum elements in the columns of the array is: [11 81 22]\nmaximum elements in the rows of the array is: [11 16 81]\nminimum elements in the columns of the array is: [4 2 3]\nminimum elements in the rows of the array is: [2 4 7]"
},
{
"code": null,
"e": 4291,
"s": 4061,
"text": "Example 4: If we have two same shaped NumPy arrays, we can find the maximum or minimum elements. For this step, we have to numpy.maximum(array1, array2) function. It will return a list containing maximum values from each column. "
},
{
"code": null,
"e": 4298,
"s": 4291,
"text": "Code: "
},
{
"code": null,
"e": 4306,
"s": 4298,
"text": "Python3"
},
{
"code": "# importing numpy libraryimport numpy # creating two single dimensional arraya = numpy.array([1, 4, 6, 8, 9])b = numpy.array([5, 7, 3, 9, 22]) # print maximum valueprint(numpy.maximum(a, b))",
"e": 4497,
"s": 4306,
"text": null
},
{
"code": null,
"e": 4506,
"s": 4497,
"text": "Output: "
},
{
"code": null,
"e": 4523,
"s": 4506,
"text": "[ 5 7 6 9 22]"
},
{
"code": null,
"e": 4537,
"s": 4525,
"text": "anikakapoor"
},
{
"code": null,
"e": 4557,
"s": 4537,
"text": "Python numpy-Basics"
},
{
"code": null,
"e": 4570,
"s": 4557,
"text": "Python-numpy"
},
{
"code": null,
"e": 4577,
"s": 4570,
"text": "Python"
},
{
"code": null,
"e": 4675,
"s": 4577,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4693,
"s": 4675,
"text": "Python Dictionary"
},
{
"code": null,
"e": 4735,
"s": 4693,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 4757,
"s": 4735,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 4789,
"s": 4757,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 4818,
"s": 4789,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 4845,
"s": 4818,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 4875,
"s": 4845,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 4911,
"s": 4875,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 4932,
"s": 4911,
"text": "Python OOPs Concepts"
}
] |
The Knight’s tour problem | Backtracking-1 | 21 Oct, 2021
Backtracking is an algorithmic paradigm that tries different solutions until finds a solution that “works”. Problems that are typically solved using the backtracking technique have the following property in common. These problems can only be solved by trying every possible configuration and each configuration is tried only once. A Naive solution for these problems is to try all configurations and output a configuration that follows given problem constraints. Backtracking works incrementally and is an optimization over the Naive solution where all possible configurations are generated and tried.For example, consider the following Knight’s Tour problem.
Problem Statement:Given a N*N board with the Knight placed on the first block of an empty board. Moving according to the rules of chess knight must visit each square exactly once. Print the order of each cell in which they are visited.
Example:
Input :
N = 8
Output:
0 59 38 33 30 17 8 63
37 34 31 60 9 62 29 16
58 1 36 39 32 27 18 7
35 48 41 26 61 10 15 28
42 57 2 49 40 23 6 19
47 50 45 54 25 20 11 14
56 43 52 3 22 13 24 5
51 46 55 44 53 4 21 12
The path followed by Knight to cover all the cellsFollowing is a chessboard with 8 x 8 cells. Numbers in cells indicate the move number of Knight.
Let us first discuss the Naive algorithm for this problem and then the Backtracking algorithm.
Naive Algorithm for Knight’s tour The Naive Algorithm is to generate all tours one by one and check if the generated tour satisfies the constraints.
while there are untried tours
{
generate the next tour
if this tour covers all squares
{
print this path;
}
}
Backtracking works in an incremental way to attack problems. Typically, we start from an empty solution vector and one by one add items (Meaning of item varies from problem to problem. In the context of Knight’s tour problem, an item is a Knight’s move). When we add an item, we check if adding the current item violates the problem constraint, if it does then we remove the item and try other alternatives. If none of the alternatives works out then we go to the previous stage and remove the item added in the previous stage. If we reach the initial stage back then we say that no solution exists. If adding an item doesn’t violate constraints then we recursively add items one by one. If the solution vector becomes complete then we print the solution.
Backtracking Algorithm for Knight’s tour
Following is the Backtracking algorithm for Knight’s tour problem.
If all squares are visited
print the solution
Else
a) Add one of the next moves to solution vector and recursively
check if this move leads to a solution. (A Knight can make maximum
eight moves. We choose one of the 8 moves in this step).
b) If the move chosen in the above step doesn't lead to a solution
then remove this move from the solution vector and try other
alternative moves.
c) If none of the alternatives work then return false (Returning false
will remove the previously added item in recursion and if false is
returned by the initial call of recursion then "no solution exists" )
Following are implementations for Knight’s tour problem. It prints one of the possible solutions in 2D matrix form. Basically, the output is a 2D 8*8 matrix with numbers from 0 to 63 and these numbers show steps made by Knight.
C++
C
Java
Python3
C#
Javascript
// C++ program for Knight Tour problem#include <bits/stdc++.h>using namespace std; #define N 8 int solveKTUtil(int x, int y, int movei, int sol[N][N], int xMove[], int yMove[]); /* A utility function to check if i,j arevalid indexes for N*N chessboard */int isSafe(int x, int y, int sol[N][N]){ return (x >= 0 && x < N && y >= 0 && y < N && sol[x][y] == -1);} /* A utility function to printsolution matrix sol[N][N] */void printSolution(int sol[N][N]){ for (int x = 0; x < N; x++) { for (int y = 0; y < N; y++) cout << " " << setw(2) << sol[x][y] << " "; cout << endl; }} /* This function solves the Knight Tour problem usingBacktracking. This function mainly uses solveKTUtil()to solve the problem. It returns false if no completetour is possible, otherwise return true and prints thetour.Please note that there may be more than one solutions,this function prints one of the feasible solutions. */int solveKT(){ int sol[N][N]; /* Initialization of solution matrix */ for (int x = 0; x < N; x++) for (int y = 0; y < N; y++) sol[x][y] = -1; /* xMove[] and yMove[] define next move of Knight. xMove[] is for next value of x coordinate yMove[] is for next value of y coordinate */ int xMove[8] = { 2, 1, -1, -2, -2, -1, 1, 2 }; int yMove[8] = { 1, 2, 2, 1, -1, -2, -2, -1 }; // Since the Knight is initially at the first block sol[0][0] = 0; /* Start from 0,0 and explore all tours using solveKTUtil() */ if (solveKTUtil(0, 0, 1, sol, xMove, yMove) == 0) { cout << "Solution does not exist"; return 0; } else printSolution(sol); return 1;} /* A recursive utility function to solve Knight Tourproblem */int solveKTUtil(int x, int y, int movei, int sol[N][N], int xMove[8], int yMove[8]){ int k, next_x, next_y; if (movei == N * N) return 1; /* Try all next moves from the current coordinate x, y */ for (k = 0; k < 8; k++) { next_x = x + xMove[k]; next_y = y + yMove[k]; if (isSafe(next_x, next_y, sol)) { sol[next_x][next_y] = movei; if (solveKTUtil(next_x, next_y, movei + 1, sol, xMove, yMove) == 1) return 1; else // backtracking sol[next_x][next_y] = -1; } } return 0;} // Driver Codeint main(){ // Function Call solveKT(); return 0;} // This code is contributed by ShubhamCoder
// C program for Knight Tour problem#include <stdio.h>#define N 8 int solveKTUtil(int x, int y, int movei, int sol[N][N], int xMove[], int yMove[]); /* A utility function to check if i,j are valid indexes for N*N chessboard */int isSafe(int x, int y, int sol[N][N]){ return (x >= 0 && x < N && y >= 0 && y < N && sol[x][y] == -1);} /* A utility function to print solution matrix sol[N][N] */void printSolution(int sol[N][N]){ for (int x = 0; x < N; x++) { for (int y = 0; y < N; y++) printf(" %2d ", sol[x][y]); printf("\n"); }} /* This function solves the Knight Tour problem using Backtracking. This function mainly uses solveKTUtil() to solve the problem. It returns false if no complete tour is possible, otherwise return true and prints the tour. Please note that there may be more than one solutions, this function prints one of the feasible solutions. */int solveKT(){ int sol[N][N]; /* Initialization of solution matrix */ for (int x = 0; x < N; x++) for (int y = 0; y < N; y++) sol[x][y] = -1; /* xMove[] and yMove[] define next move of Knight. xMove[] is for next value of x coordinate yMove[] is for next value of y coordinate */ int xMove[8] = { 2, 1, -1, -2, -2, -1, 1, 2 }; int yMove[8] = { 1, 2, 2, 1, -1, -2, -2, -1 }; // Since the Knight is initially at the first block sol[0][0] = 0; /* Start from 0,0 and explore all tours using solveKTUtil() */ if (solveKTUtil(0, 0, 1, sol, xMove, yMove) == 0) { printf("Solution does not exist"); return 0; } else printSolution(sol); return 1;} /* A recursive utility function to solve Knight Tour problem */int solveKTUtil(int x, int y, int movei, int sol[N][N], int xMove[N], int yMove[N]){ int k, next_x, next_y; if (movei == N * N) return 1; /* Try all next moves from the current coordinate x, y */ for (k = 0; k < 8; k++) { next_x = x + xMove[k]; next_y = y + yMove[k]; if (isSafe(next_x, next_y, sol)) { sol[next_x][next_y] = movei; if (solveKTUtil(next_x, next_y, movei + 1, sol, xMove, yMove) == 1) return 1; else sol[next_x][next_y] = -1; // backtracking } } return 0;} /* Driver Code */int main(){ // Function Call solveKT(); return 0;}
// Java program for Knight Tour problemclass KnightTour { static int N = 8; /* A utility function to check if i,j are valid indexes for N*N chessboard */ static boolean isSafe(int x, int y, int sol[][]) { return (x >= 0 && x < N && y >= 0 && y < N && sol[x][y] == -1); } /* A utility function to print solution matrix sol[N][N] */ static void printSolution(int sol[][]) { for (int x = 0; x < N; x++) { for (int y = 0; y < N; y++) System.out.print(sol[x][y] + " "); System.out.println(); } } /* This function solves the Knight Tour problem using Backtracking. This function mainly uses solveKTUtil() to solve the problem. It returns false if no complete tour is possible, otherwise return true and prints the tour. Please note that there may be more than one solutions, this function prints one of the feasible solutions. */ static boolean solveKT() { int sol[][] = new int[8][8]; /* Initialization of solution matrix */ for (int x = 0; x < N; x++) for (int y = 0; y < N; y++) sol[x][y] = -1; /* xMove[] and yMove[] define next move of Knight. xMove[] is for next value of x coordinate yMove[] is for next value of y coordinate */ int xMove[] = { 2, 1, -1, -2, -2, -1, 1, 2 }; int yMove[] = { 1, 2, 2, 1, -1, -2, -2, -1 }; // Since the Knight is initially at the first block sol[0][0] = 0; /* Start from 0,0 and explore all tours using solveKTUtil() */ if (!solveKTUtil(0, 0, 1, sol, xMove, yMove)) { System.out.println("Solution does not exist"); return false; } else printSolution(sol); return true; } /* A recursive utility function to solve Knight Tour problem */ static boolean solveKTUtil(int x, int y, int movei, int sol[][], int xMove[], int yMove[]) { int k, next_x, next_y; if (movei == N * N) return true; /* Try all next moves from the current coordinate x, y */ for (k = 0; k < 8; k++) { next_x = x + xMove[k]; next_y = y + yMove[k]; if (isSafe(next_x, next_y, sol)) { sol[next_x][next_y] = movei; if (solveKTUtil(next_x, next_y, movei + 1, sol, xMove, yMove)) return true; else sol[next_x][next_y] = -1; // backtracking } } return false; } /* Driver Code */ public static void main(String args[]) { // Function Call solveKT(); }}// This code is contributed by Abhishek Shankhadhar
# Python3 program to solve Knight Tour problem using Backtracking # Chessboard Sizen = 8 def isSafe(x, y, board): ''' A utility function to check if i,j are valid indexes for N*N chessboard ''' if(x >= 0 and y >= 0 and x < n and y < n and board[x][y] == -1): return True return False def printSolution(n, board): ''' A utility function to print Chessboard matrix ''' for i in range(n): for j in range(n): print(board[i][j], end=' ') print() def solveKT(n): ''' This function solves the Knight Tour problem using Backtracking. This function mainly uses solveKTUtil() to solve the problem. It returns false if no complete tour is possible, otherwise return true and prints the tour. Please note that there may be more than one solutions, this function prints one of the feasible solutions. ''' # Initialization of Board matrix board = [[-1 for i in range(n)]for i in range(n)] # move_x and move_y define next move of Knight. # move_x is for next value of x coordinate # move_y is for next value of y coordinate move_x = [2, 1, -1, -2, -2, -1, 1, 2] move_y = [1, 2, 2, 1, -1, -2, -2, -1] # Since the Knight is initially at the first block board[0][0] = 0 # Step counter for knight's position pos = 1 # Checking if solution exists or not if(not solveKTUtil(n, board, 0, 0, move_x, move_y, pos)): print("Solution does not exist") else: printSolution(n, board) def solveKTUtil(n, board, curr_x, curr_y, move_x, move_y, pos): ''' A recursive utility function to solve Knight Tour problem ''' if(pos == n**2): return True # Try all next moves from the current coordinate x, y for i in range(8): new_x = curr_x + move_x[i] new_y = curr_y + move_y[i] if(isSafe(new_x, new_y, board)): board[new_x][new_y] = pos if(solveKTUtil(n, board, new_x, new_y, move_x, move_y, pos+1)): return True # Backtracking board[new_x][new_y] = -1 return False # Driver Codeif __name__ == "__main__": # Function Call solveKT(n) # This code is contributed by AAKASH PAL
// C# program for// Knight Tour problemusing System; class GFG { static int N = 8; /* A utility function to check if i,j are valid indexes for N*N chessboard */ static bool isSafe(int x, int y, int[, ] sol) { return (x >= 0 && x < N && y >= 0 && y < N && sol[x, y] == -1); } /* A utility function to print solution matrix sol[N][N] */ static void printSolution(int[, ] sol) { for (int x = 0; x < N; x++) { for (int y = 0; y < N; y++) Console.Write(sol[x, y] + " "); Console.WriteLine(); } } /* This function solves the Knight Tour problem using Backtracking. This function mainly uses solveKTUtil() to solve the problem. It returns false if no complete tour is possible, otherwise return true and prints the tour. Please note that there may be more than one solutions, this function prints one of the feasible solutions. */ static bool solveKT() { int[, ] sol = new int[8, 8]; /* Initialization of solution matrix */ for (int x = 0; x < N; x++) for (int y = 0; y < N; y++) sol[x, y] = -1; /* xMove[] and yMove[] define next move of Knight. xMove[] is for next value of x coordinate yMove[] is for next value of y coordinate */ int[] xMove = { 2, 1, -1, -2, -2, -1, 1, 2 }; int[] yMove = { 1, 2, 2, 1, -1, -2, -2, -1 }; // Since the Knight is // initially at the first block sol[0, 0] = 0; /* Start from 0,0 and explore all tours using solveKTUtil() */ if (!solveKTUtil(0, 0, 1, sol, xMove, yMove)) { Console.WriteLine("Solution does " + "not exist"); return false; } else printSolution(sol); return true; } /* A recursive utility function to solve Knight Tour problem */ static bool solveKTUtil(int x, int y, int movei, int[, ] sol, int[] xMove, int[] yMove) { int k, next_x, next_y; if (movei == N * N) return true; /* Try all next moves from the current coordinate x, y */ for (k = 0; k < 8; k++) { next_x = x + xMove[k]; next_y = y + yMove[k]; if (isSafe(next_x, next_y, sol)) { sol[next_x, next_y] = movei; if (solveKTUtil(next_x, next_y, movei + 1, sol, xMove, yMove)) return true; else // backtracking sol[next_x, next_y] = -1; } } return false; } // Driver Code public static void Main() { // Function Call solveKT(); }} // This code is contributed by mits.
<script> // Javascript program for Knight Tour problemlet N = 8; // A utility function to check if i,j are// valid indexes for N*N chessboardfunction isSafe(x, y, sol){ return(x >= 0 && x < N && y >= 0 && y < N && sol[x][y] == -1);} // A utility function to print solution// matrix sol[N][N]function printSolution(sol){ for(let x = 0; x < N; x++) { for(let y = 0; y < N; y++) document.write(sol[x][y] + " "); document.write("<br/>"); }} // This function solves the Knight Tour problem// using Backtracking. This function mainly// uses solveKTUtil() to solve the problem. It// returns false if no complete tour is possible,// otherwise return true and prints the tour.// Please note that there may be more than one// solutions, this function prints one of the// feasible solutions. function solveKT(){ let sol = new Array(8); for(var i = 0; i < sol.length; i++) { sol[i] = new Array(2); } // Initialization of solution matrix for(let x = 0; x < N; x++) for(let y = 0; y < N; y++) sol[x][y] = -1; // xMove[] and yMove[] define next move of Knight. // xMove[] is for next value of x coordinate // yMove[] is for next value of y coordinate let xMove = [ 2, 1, -1, -2, -2, -1, 1, 2 ]; let yMove = [ 1, 2, 2, 1, -1, -2, -2, -1 ]; // Since the Knight is initially at the first block sol[0][0] = 0; // Start from 0,0 and explore all tours using // solveKTUtil() if (!solveKTUtil(0, 0, 1, sol, xMove, yMove)) { document.write("Solution does not exist"); return false; } else printSolution(sol); return true;} // A recursive utility function to solve Knight// Tour problemfunction solveKTUtil(x, y, movei, sol, xMove, yMove){ let k, next_x, next_y; if (movei == N * N) return true; // Try all next moves from the // current coordinate x, y for(k = 0; k < 8; k++) { next_x = x + xMove[k]; next_y = y + yMove[k]; if (isSafe(next_x, next_y, sol)) { sol[next_x][next_y] = movei; if (solveKTUtil(next_x, next_y, movei + 1, sol, xMove, yMove)) return true; else sol[next_x][next_y] = -1; // backtracking } } return false;} // Driver code // Function CallsolveKT(); // This code is contributed by target_2 </script>
0 59 38 33 30 17 8 63
37 34 31 60 9 62 29 16
58 1 36 39 32 27 18 7
35 48 41 26 61 10 15 28
42 57 2 49 40 23 6 19
47 50 45 54 25 20 11 14
56 43 52 3 22 13 24 5
51 46 55 44 53 4 21 12
Time Complexity : There are N2 Cells and for each, we have a maximum of 8 possible moves to choose from, so the worst running time is O(8N^2).
Auxiliary Space: O(N2)
Important Note:No order of the xMove, yMove is wrong, but they will affect the running time of the algorithm drastically. For example, think of the case where the 8th choice of the move is the correct one, and before that our code ran 7 different wrong paths. It’s always a good idea a have a heuristic than to try backtracking randomly. Like, in this case, we know the next step would probably be in the south or east direction, then checking the paths which lead their first is a better strategy.
Note that Backtracking is not the best solution for the Knight’s tour problem. See the below article for other better solutions. The purpose of this post is to explain Backtracking with an example. Warnsdorff’s algorithm for Knight’s tour problem
References: http://see.stanford.edu/materials/icspacs106b/H19-RecBacktrackExamples.pdf http://www.cis.upenn.edu/~matuszek/cit594-2009/Lectures/35-backtracking.ppt http://mathworld.wolfram.com/KnightsTour.html http://en.wikipedia.org/wiki/Knight%27s_tour Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Mithun Kumar
Aakash Pal
skwillbesk
ChetanGoyal1
shubhamsingh84100
yadavgaurav251
target_2
user_3ums
khushboogoyal499
subhammahato348
pujasingg43
Amazon
chessboard-problems
Backtracking
Mathematical
Amazon
Mathematical
Backtracking
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)
Generate all the binary strings of N bits
Print all paths from a given source to a destination
Print all permutations of a string in Java
Find if there is a path of more than k length from a source
Program for Fibonacci numbers
Set in C++ Standard Template Library (STL)
C++ Data Types
Merge two sorted arrays
Coin Change | DP-7 | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n21 Oct, 2021"
},
{
"code": null,
"e": 713,
"s": 52,
"text": "Backtracking is an algorithmic paradigm that tries different solutions until finds a solution that “works”. Problems that are typically solved using the backtracking technique have the following property in common. These problems can only be solved by trying every possible configuration and each configuration is tried only once. A Naive solution for these problems is to try all configurations and output a configuration that follows given problem constraints. Backtracking works incrementally and is an optimization over the Naive solution where all possible configurations are generated and tried.For example, consider the following Knight’s Tour problem. "
},
{
"code": null,
"e": 949,
"s": 713,
"text": "Problem Statement:Given a N*N board with the Knight placed on the first block of an empty board. Moving according to the rules of chess knight must visit each square exactly once. Print the order of each cell in which they are visited."
},
{
"code": null,
"e": 958,
"s": 949,
"text": "Example:"
},
{
"code": null,
"e": 1228,
"s": 958,
"text": "Input : \nN = 8\nOutput:\n0 59 38 33 30 17 8 63\n37 34 31 60 9 62 29 16\n58 1 36 39 32 27 18 7\n35 48 41 26 61 10 15 28\n42 57 2 49 40 23 6 19\n47 50 45 54 25 20 11 14\n56 43 52 3 22 13 24 5\n51 46 55 44 53 4 21 12"
},
{
"code": null,
"e": 1376,
"s": 1228,
"text": "The path followed by Knight to cover all the cellsFollowing is a chessboard with 8 x 8 cells. Numbers in cells indicate the move number of Knight. "
},
{
"code": null,
"e": 1471,
"s": 1376,
"text": "Let us first discuss the Naive algorithm for this problem and then the Backtracking algorithm."
},
{
"code": null,
"e": 1621,
"s": 1471,
"text": "Naive Algorithm for Knight’s tour The Naive Algorithm is to generate all tours one by one and check if the generated tour satisfies the constraints. "
},
{
"code": null,
"e": 1753,
"s": 1621,
"text": "while there are untried tours\n{ \n generate the next tour \n if this tour covers all squares \n { \n print this path;\n }\n}"
},
{
"code": null,
"e": 2509,
"s": 1753,
"text": "Backtracking works in an incremental way to attack problems. Typically, we start from an empty solution vector and one by one add items (Meaning of item varies from problem to problem. In the context of Knight’s tour problem, an item is a Knight’s move). When we add an item, we check if adding the current item violates the problem constraint, if it does then we remove the item and try other alternatives. If none of the alternatives works out then we go to the previous stage and remove the item added in the previous stage. If we reach the initial stage back then we say that no solution exists. If adding an item doesn’t violate constraints then we recursively add items one by one. If the solution vector becomes complete then we print the solution."
},
{
"code": null,
"e": 2551,
"s": 2509,
"text": "Backtracking Algorithm for Knight’s tour "
},
{
"code": null,
"e": 2619,
"s": 2551,
"text": "Following is the Backtracking algorithm for Knight’s tour problem. "
},
{
"code": null,
"e": 3250,
"s": 2619,
"text": "If all squares are visited \n print the solution\nElse\n a) Add one of the next moves to solution vector and recursively \n check if this move leads to a solution. (A Knight can make maximum \n eight moves. We choose one of the 8 moves in this step).\n b) If the move chosen in the above step doesn't lead to a solution\n then remove this move from the solution vector and try other \n alternative moves.\n c) If none of the alternatives work then return false (Returning false \n will remove the previously added item in recursion and if false is \n returned by the initial call of recursion then \"no solution exists\" )"
},
{
"code": null,
"e": 3480,
"s": 3250,
"text": "Following are implementations for Knight’s tour problem. It prints one of the possible solutions in 2D matrix form. Basically, the output is a 2D 8*8 matrix with numbers from 0 to 63 and these numbers show steps made by Knight. "
},
{
"code": null,
"e": 3484,
"s": 3480,
"text": "C++"
},
{
"code": null,
"e": 3486,
"s": 3484,
"text": "C"
},
{
"code": null,
"e": 3491,
"s": 3486,
"text": "Java"
},
{
"code": null,
"e": 3499,
"s": 3491,
"text": "Python3"
},
{
"code": null,
"e": 3502,
"s": 3499,
"text": "C#"
},
{
"code": null,
"e": 3513,
"s": 3502,
"text": "Javascript"
},
{
"code": "// C++ program for Knight Tour problem#include <bits/stdc++.h>using namespace std; #define N 8 int solveKTUtil(int x, int y, int movei, int sol[N][N], int xMove[], int yMove[]); /* A utility function to check if i,j arevalid indexes for N*N chessboard */int isSafe(int x, int y, int sol[N][N]){ return (x >= 0 && x < N && y >= 0 && y < N && sol[x][y] == -1);} /* A utility function to printsolution matrix sol[N][N] */void printSolution(int sol[N][N]){ for (int x = 0; x < N; x++) { for (int y = 0; y < N; y++) cout << \" \" << setw(2) << sol[x][y] << \" \"; cout << endl; }} /* This function solves the Knight Tour problem usingBacktracking. This function mainly uses solveKTUtil()to solve the problem. It returns false if no completetour is possible, otherwise return true and prints thetour.Please note that there may be more than one solutions,this function prints one of the feasible solutions. */int solveKT(){ int sol[N][N]; /* Initialization of solution matrix */ for (int x = 0; x < N; x++) for (int y = 0; y < N; y++) sol[x][y] = -1; /* xMove[] and yMove[] define next move of Knight. xMove[] is for next value of x coordinate yMove[] is for next value of y coordinate */ int xMove[8] = { 2, 1, -1, -2, -2, -1, 1, 2 }; int yMove[8] = { 1, 2, 2, 1, -1, -2, -2, -1 }; // Since the Knight is initially at the first block sol[0][0] = 0; /* Start from 0,0 and explore all tours using solveKTUtil() */ if (solveKTUtil(0, 0, 1, sol, xMove, yMove) == 0) { cout << \"Solution does not exist\"; return 0; } else printSolution(sol); return 1;} /* A recursive utility function to solve Knight Tourproblem */int solveKTUtil(int x, int y, int movei, int sol[N][N], int xMove[8], int yMove[8]){ int k, next_x, next_y; if (movei == N * N) return 1; /* Try all next moves from the current coordinate x, y */ for (k = 0; k < 8; k++) { next_x = x + xMove[k]; next_y = y + yMove[k]; if (isSafe(next_x, next_y, sol)) { sol[next_x][next_y] = movei; if (solveKTUtil(next_x, next_y, movei + 1, sol, xMove, yMove) == 1) return 1; else // backtracking sol[next_x][next_y] = -1; } } return 0;} // Driver Codeint main(){ // Function Call solveKT(); return 0;} // This code is contributed by ShubhamCoder",
"e": 6063,
"s": 3513,
"text": null
},
{
"code": "// C program for Knight Tour problem#include <stdio.h>#define N 8 int solveKTUtil(int x, int y, int movei, int sol[N][N], int xMove[], int yMove[]); /* A utility function to check if i,j are valid indexes for N*N chessboard */int isSafe(int x, int y, int sol[N][N]){ return (x >= 0 && x < N && y >= 0 && y < N && sol[x][y] == -1);} /* A utility function to print solution matrix sol[N][N] */void printSolution(int sol[N][N]){ for (int x = 0; x < N; x++) { for (int y = 0; y < N; y++) printf(\" %2d \", sol[x][y]); printf(\"\\n\"); }} /* This function solves the Knight Tour problem using Backtracking. This function mainly uses solveKTUtil() to solve the problem. It returns false if no complete tour is possible, otherwise return true and prints the tour. Please note that there may be more than one solutions, this function prints one of the feasible solutions. */int solveKT(){ int sol[N][N]; /* Initialization of solution matrix */ for (int x = 0; x < N; x++) for (int y = 0; y < N; y++) sol[x][y] = -1; /* xMove[] and yMove[] define next move of Knight. xMove[] is for next value of x coordinate yMove[] is for next value of y coordinate */ int xMove[8] = { 2, 1, -1, -2, -2, -1, 1, 2 }; int yMove[8] = { 1, 2, 2, 1, -1, -2, -2, -1 }; // Since the Knight is initially at the first block sol[0][0] = 0; /* Start from 0,0 and explore all tours using solveKTUtil() */ if (solveKTUtil(0, 0, 1, sol, xMove, yMove) == 0) { printf(\"Solution does not exist\"); return 0; } else printSolution(sol); return 1;} /* A recursive utility function to solve Knight Tour problem */int solveKTUtil(int x, int y, int movei, int sol[N][N], int xMove[N], int yMove[N]){ int k, next_x, next_y; if (movei == N * N) return 1; /* Try all next moves from the current coordinate x, y */ for (k = 0; k < 8; k++) { next_x = x + xMove[k]; next_y = y + yMove[k]; if (isSafe(next_x, next_y, sol)) { sol[next_x][next_y] = movei; if (solveKTUtil(next_x, next_y, movei + 1, sol, xMove, yMove) == 1) return 1; else sol[next_x][next_y] = -1; // backtracking } } return 0;} /* Driver Code */int main(){ // Function Call solveKT(); return 0;}",
"e": 8538,
"s": 6063,
"text": null
},
{
"code": "// Java program for Knight Tour problemclass KnightTour { static int N = 8; /* A utility function to check if i,j are valid indexes for N*N chessboard */ static boolean isSafe(int x, int y, int sol[][]) { return (x >= 0 && x < N && y >= 0 && y < N && sol[x][y] == -1); } /* A utility function to print solution matrix sol[N][N] */ static void printSolution(int sol[][]) { for (int x = 0; x < N; x++) { for (int y = 0; y < N; y++) System.out.print(sol[x][y] + \" \"); System.out.println(); } } /* This function solves the Knight Tour problem using Backtracking. This function mainly uses solveKTUtil() to solve the problem. It returns false if no complete tour is possible, otherwise return true and prints the tour. Please note that there may be more than one solutions, this function prints one of the feasible solutions. */ static boolean solveKT() { int sol[][] = new int[8][8]; /* Initialization of solution matrix */ for (int x = 0; x < N; x++) for (int y = 0; y < N; y++) sol[x][y] = -1; /* xMove[] and yMove[] define next move of Knight. xMove[] is for next value of x coordinate yMove[] is for next value of y coordinate */ int xMove[] = { 2, 1, -1, -2, -2, -1, 1, 2 }; int yMove[] = { 1, 2, 2, 1, -1, -2, -2, -1 }; // Since the Knight is initially at the first block sol[0][0] = 0; /* Start from 0,0 and explore all tours using solveKTUtil() */ if (!solveKTUtil(0, 0, 1, sol, xMove, yMove)) { System.out.println(\"Solution does not exist\"); return false; } else printSolution(sol); return true; } /* A recursive utility function to solve Knight Tour problem */ static boolean solveKTUtil(int x, int y, int movei, int sol[][], int xMove[], int yMove[]) { int k, next_x, next_y; if (movei == N * N) return true; /* Try all next moves from the current coordinate x, y */ for (k = 0; k < 8; k++) { next_x = x + xMove[k]; next_y = y + yMove[k]; if (isSafe(next_x, next_y, sol)) { sol[next_x][next_y] = movei; if (solveKTUtil(next_x, next_y, movei + 1, sol, xMove, yMove)) return true; else sol[next_x][next_y] = -1; // backtracking } } return false; } /* Driver Code */ public static void main(String args[]) { // Function Call solveKT(); }}// This code is contributed by Abhishek Shankhadhar",
"e": 11442,
"s": 8538,
"text": null
},
{
"code": "# Python3 program to solve Knight Tour problem using Backtracking # Chessboard Sizen = 8 def isSafe(x, y, board): ''' A utility function to check if i,j are valid indexes for N*N chessboard ''' if(x >= 0 and y >= 0 and x < n and y < n and board[x][y] == -1): return True return False def printSolution(n, board): ''' A utility function to print Chessboard matrix ''' for i in range(n): for j in range(n): print(board[i][j], end=' ') print() def solveKT(n): ''' This function solves the Knight Tour problem using Backtracking. This function mainly uses solveKTUtil() to solve the problem. It returns false if no complete tour is possible, otherwise return true and prints the tour. Please note that there may be more than one solutions, this function prints one of the feasible solutions. ''' # Initialization of Board matrix board = [[-1 for i in range(n)]for i in range(n)] # move_x and move_y define next move of Knight. # move_x is for next value of x coordinate # move_y is for next value of y coordinate move_x = [2, 1, -1, -2, -2, -1, 1, 2] move_y = [1, 2, 2, 1, -1, -2, -2, -1] # Since the Knight is initially at the first block board[0][0] = 0 # Step counter for knight's position pos = 1 # Checking if solution exists or not if(not solveKTUtil(n, board, 0, 0, move_x, move_y, pos)): print(\"Solution does not exist\") else: printSolution(n, board) def solveKTUtil(n, board, curr_x, curr_y, move_x, move_y, pos): ''' A recursive utility function to solve Knight Tour problem ''' if(pos == n**2): return True # Try all next moves from the current coordinate x, y for i in range(8): new_x = curr_x + move_x[i] new_y = curr_y + move_y[i] if(isSafe(new_x, new_y, board)): board[new_x][new_y] = pos if(solveKTUtil(n, board, new_x, new_y, move_x, move_y, pos+1)): return True # Backtracking board[new_x][new_y] = -1 return False # Driver Codeif __name__ == \"__main__\": # Function Call solveKT(n) # This code is contributed by AAKASH PAL",
"e": 13707,
"s": 11442,
"text": null
},
{
"code": "// C# program for// Knight Tour problemusing System; class GFG { static int N = 8; /* A utility function to check if i,j are valid indexes for N*N chessboard */ static bool isSafe(int x, int y, int[, ] sol) { return (x >= 0 && x < N && y >= 0 && y < N && sol[x, y] == -1); } /* A utility function to print solution matrix sol[N][N] */ static void printSolution(int[, ] sol) { for (int x = 0; x < N; x++) { for (int y = 0; y < N; y++) Console.Write(sol[x, y] + \" \"); Console.WriteLine(); } } /* This function solves the Knight Tour problem using Backtracking. This function mainly uses solveKTUtil() to solve the problem. It returns false if no complete tour is possible, otherwise return true and prints the tour. Please note that there may be more than one solutions, this function prints one of the feasible solutions. */ static bool solveKT() { int[, ] sol = new int[8, 8]; /* Initialization of solution matrix */ for (int x = 0; x < N; x++) for (int y = 0; y < N; y++) sol[x, y] = -1; /* xMove[] and yMove[] define next move of Knight. xMove[] is for next value of x coordinate yMove[] is for next value of y coordinate */ int[] xMove = { 2, 1, -1, -2, -2, -1, 1, 2 }; int[] yMove = { 1, 2, 2, 1, -1, -2, -2, -1 }; // Since the Knight is // initially at the first block sol[0, 0] = 0; /* Start from 0,0 and explore all tours using solveKTUtil() */ if (!solveKTUtil(0, 0, 1, sol, xMove, yMove)) { Console.WriteLine(\"Solution does \" + \"not exist\"); return false; } else printSolution(sol); return true; } /* A recursive utility function to solve Knight Tour problem */ static bool solveKTUtil(int x, int y, int movei, int[, ] sol, int[] xMove, int[] yMove) { int k, next_x, next_y; if (movei == N * N) return true; /* Try all next moves from the current coordinate x, y */ for (k = 0; k < 8; k++) { next_x = x + xMove[k]; next_y = y + yMove[k]; if (isSafe(next_x, next_y, sol)) { sol[next_x, next_y] = movei; if (solveKTUtil(next_x, next_y, movei + 1, sol, xMove, yMove)) return true; else // backtracking sol[next_x, next_y] = -1; } } return false; } // Driver Code public static void Main() { // Function Call solveKT(); }} // This code is contributed by mits.",
"e": 16617,
"s": 13707,
"text": null
},
{
"code": "<script> // Javascript program for Knight Tour problemlet N = 8; // A utility function to check if i,j are// valid indexes for N*N chessboardfunction isSafe(x, y, sol){ return(x >= 0 && x < N && y >= 0 && y < N && sol[x][y] == -1);} // A utility function to print solution// matrix sol[N][N]function printSolution(sol){ for(let x = 0; x < N; x++) { for(let y = 0; y < N; y++) document.write(sol[x][y] + \" \"); document.write(\"<br/>\"); }} // This function solves the Knight Tour problem// using Backtracking. This function mainly// uses solveKTUtil() to solve the problem. It// returns false if no complete tour is possible,// otherwise return true and prints the tour.// Please note that there may be more than one// solutions, this function prints one of the// feasible solutions. function solveKT(){ let sol = new Array(8); for(var i = 0; i < sol.length; i++) { sol[i] = new Array(2); } // Initialization of solution matrix for(let x = 0; x < N; x++) for(let y = 0; y < N; y++) sol[x][y] = -1; // xMove[] and yMove[] define next move of Knight. // xMove[] is for next value of x coordinate // yMove[] is for next value of y coordinate let xMove = [ 2, 1, -1, -2, -2, -1, 1, 2 ]; let yMove = [ 1, 2, 2, 1, -1, -2, -2, -1 ]; // Since the Knight is initially at the first block sol[0][0] = 0; // Start from 0,0 and explore all tours using // solveKTUtil() if (!solveKTUtil(0, 0, 1, sol, xMove, yMove)) { document.write(\"Solution does not exist\"); return false; } else printSolution(sol); return true;} // A recursive utility function to solve Knight// Tour problemfunction solveKTUtil(x, y, movei, sol, xMove, yMove){ let k, next_x, next_y; if (movei == N * N) return true; // Try all next moves from the // current coordinate x, y for(k = 0; k < 8; k++) { next_x = x + xMove[k]; next_y = y + yMove[k]; if (isSafe(next_x, next_y, sol)) { sol[next_x][next_y] = movei; if (solveKTUtil(next_x, next_y, movei + 1, sol, xMove, yMove)) return true; else sol[next_x][next_y] = -1; // backtracking } } return false;} // Driver code // Function CallsolveKT(); // This code is contributed by target_2 </script>",
"e": 19056,
"s": 16617,
"text": null
},
{
"code": null,
"e": 19320,
"s": 19056,
"text": " 0 59 38 33 30 17 8 63 \n 37 34 31 60 9 62 29 16 \n 58 1 36 39 32 27 18 7 \n 35 48 41 26 61 10 15 28 \n 42 57 2 49 40 23 6 19 \n 47 50 45 54 25 20 11 14 \n 56 43 52 3 22 13 24 5 \n 51 46 55 44 53 4 21 12 "
},
{
"code": null,
"e": 19463,
"s": 19320,
"text": "Time Complexity : There are N2 Cells and for each, we have a maximum of 8 possible moves to choose from, so the worst running time is O(8N^2)."
},
{
"code": null,
"e": 19486,
"s": 19463,
"text": "Auxiliary Space: O(N2)"
},
{
"code": null,
"e": 19985,
"s": 19486,
"text": "Important Note:No order of the xMove, yMove is wrong, but they will affect the running time of the algorithm drastically. For example, think of the case where the 8th choice of the move is the correct one, and before that our code ran 7 different wrong paths. It’s always a good idea a have a heuristic than to try backtracking randomly. Like, in this case, we know the next step would probably be in the south or east direction, then checking the paths which lead their first is a better strategy."
},
{
"code": null,
"e": 20232,
"s": 19985,
"text": "Note that Backtracking is not the best solution for the Knight’s tour problem. See the below article for other better solutions. The purpose of this post is to explain Backtracking with an example. Warnsdorff’s algorithm for Knight’s tour problem"
},
{
"code": null,
"e": 20612,
"s": 20232,
"text": "References: http://see.stanford.edu/materials/icspacs106b/H19-RecBacktrackExamples.pdf http://www.cis.upenn.edu/~matuszek/cit594-2009/Lectures/35-backtracking.ppt http://mathworld.wolfram.com/KnightsTour.html http://en.wikipedia.org/wiki/Knight%27s_tour Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 20625,
"s": 20612,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 20636,
"s": 20625,
"text": "Aakash Pal"
},
{
"code": null,
"e": 20647,
"s": 20636,
"text": "skwillbesk"
},
{
"code": null,
"e": 20660,
"s": 20647,
"text": "ChetanGoyal1"
},
{
"code": null,
"e": 20678,
"s": 20660,
"text": "shubhamsingh84100"
},
{
"code": null,
"e": 20693,
"s": 20678,
"text": "yadavgaurav251"
},
{
"code": null,
"e": 20702,
"s": 20693,
"text": "target_2"
},
{
"code": null,
"e": 20712,
"s": 20702,
"text": "user_3ums"
},
{
"code": null,
"e": 20729,
"s": 20712,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 20745,
"s": 20729,
"text": "subhammahato348"
},
{
"code": null,
"e": 20757,
"s": 20745,
"text": "pujasingg43"
},
{
"code": null,
"e": 20764,
"s": 20757,
"text": "Amazon"
},
{
"code": null,
"e": 20784,
"s": 20764,
"text": "chessboard-problems"
},
{
"code": null,
"e": 20797,
"s": 20784,
"text": "Backtracking"
},
{
"code": null,
"e": 20810,
"s": 20797,
"text": "Mathematical"
},
{
"code": null,
"e": 20817,
"s": 20810,
"text": "Amazon"
},
{
"code": null,
"e": 20830,
"s": 20817,
"text": "Mathematical"
},
{
"code": null,
"e": 20843,
"s": 20830,
"text": "Backtracking"
},
{
"code": null,
"e": 20941,
"s": 20843,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 21026,
"s": 20941,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 21068,
"s": 21026,
"text": "Generate all the binary strings of N bits"
},
{
"code": null,
"e": 21121,
"s": 21068,
"text": "Print all paths from a given source to a destination"
},
{
"code": null,
"e": 21164,
"s": 21121,
"text": "Print all permutations of a string in Java"
},
{
"code": null,
"e": 21224,
"s": 21164,
"text": "Find if there is a path of more than k length from a source"
},
{
"code": null,
"e": 21254,
"s": 21224,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 21297,
"s": 21254,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 21312,
"s": 21297,
"text": "C++ Data Types"
},
{
"code": null,
"e": 21336,
"s": 21312,
"text": "Merge two sorted arrays"
}
] |
Python program to verify that a string only contains letters, numbers, underscores and dashes | 19 Aug, 2020
Prerequisite: Regular Expression in Python
Given a string, we have to find whether the string contains any letters, numbers, underscores, and dashes or not. It is usually used for verifying username and password validity. For example, the user has a string for the username of a person and the user doesn’t want the username to have any special characters such as @, $, etc.
Let’s see the different methods for solving this task:
Method 1: Using Regular Expression.
There is a function in the regular expression library(re) that compares two string for us. re.match(pattern, string) is a function that returns an object, to find whether a match is find or not we have to typecast it into boolean.
Syntax: re.match(pattern, string)
Parameters:
pattern: the pattern against which you want to check
string: the string you want to check for the pattern
Return: Match object
Let’s see an example:
Example 1:
Python3
# import libraryimport re # make a patternpattern = "^[A-Za-z0-9_-]*$" # inputstring = "G33ks_F0r_Geeks" # convert match object # into boolean valuesstate = bool(re.match(pattern, string)) print(state)
Output:
True
Example 2:
Python3
# import libraryimport re print(bool(re.match("^[A-Za-z0-9_-]*$", 'ValidString12-_'))) print(bool(re.match("^[A-Za-z0-9_-]*$", 'inv@lidstring')))
Output:
True
False
Method 2: Using Set.
Set is built-in data-type in Python. We are using issubset() function of set that returns True if all characters of a set are present in a given set Otherwise False.
Syntax: set_name.issubset(set)Parameters:
set: Represents that set in which the subset has to be searched
Return: boolean value
Let’s see an example:Example 1:
Python3
# create a set of allowed charactersallowed_chars = set(("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-")) # input stringstring = "inv@lid" # convert string into set of charactersvalidation = set((string)) # check conditionif validation.issubset(allowed_chars): print("True") else: print ("False")
Output:
False
Example 2:
Python3
allowed_chars = set("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-") string = "__Val1d__" validation = set((string)) if validation.issubset(allowed_chars): print("True") else: print ("False")
Output:
True
Python string-programs
python-string
Python
Python Programs
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()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Aug, 2020"
},
{
"code": null,
"e": 71,
"s": 28,
"text": "Prerequisite: Regular Expression in Python"
},
{
"code": null,
"e": 404,
"s": 71,
"text": "Given a string, we have to find whether the string contains any letters, numbers, underscores, and dashes or not. It is usually used for verifying username and password validity. For example, the user has a string for the username of a person and the user doesn’t want the username to have any special characters such as @, $, etc. "
},
{
"code": null,
"e": 459,
"s": 404,
"text": "Let’s see the different methods for solving this task:"
},
{
"code": null,
"e": 495,
"s": 459,
"text": "Method 1: Using Regular Expression."
},
{
"code": null,
"e": 727,
"s": 495,
"text": "There is a function in the regular expression library(re) that compares two string for us. re.match(pattern, string) is a function that returns an object, to find whether a match is find or not we have to typecast it into boolean. "
},
{
"code": null,
"e": 762,
"s": 727,
"text": "Syntax: re.match(pattern, string) "
},
{
"code": null,
"e": 774,
"s": 762,
"text": "Parameters:"
},
{
"code": null,
"e": 828,
"s": 774,
"text": "pattern: the pattern against which you want to check "
},
{
"code": null,
"e": 882,
"s": 828,
"text": "string: the string you want to check for the pattern "
},
{
"code": null,
"e": 904,
"s": 882,
"text": "Return: Match object "
},
{
"code": null,
"e": 926,
"s": 904,
"text": "Let’s see an example:"
},
{
"code": null,
"e": 937,
"s": 926,
"text": "Example 1:"
},
{
"code": null,
"e": 945,
"s": 937,
"text": "Python3"
},
{
"code": "# import libraryimport re # make a patternpattern = \"^[A-Za-z0-9_-]*$\" # inputstring = \"G33ks_F0r_Geeks\" # convert match object # into boolean valuesstate = bool(re.match(pattern, string)) print(state)",
"e": 1151,
"s": 945,
"text": null
},
{
"code": null,
"e": 1159,
"s": 1151,
"text": "Output:"
},
{
"code": null,
"e": 1164,
"s": 1159,
"text": "True"
},
{
"code": null,
"e": 1175,
"s": 1164,
"text": "Example 2:"
},
{
"code": null,
"e": 1183,
"s": 1175,
"text": "Python3"
},
{
"code": "# import libraryimport re print(bool(re.match(\"^[A-Za-z0-9_-]*$\", 'ValidString12-_'))) print(bool(re.match(\"^[A-Za-z0-9_-]*$\", 'inv@lidstring')))",
"e": 1370,
"s": 1183,
"text": null
},
{
"code": null,
"e": 1378,
"s": 1370,
"text": "Output:"
},
{
"code": null,
"e": 1389,
"s": 1378,
"text": "True\nFalse"
},
{
"code": null,
"e": 1410,
"s": 1389,
"text": "Method 2: Using Set."
},
{
"code": null,
"e": 1576,
"s": 1410,
"text": "Set is built-in data-type in Python. We are using issubset() function of set that returns True if all characters of a set are present in a given set Otherwise False."
},
{
"code": null,
"e": 1619,
"s": 1576,
"text": "Syntax: set_name.issubset(set)Parameters: "
},
{
"code": null,
"e": 1684,
"s": 1619,
"text": "set: Represents that set in which the subset has to be searched "
},
{
"code": null,
"e": 1706,
"s": 1684,
"text": "Return: boolean value"
},
{
"code": null,
"e": 1739,
"s": 1706,
"text": "Let’s see an example:Example 1: "
},
{
"code": null,
"e": 1747,
"s": 1739,
"text": "Python3"
},
{
"code": "# create a set of allowed charactersallowed_chars = set((\"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-\")) # input stringstring = \"inv@lid\" # convert string into set of charactersvalidation = set((string)) # check conditionif validation.issubset(allowed_chars): print(\"True\") else: print (\"False\")",
"e": 2078,
"s": 1747,
"text": null
},
{
"code": null,
"e": 2086,
"s": 2078,
"text": "Output:"
},
{
"code": null,
"e": 2092,
"s": 2086,
"text": "False"
},
{
"code": null,
"e": 2104,
"s": 2092,
"text": "Example 2: "
},
{
"code": null,
"e": 2112,
"s": 2104,
"text": "Python3"
},
{
"code": "allowed_chars = set(\"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-\") string = \"__Val1d__\" validation = set((string)) if validation.issubset(allowed_chars): print(\"True\") else: print (\"False\")",
"e": 2337,
"s": 2112,
"text": null
},
{
"code": null,
"e": 2345,
"s": 2337,
"text": "Output:"
},
{
"code": null,
"e": 2350,
"s": 2345,
"text": "True"
},
{
"code": null,
"e": 2373,
"s": 2350,
"text": "Python string-programs"
},
{
"code": null,
"e": 2387,
"s": 2373,
"text": "python-string"
},
{
"code": null,
"e": 2394,
"s": 2387,
"text": "Python"
},
{
"code": null,
"e": 2410,
"s": 2394,
"text": "Python Programs"
},
{
"code": null,
"e": 2508,
"s": 2410,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2526,
"s": 2508,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2568,
"s": 2526,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2590,
"s": 2568,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2625,
"s": 2590,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2651,
"s": 2625,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2694,
"s": 2651,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 2716,
"s": 2694,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2755,
"s": 2716,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2793,
"s": 2755,
"text": "Python | Convert a list to dictionary"
}
] |
Python String | max() | 08 Dec, 2021
max() is an inbuilt function in Python programming language that returns the highest alphabetical character in a string.
Syntax:
max(string)
Parameter:max() method takes a string as a parameter
Return value:
Returns a character which is alphabetically the highest character in the string.
Below is the Python implementation of the method max()
Python
# python program to demonstrate the use of # max() function # maximum alphabetical character in # "geeks" string = "geeks" print max(string) # maximum alphabetical character in # "raj"string = "raj" print max(string)
s
r
prachisoda1234
python-string
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n08 Dec, 2021"
},
{
"code": null,
"e": 174,
"s": 53,
"text": "max() is an inbuilt function in Python programming language that returns the highest alphabetical character in a string."
},
{
"code": null,
"e": 182,
"s": 174,
"text": "Syntax:"
},
{
"code": null,
"e": 194,
"s": 182,
"text": "max(string)"
},
{
"code": null,
"e": 247,
"s": 194,
"text": "Parameter:max() method takes a string as a parameter"
},
{
"code": null,
"e": 261,
"s": 247,
"text": "Return value:"
},
{
"code": null,
"e": 342,
"s": 261,
"text": "Returns a character which is alphabetically the highest character in the string."
},
{
"code": null,
"e": 397,
"s": 342,
"text": "Below is the Python implementation of the method max()"
},
{
"code": null,
"e": 404,
"s": 397,
"text": "Python"
},
{
"code": "# python program to demonstrate the use of # max() function # maximum alphabetical character in # \"geeks\" string = \"geeks\" print max(string) # maximum alphabetical character in # \"raj\"string = \"raj\" print max(string)",
"e": 624,
"s": 404,
"text": null
},
{
"code": null,
"e": 629,
"s": 624,
"text": "s\nr\n"
},
{
"code": null,
"e": 644,
"s": 629,
"text": "prachisoda1234"
},
{
"code": null,
"e": 658,
"s": 644,
"text": "python-string"
},
{
"code": null,
"e": 665,
"s": 658,
"text": "Python"
}
] |
Convert String to Double in Python3 | 08 Oct, 2021
Given a string and our task is to convert it in double. Since double datatype allows a number to have non -integer values. So conversion of string to double is the same as the conversion of string to float
This can be implemented in these two ways
1) Using float() method
Python3
str1 = "9.02"print("This is the initial string: " + str1) # Converting to doublestr2 = float(str1)print("The conversion of string to double is", str2) str2 = str2+1print("The converted string to double is incremented by 1:", str2)
Output:
This is the initial string: 9.02
The conversion of string to double is 9.02
The converted string to double is incremented by 1: 10.02
2) Using decimal() method: Since we only want a string with a number with decimal values this method can also be used
Python3
from decimal import Decimal str1 = "9.02"print("This is the initial string: " + str1) # Converting to doublestr2 = Decimal(str1)print("The conversion of string to double is", str2) str2 = str2+1print("The converted string to double is incremented by 1:", str2)
Output:
This is the initial string: 9.02
The conversion of string to double is 9.02
The converted string to double is incremented by 1: 10.02
kashishsoda
python-basics
Python-Built-in-functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Create a directory in Python | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Oct, 2021"
},
{
"code": null,
"e": 236,
"s": 28,
"text": "Given a string and our task is to convert it in double. Since double datatype allows a number to have non -integer values. So conversion of string to double is the same as the conversion of string to float "
},
{
"code": null,
"e": 278,
"s": 236,
"text": "This can be implemented in these two ways"
},
{
"code": null,
"e": 302,
"s": 278,
"text": "1) Using float() method"
},
{
"code": null,
"e": 310,
"s": 302,
"text": "Python3"
},
{
"code": "str1 = \"9.02\"print(\"This is the initial string: \" + str1) # Converting to doublestr2 = float(str1)print(\"The conversion of string to double is\", str2) str2 = str2+1print(\"The converted string to double is incremented by 1:\", str2)",
"e": 541,
"s": 310,
"text": null
},
{
"code": null,
"e": 549,
"s": 541,
"text": "Output:"
},
{
"code": null,
"e": 683,
"s": 549,
"text": "This is the initial string: 9.02\nThe conversion of string to double is 9.02\nThe converted string to double is incremented by 1: 10.02"
},
{
"code": null,
"e": 802,
"s": 683,
"text": "2) Using decimal() method: Since we only want a string with a number with decimal values this method can also be used"
},
{
"code": null,
"e": 810,
"s": 802,
"text": "Python3"
},
{
"code": "from decimal import Decimal str1 = \"9.02\"print(\"This is the initial string: \" + str1) # Converting to doublestr2 = Decimal(str1)print(\"The conversion of string to double is\", str2) str2 = str2+1print(\"The converted string to double is incremented by 1:\", str2)",
"e": 1072,
"s": 810,
"text": null
},
{
"code": null,
"e": 1080,
"s": 1072,
"text": "Output:"
},
{
"code": null,
"e": 1214,
"s": 1080,
"text": "This is the initial string: 9.02\nThe conversion of string to double is 9.02\nThe converted string to double is incremented by 1: 10.02"
},
{
"code": null,
"e": 1226,
"s": 1214,
"text": "kashishsoda"
},
{
"code": null,
"e": 1240,
"s": 1226,
"text": "python-basics"
},
{
"code": null,
"e": 1266,
"s": 1240,
"text": "Python-Built-in-functions"
},
{
"code": null,
"e": 1273,
"s": 1266,
"text": "Python"
},
{
"code": null,
"e": 1371,
"s": 1273,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1403,
"s": 1371,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1430,
"s": 1403,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1461,
"s": 1430,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 1484,
"s": 1461,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1505,
"s": 1484,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1561,
"s": 1505,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 1603,
"s": 1561,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 1645,
"s": 1603,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 1684,
"s": 1645,
"text": "Python | Get unique values from a list"
}
] |
Overriding toString() Method in Java | 25 Feb, 2022
Java being object-oriented only deals with classes and objects so do if we do require any computation we use the help of object/s corresponding to the class. It is the most frequent method of Java been used to get a string representation of an object. Now you must be wondering that till now they were not using the same but getting string representation or in short output on the console while using System.out.print. It is because this method was getting automatically called when the print statement is written. So this method is overridden in order to return the values of the object which is showcased below via examples.
Example 1:
Java
// file name: Main.java class Complex { private double re, im; public Complex(double re, double im) { this.re = re; this.im = im; }} // Driver class to test the Complex classpublic class Main { public static void main(String[] args) { Complex c1 = new Complex(10, 15); System.out.println(c1); }}
Complex@214c265e
Output Explanation: The output is the class name, then ‘at’ sign, and at the end hashCode of the object. All classes in Java inherit from the Object class, directly or indirectly (See point 1 of this). The Object class has some basic methods like clone(), toString(), equals(),.. etc. The default toString() method in Object prints “class name @ hash code”. We can override the toString() method in our class to print proper output. For example, in the following code toString() is overridden to print the “Real + i Imag” form.
Example 2:
Java
// Java Program to illustrate Overriding// toString() Method // Class 1public class GFG { // Main driver method public static void main(String[] args) { // Creating object of class1 // inside main() method Complex c1 = new Complex(10, 15); // Printing the complex number System.out.println(c1); }}// Class 2// Helper classclass Complex { // Attributes of a complex number private double re, im; // Constructor to initialize a complex number // Default // public Complex() { // this.re = 0; // this.im = 0; // } // Constructor 2: Parameterized public Complex(double re, double im) { // This keyword refers to // current complex number this.re = re; this.im = im; } // Getters public double getReal() { return this.re; } public double getImaginary() { return this.im ; } // Setters public void setReal(double re) { this.re = re; } public void setImaginary(double im) { this.im = im; } // Overriding toString() method of String class @Override public String toString() { return this.re + " + " + this.im + "i"; }}
10.0 + 15.0i
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
solankimayank
simranarora5sos
java-overriding
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n25 Feb, 2022"
},
{
"code": null,
"e": 679,
"s": 52,
"text": "Java being object-oriented only deals with classes and objects so do if we do require any computation we use the help of object/s corresponding to the class. It is the most frequent method of Java been used to get a string representation of an object. Now you must be wondering that till now they were not using the same but getting string representation or in short output on the console while using System.out.print. It is because this method was getting automatically called when the print statement is written. So this method is overridden in order to return the values of the object which is showcased below via examples."
},
{
"code": null,
"e": 690,
"s": 679,
"text": "Example 1:"
},
{
"code": null,
"e": 695,
"s": 690,
"text": "Java"
},
{
"code": "// file name: Main.java class Complex { private double re, im; public Complex(double re, double im) { this.re = re; this.im = im; }} // Driver class to test the Complex classpublic class Main { public static void main(String[] args) { Complex c1 = new Complex(10, 15); System.out.println(c1); }}",
"e": 1044,
"s": 695,
"text": null
},
{
"code": null,
"e": 1061,
"s": 1044,
"text": "Complex@214c265e"
},
{
"code": null,
"e": 1589,
"s": 1061,
"text": "Output Explanation: The output is the class name, then ‘at’ sign, and at the end hashCode of the object. All classes in Java inherit from the Object class, directly or indirectly (See point 1 of this). The Object class has some basic methods like clone(), toString(), equals(),.. etc. The default toString() method in Object prints “class name @ hash code”. We can override the toString() method in our class to print proper output. For example, in the following code toString() is overridden to print the “Real + i Imag” form."
},
{
"code": null,
"e": 1600,
"s": 1589,
"text": "Example 2:"
},
{
"code": null,
"e": 1605,
"s": 1600,
"text": "Java"
},
{
"code": "// Java Program to illustrate Overriding// toString() Method // Class 1public class GFG { // Main driver method public static void main(String[] args) { // Creating object of class1 // inside main() method Complex c1 = new Complex(10, 15); // Printing the complex number System.out.println(c1); }}// Class 2// Helper classclass Complex { // Attributes of a complex number private double re, im; // Constructor to initialize a complex number // Default // public Complex() { // this.re = 0; // this.im = 0; // } // Constructor 2: Parameterized public Complex(double re, double im) { // This keyword refers to // current complex number this.re = re; this.im = im; } // Getters public double getReal() { return this.re; } public double getImaginary() { return this.im ; } // Setters public void setReal(double re) { this.re = re; } public void setImaginary(double im) { this.im = im; } // Overriding toString() method of String class @Override public String toString() { return this.re + \" + \" + this.im + \"i\"; }}",
"e": 2853,
"s": 1605,
"text": null
},
{
"code": null,
"e": 2869,
"s": 2856,
"text": "10.0 + 15.0i"
},
{
"code": null,
"e": 2997,
"s": 2871,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 3013,
"s": 2999,
"text": "solankimayank"
},
{
"code": null,
"e": 3029,
"s": 3013,
"text": "simranarora5sos"
},
{
"code": null,
"e": 3045,
"s": 3029,
"text": "java-overriding"
},
{
"code": null,
"e": 3050,
"s": 3045,
"text": "Java"
},
{
"code": null,
"e": 3055,
"s": 3050,
"text": "Java"
}
] |
Python Program for Merge Sort | 17 Jan, 2022
Merge Sort is a Divide and Conquer algorithm. It divides input array in two halves, calls itself for the two halves and then merges the two sorted halves. The merge() function is used for merging two halves. The merge(arr, l, m, r) is key process that assumes that arr[l..m] and arr[m+1..r] are sorted and merges the two sorted sub-arrays into one.
Python3
# Python program for implementation of MergeSort # Merges two subarrays of arr[].# First subarray is arr[l..m]# Second subarray is arr[m+1..r] def merge(arr, l, m, r): n1 = m - l + 1 n2 = r - m # create temp arrays L = [0] * (n1) R = [0] * (n2) # Copy data to temp arrays L[] and R[] for i in range(0, n1): L[i] = arr[l + i] for j in range(0, n2): R[j] = arr[m + 1 + j] # Merge the temp arrays back into arr[l..r] i = 0 # Initial index of first subarray j = 0 # Initial index of second subarray k = l # Initial index of merged subarray while i < n1 and j < n2: if L[i] <= R[j]: arr[k] = L[i] i += 1 else: arr[k] = R[j] j += 1 k += 1 # Copy the remaining elements of L[], if there # are any while i < n1: arr[k] = L[i] i += 1 k += 1 # Copy the remaining elements of R[], if there # are any while j < n2: arr[k] = R[j] j += 1 k += 1 # l is for left index and r is right index of the# sub-array of arr to be sorted def mergeSort(arr, l, r): if l < r: # Same as (l+r)//2, but avoids overflow for # large l and h m = l+(r-l)//2 # Sort first and second halves mergeSort(arr, l, m) mergeSort(arr, m+1, r) merge(arr, l, m, r) # Driver code to test abovearr = [12, 11, 13, 5, 6, 7]n = len(arr)print("Given array is")for i in range(n): print("%d" % arr[i],end=" ") mergeSort(arr, 0, n-1)print("\n\nSorted array is")for i in range(n): print("%d" % arr[i],end=" ") # This code is contributed by Mohit Kumra
Given array is
12 11 13 5 6 7
Sorted array is
5 6 7 11 12 13
Please refer complete article on Merge Sort for more details!
the_alphaEye
amartyaghoshgfg
Merge Sort
Python Programs
Merge Sort
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
Python program to check whether a number is Prime or not
Python program to add two numbers
Python Program for Binary Search (Recursive and Iterative)
Python Program for factorial of a number
Python program to find second largest number in a list
Iterate over characters of a string in Python
Python | Convert set into a list | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n17 Jan, 2022"
},
{
"code": null,
"e": 405,
"s": 54,
"text": "Merge Sort is a Divide and Conquer algorithm. It divides input array in two halves, calls itself for the two halves and then merges the two sorted halves. The merge() function is used for merging two halves. The merge(arr, l, m, r) is key process that assumes that arr[l..m] and arr[m+1..r] are sorted and merges the two sorted sub-arrays into one. "
},
{
"code": null,
"e": 413,
"s": 405,
"text": "Python3"
},
{
"code": "# Python program for implementation of MergeSort # Merges two subarrays of arr[].# First subarray is arr[l..m]# Second subarray is arr[m+1..r] def merge(arr, l, m, r): n1 = m - l + 1 n2 = r - m # create temp arrays L = [0] * (n1) R = [0] * (n2) # Copy data to temp arrays L[] and R[] for i in range(0, n1): L[i] = arr[l + i] for j in range(0, n2): R[j] = arr[m + 1 + j] # Merge the temp arrays back into arr[l..r] i = 0 # Initial index of first subarray j = 0 # Initial index of second subarray k = l # Initial index of merged subarray while i < n1 and j < n2: if L[i] <= R[j]: arr[k] = L[i] i += 1 else: arr[k] = R[j] j += 1 k += 1 # Copy the remaining elements of L[], if there # are any while i < n1: arr[k] = L[i] i += 1 k += 1 # Copy the remaining elements of R[], if there # are any while j < n2: arr[k] = R[j] j += 1 k += 1 # l is for left index and r is right index of the# sub-array of arr to be sorted def mergeSort(arr, l, r): if l < r: # Same as (l+r)//2, but avoids overflow for # large l and h m = l+(r-l)//2 # Sort first and second halves mergeSort(arr, l, m) mergeSort(arr, m+1, r) merge(arr, l, m, r) # Driver code to test abovearr = [12, 11, 13, 5, 6, 7]n = len(arr)print(\"Given array is\")for i in range(n): print(\"%d\" % arr[i],end=\" \") mergeSort(arr, 0, n-1)print(\"\\n\\nSorted array is\")for i in range(n): print(\"%d\" % arr[i],end=\" \") # This code is contributed by Mohit Kumra",
"e": 2068,
"s": 413,
"text": null
},
{
"code": null,
"e": 2132,
"s": 2068,
"text": "Given array is\n12 11 13 5 6 7 \n\nSorted array is\n5 6 7 11 12 13 "
},
{
"code": null,
"e": 2195,
"s": 2132,
"text": "Please refer complete article on Merge Sort for more details! "
},
{
"code": null,
"e": 2208,
"s": 2195,
"text": "the_alphaEye"
},
{
"code": null,
"e": 2224,
"s": 2208,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 2235,
"s": 2224,
"text": "Merge Sort"
},
{
"code": null,
"e": 2251,
"s": 2235,
"text": "Python Programs"
},
{
"code": null,
"e": 2262,
"s": 2251,
"text": "Merge Sort"
},
{
"code": null,
"e": 2360,
"s": 2262,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2398,
"s": 2360,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 2447,
"s": 2398,
"text": "Python | Convert string dictionary to dictionary"
},
{
"code": null,
"e": 2484,
"s": 2447,
"text": "Python Program for Fibonacci numbers"
},
{
"code": null,
"e": 2541,
"s": 2484,
"text": "Python program to check whether a number is Prime or not"
},
{
"code": null,
"e": 2575,
"s": 2541,
"text": "Python program to add two numbers"
},
{
"code": null,
"e": 2634,
"s": 2575,
"text": "Python Program for Binary Search (Recursive and Iterative)"
},
{
"code": null,
"e": 2675,
"s": 2634,
"text": "Python Program for factorial of a number"
},
{
"code": null,
"e": 2730,
"s": 2675,
"text": "Python program to find second largest number in a list"
},
{
"code": null,
"e": 2776,
"s": 2730,
"text": "Iterate over characters of a string in Python"
}
] |
Populate null columns in a MySQL table and set values | For this, you can use IS NULL property. Let us first create a table −
mysql> create table DemoTable
(
ProductPrice int,
ProductQuantity int,
TotalAmount int
);
Query OK, 0 rows affected (1.22 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable(ProductPrice,ProductQuantity) values(100,2);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable(ProductPrice,ProductQuantity) values(500,4);
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable(ProductPrice,ProductQuantity) values(1000,10);
Query OK, 1 row affected (0.21 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+--------------+-----------------+-------------+
| ProductPrice | ProductQuantity | TotalAmount |
+--------------+-----------------+-------------+
| 100 | 2 | NULL |
| 500 | 4 | NULL |
| 1000 | 10 | NULL |
+--------------+-----------------+-------------+
3 rows in set (0.00 sec)
Here is the query to populate NULL columns −
mysql> update DemoTable set TotalAmount=(ProductPrice*ProductQuantity) where
TotalAmount IS NULL;
Query OK, 3 rows affected (0.20 sec)
Rows matched: 3 Changed: 3 Warnings: 0
Let us check the table records once again −
mysql> select *from DemoTable;
This will produce the following output −
+--------------+-----------------+-------------+
| ProductPrice | ProductQuantity | TotalAmount |
+--------------+-----------------+-------------+
| 100 | 2 | 200 |
| 500 | 4 | 2000 |
| 1000 | 10 | 10000 |
+--------------+-----------------+-------------+
3 rows in set (0.00 sec) | [
{
"code": null,
"e": 1257,
"s": 1187,
"text": "For this, you can use IS NULL property. Let us first create a table −"
},
{
"code": null,
"e": 1393,
"s": 1257,
"text": "mysql> create table DemoTable\n(\n ProductPrice int,\n ProductQuantity int,\n TotalAmount int\n);\nQuery OK, 0 rows affected (1.22 sec)"
},
{
"code": null,
"e": 1449,
"s": 1393,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1781,
"s": 1449,
"text": "mysql> insert into DemoTable(ProductPrice,ProductQuantity) values(100,2);\nQuery OK, 1 row affected (0.17 sec)\nmysql> insert into DemoTable(ProductPrice,ProductQuantity) values(500,4);\nQuery OK, 1 row affected (0.23 sec)\nmysql> insert into DemoTable(ProductPrice,ProductQuantity) values(1000,10);\nQuery OK, 1 row affected (0.21 sec)"
},
{
"code": null,
"e": 1841,
"s": 1781,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1872,
"s": 1841,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 1913,
"s": 1872,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2281,
"s": 1913,
"text": "+--------------+-----------------+-------------+\n| ProductPrice | ProductQuantity | TotalAmount |\n+--------------+-----------------+-------------+\n| 100 | 2 | NULL |\n| 500 | 4 | NULL |\n| 1000 | 10 | NULL |\n+--------------+-----------------+-------------+\n3 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2326,
"s": 2281,
"text": "Here is the query to populate NULL columns −"
},
{
"code": null,
"e": 2500,
"s": 2326,
"text": "mysql> update DemoTable set TotalAmount=(ProductPrice*ProductQuantity) where\nTotalAmount IS NULL;\nQuery OK, 3 rows affected (0.20 sec)\nRows matched: 3 Changed: 3 Warnings: 0"
},
{
"code": null,
"e": 2544,
"s": 2500,
"text": "Let us check the table records once again −"
},
{
"code": null,
"e": 2575,
"s": 2544,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 2616,
"s": 2575,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2984,
"s": 2616,
"text": "+--------------+-----------------+-------------+\n| ProductPrice | ProductQuantity | TotalAmount |\n+--------------+-----------------+-------------+\n| 100 | 2 | 200 |\n| 500 | 4 | 2000 |\n| 1000 | 10 | 10000 |\n+--------------+-----------------+-------------+\n3 rows in set (0.00 sec)"
}
] |
Python | Ways to check if given string contains only letter | 21 Jul, 2021
Given a string, write a Python program to find whether a string contains only letters and no other keywords. Let’s discuss a few methods to complete the task.
Method #1: Using isalpha() method
Python3
# Python code to demonstrate# to find whether string contains# only letters # Initialising stringini_str = "ababababa" # Printing initial stringprint ("Initial String", ini_str) # Code to check whether string contains only numberif ini_str.isalpha(): print("String contains only letters")else: print("String doesn't contains only letters")
Method #2: Using re
Python3
# Python code to demonstrate# to find whether string contains# only lettersimport re # Initialising stringini_str = "ababababa" # Printing initial stringprint ("Initial String", ini_str) # Code to check whether string contains only numberpattern = re.compile("^[a-zA-Z]+$")if pattern.match(ini_str): print ("Contains only letters")else: print ("Doesn't contains only letters")
sagar0719kumar
Python string-programs
Python
Python Programs
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()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Jul, 2021"
},
{
"code": null,
"e": 187,
"s": 28,
"text": "Given a string, write a Python program to find whether a string contains only letters and no other keywords. Let’s discuss a few methods to complete the task."
},
{
"code": null,
"e": 222,
"s": 187,
"text": "Method #1: Using isalpha() method "
},
{
"code": null,
"e": 230,
"s": 222,
"text": "Python3"
},
{
"code": "# Python code to demonstrate# to find whether string contains# only letters # Initialising stringini_str = \"ababababa\" # Printing initial stringprint (\"Initial String\", ini_str) # Code to check whether string contains only numberif ini_str.isalpha(): print(\"String contains only letters\")else: print(\"String doesn't contains only letters\")",
"e": 576,
"s": 230,
"text": null
},
{
"code": null,
"e": 599,
"s": 576,
"text": " Method #2: Using re "
},
{
"code": null,
"e": 607,
"s": 599,
"text": "Python3"
},
{
"code": "# Python code to demonstrate# to find whether string contains# only lettersimport re # Initialising stringini_str = \"ababababa\" # Printing initial stringprint (\"Initial String\", ini_str) # Code to check whether string contains only numberpattern = re.compile(\"^[a-zA-Z]+$\")if pattern.match(ini_str): print (\"Contains only letters\")else: print (\"Doesn't contains only letters\")",
"e": 990,
"s": 607,
"text": null
},
{
"code": null,
"e": 1005,
"s": 990,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 1028,
"s": 1005,
"text": "Python string-programs"
},
{
"code": null,
"e": 1035,
"s": 1028,
"text": "Python"
},
{
"code": null,
"e": 1051,
"s": 1035,
"text": "Python Programs"
},
{
"code": null,
"e": 1149,
"s": 1051,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1167,
"s": 1149,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1209,
"s": 1167,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1231,
"s": 1209,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1266,
"s": 1231,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 1292,
"s": 1266,
"text": "Python String | replace()"
},
{
"code": null,
"e": 1335,
"s": 1292,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 1357,
"s": 1335,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 1396,
"s": 1357,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 1434,
"s": 1396,
"text": "Python | Convert a list to dictionary"
}
] |
How to find If a given String contains only letters in Java? | To verify whether a given String contains only characters −
Read the String.
Convert all the characters in the given String to lower case using the toLower() method.
Convert it into a character array using the toCharArray() method of the String class.
Find whether every character in the array is in between a and z, if not, return false.
Following Java program accepts a String from the user and displays whether it is valid or not.
import java.util.Scanner;
public class StringValidation{
public boolean validtaeString(String str) {
str = str.toLowerCase();
char[] charArray = str.toCharArray();
for (int i = 0; i < charArray.length; i++) {
char ch = charArray[i];
if (!(ch >= 'a' && ch <= 'z')) {
return false;
}
}
return true;
}
public static void main(String args[]) {
Scanner sc= new Scanner(System.in);
System.out.println("Enter a string value: ");
String str = sc.next();
StringValidation obj = new StringValidation();
boolean bool = obj.validtaeString(str);
if(!bool) {
System.out.println("Given String is invalid");
}else{
System.out.println("Given String is valid");
}
}
}
Enter a string value:
24ABCjhon
Given String is invalid | [
{
"code": null,
"e": 1122,
"s": 1062,
"text": "To verify whether a given String contains only characters −"
},
{
"code": null,
"e": 1139,
"s": 1122,
"text": "Read the String."
},
{
"code": null,
"e": 1228,
"s": 1139,
"text": "Convert all the characters in the given String to lower case using the toLower() method."
},
{
"code": null,
"e": 1314,
"s": 1228,
"text": "Convert it into a character array using the toCharArray() method of the String class."
},
{
"code": null,
"e": 1401,
"s": 1314,
"text": "Find whether every character in the array is in between a and z, if not, return false."
},
{
"code": null,
"e": 1496,
"s": 1401,
"text": "Following Java program accepts a String from the user and displays whether it is valid or not."
},
{
"code": null,
"e": 2293,
"s": 1496,
"text": "import java.util.Scanner;\npublic class StringValidation{\n public boolean validtaeString(String str) {\n str = str.toLowerCase();\n char[] charArray = str.toCharArray();\n for (int i = 0; i < charArray.length; i++) {\n char ch = charArray[i];\n if (!(ch >= 'a' && ch <= 'z')) {\n return false;\n }\n }\n return true;\n }\n public static void main(String args[]) {\n Scanner sc= new Scanner(System.in);\n System.out.println(\"Enter a string value: \");\n String str = sc.next();\n StringValidation obj = new StringValidation();\n boolean bool = obj.validtaeString(str);\n if(!bool) {\n System.out.println(\"Given String is invalid\");\n }else{\n System.out.println(\"Given String is valid\");\n }\n }\n}"
},
{
"code": null,
"e": 2349,
"s": 2293,
"text": "Enter a string value:\n24ABCjhon\nGiven String is invalid"
}
] |
Number of unique triplets whose XOR is zero - GeeksforGeeks | 21 May, 2021
Given N numbers with no duplicates, count the number of unique triplets (ai, aj, ak) such that their XOR is 0. A triplet is said to be unique if all of the three numbers in the triplet are unique.
Examples:
Input : a[] = {1, 3, 5, 10, 14, 15};
Output : 2
Explanation : {1, 14, 15} and {5, 10, 15} are the
unique triplets whose XOR is 0.
{1, 14, 15} and all other combinations of
1, 14, 15 are considered as 1 only.
Input : a[] = {4, 7, 5, 8, 3, 9};
Output : 1
Explanation : {4, 7, 3} is the only triplet whose XOR is 0
Naive Approach: A naive approach is to run three nested loops, the first runs from 0 to n, the second from i+1 to n, and the last one from j+1 to n to get the unique triplets. Calculate the XOR of ai, aj, ak, check if it equals 0. If so, then increase the count. Time Complexity: O(n3)
Efficient Approach: An efficient approach is to use one of the properties of XOR: the XOR of two of the same numbers gives 0. So we need to calculate the XOR of unique pairs only, and if the calculated XOR is one of the array elements, then we get the triplet whose XOR is 0. Given below are the steps for counting the number of unique triplets:Below is the complete algorithm for this approach:
With the map, mark all the array elements.Run two nested loops, one from i-n-1, and the other from i+1-n to get all the pairs.Obtain the XOR of the pair.Check if the XOR is an array element and not one of ai or aj.Increase the count if the condition holds.Return count/3 as we only want unique triplets. Since i-n and j+1-n give us unique pairs but not triplets, we do a count/3 to remove the other two possible combinations.
With the map, mark all the array elements.
Run two nested loops, one from i-n-1, and the other from i+1-n to get all the pairs.
Obtain the XOR of the pair.
Check if the XOR is an array element and not one of ai or aj.
Increase the count if the condition holds.
Return count/3 as we only want unique triplets. Since i-n and j+1-n give us unique pairs but not triplets, we do a count/3 to remove the other two possible combinations.
Below is the implementation of the above idea:
C++
Java
Python3
C#
Javascript
// CPP program to count the number of// unique triplets whose XOR is 0#include <bits/stdc++.h>using namespace std; // function to count the number of// unique triplets whose xor is 0int countTriplets(int a[], int n){ // To store values that are present unordered_set<int> s; for (int i = 0; i < n; i++) s.insert(a[i]); // stores the count of unique triplets int count = 0; // traverse for all i, j pairs such that j>i for (int i = 0; i < n-1; i++) { for (int j = i + 1; j < n; j++) { // xor of a[i] and a[j] int xr = a[i] ^ a[j]; // if xr of two numbers is present, // then increase the count if (s.find(xr) != s.end() && xr != a[i] && xr != a[j]) count++; } } // returns answer return count / 3;} // Driver code to test above functionint main(){ int a[] = {1, 3, 5, 10, 14, 15}; int n = sizeof(a) / sizeof(a[0]); cout << countTriplets(a, n); return 0;}
// Java program to count// the number of unique// triplets whose XOR is 0import java.io.*;import java.util.*; class GFG{ // function to count the // number of unique triplets // whose xor is 0 static int countTriplets(int []a, int n) { // To store values // that are present ArrayList<Integer> s = new ArrayList<Integer>(); for (int i = 0; i < n; i++) s.add(a[i]); // stores the count // of unique triplets int count = 0; // traverse for all i, // j pairs such that j>i for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { // xor of a[i] and a[j] int xr = a[i] ^ a[j]; // if xr of two numbers // is present, then // increase the count if (s.contains(xr) && xr != a[i] && xr != a[j]) count++; } } // returns answer return count / 3; } // Driver code public static void main(String srgs[]) { int []a = {1, 3, 5, 10, 14, 15}; int n = a.length; System.out.print(countTriplets(a, n)); }} // This code is contributed by// Manish Shaw(manishshaw1)
# Python 3 program to count the number of# unique triplets whose XOR is 0 # function to count the number of# unique triplets whose xor is 0def countTriplets(a, n): # To store values that are present s = set() for i in range(n): s.add(a[i]) # stores the count of unique triplets count = 0 # traverse for all i, j pairs such that j>i for i in range(n): for j in range(i + 1, n, 1): # xor of a[i] and a[j] xr = a[i] ^ a[j] # if xr of two numbers is present, # then increase the count if (xr in s and xr != a[i] and xr != a[j]): count += 1; # returns answer return int(count / 3) # Driver codeif __name__ == '__main__': a = [1, 3, 5, 10, 14, 15] n = len(a) print(countTriplets(a, n)) # This code is contributed by# Surendra_Gangwar
// C# program to count// the number of unique// triplets whose XOR is 0using System;using System.Collections.Generic; class GFG{ // function to count the // number of unique triplets // whose xor is 0 static int countTriplets(int []a, int n) { // To store values // that are present List<int> s = new List<int>(); for (int i = 0; i < n; i++) s.Add(a[i]); // stores the count // of unique triplets int count = 0; // traverse for all i, // j pairs such that j>i for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { // xor of a[i] and a[j] int xr = a[i] ^ a[j]; // if xr of two numbers // is present, then // increase the count if (s.Exists(item => item == xr) && xr != a[i] && xr != a[j]) count++; } } // returns answer return count / 3; } // Driver code static void Main() { int []a = new int[]{1, 3, 5, 10, 14, 15}; int n = a.Length; Console.Write(countTriplets(a, n)); }} // This code is contributed by// Manish Shaw(manishshaw1)
<script> // javascript program to count // the number of unique // triplets whose XOR is 0 // function to count the // number of unique triplets // whose xor is 0 function countTriplets(a , n) { // To store values // that are present var s = []; for (i = 0; i < n; i++) s.push(a[i]); // stores the count // of unique triplets var count = 0; // traverse for all i, // j pairs such that j>i for (i = 0; i < n; i++) { for (j = i + 1; j < n; j++) { // xor of a[i] and a[j] var xr = a[i] ^ a[j]; // if xr of two numbers // is present, then // increase the count if (s.includes(xr) && xr != a[i] && xr != a[j]) count++; } } // returns answer return count / 3; } // Driver code var a = [ 1, 3, 5, 10, 14, 15 ]; var n = a.length; document.write(countTriplets(a, n)); // This code contributed by Rajput-Ji</script>
Output:
2
Time Complexity: O(n2)
manishshaw1
SURENDRA_GANGWAR
yepitsme
Rajput-Ji
Bitwise-XOR
cpp-unordered_set
Arrays
Bit Magic
Searching
Arrays
Searching
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
Introduction to Arrays
Multidimensional Arrays in Java
Linear Search
Bitwise Operators in C/C++
Left Shift and Right Shift Operators in C/C++
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Count set bits in an integer
Cyclic Redundancy Check and Modulo-2 Division | [
{
"code": null,
"e": 24773,
"s": 24745,
"text": "\n21 May, 2021"
},
{
"code": null,
"e": 24971,
"s": 24773,
"text": "Given N numbers with no duplicates, count the number of unique triplets (ai, aj, ak) such that their XOR is 0. A triplet is said to be unique if all of the three numbers in the triplet are unique. "
},
{
"code": null,
"e": 24982,
"s": 24971,
"text": "Examples: "
},
{
"code": null,
"e": 25342,
"s": 24982,
"text": "Input : a[] = {1, 3, 5, 10, 14, 15};\nOutput : 2 \nExplanation : {1, 14, 15} and {5, 10, 15} are the \n unique triplets whose XOR is 0. \n {1, 14, 15} and all other combinations of \n 1, 14, 15 are considered as 1 only.\n\nInput : a[] = {4, 7, 5, 8, 3, 9};\nOutput : 1\nExplanation : {4, 7, 3} is the only triplet whose XOR is 0 "
},
{
"code": null,
"e": 25628,
"s": 25342,
"text": "Naive Approach: A naive approach is to run three nested loops, the first runs from 0 to n, the second from i+1 to n, and the last one from j+1 to n to get the unique triplets. Calculate the XOR of ai, aj, ak, check if it equals 0. If so, then increase the count. Time Complexity: O(n3)"
},
{
"code": null,
"e": 26026,
"s": 25628,
"text": "Efficient Approach: An efficient approach is to use one of the properties of XOR: the XOR of two of the same numbers gives 0. So we need to calculate the XOR of unique pairs only, and if the calculated XOR is one of the array elements, then we get the triplet whose XOR is 0. Given below are the steps for counting the number of unique triplets:Below is the complete algorithm for this approach: "
},
{
"code": null,
"e": 26452,
"s": 26026,
"text": "With the map, mark all the array elements.Run two nested loops, one from i-n-1, and the other from i+1-n to get all the pairs.Obtain the XOR of the pair.Check if the XOR is an array element and not one of ai or aj.Increase the count if the condition holds.Return count/3 as we only want unique triplets. Since i-n and j+1-n give us unique pairs but not triplets, we do a count/3 to remove the other two possible combinations."
},
{
"code": null,
"e": 26495,
"s": 26452,
"text": "With the map, mark all the array elements."
},
{
"code": null,
"e": 26580,
"s": 26495,
"text": "Run two nested loops, one from i-n-1, and the other from i+1-n to get all the pairs."
},
{
"code": null,
"e": 26608,
"s": 26580,
"text": "Obtain the XOR of the pair."
},
{
"code": null,
"e": 26670,
"s": 26608,
"text": "Check if the XOR is an array element and not one of ai or aj."
},
{
"code": null,
"e": 26713,
"s": 26670,
"text": "Increase the count if the condition holds."
},
{
"code": null,
"e": 26883,
"s": 26713,
"text": "Return count/3 as we only want unique triplets. Since i-n and j+1-n give us unique pairs but not triplets, we do a count/3 to remove the other two possible combinations."
},
{
"code": null,
"e": 26932,
"s": 26883,
"text": "Below is the implementation of the above idea: "
},
{
"code": null,
"e": 26936,
"s": 26932,
"text": "C++"
},
{
"code": null,
"e": 26941,
"s": 26936,
"text": "Java"
},
{
"code": null,
"e": 26949,
"s": 26941,
"text": "Python3"
},
{
"code": null,
"e": 26952,
"s": 26949,
"text": "C#"
},
{
"code": null,
"e": 26963,
"s": 26952,
"text": "Javascript"
},
{
"code": "// CPP program to count the number of// unique triplets whose XOR is 0#include <bits/stdc++.h>using namespace std; // function to count the number of// unique triplets whose xor is 0int countTriplets(int a[], int n){ // To store values that are present unordered_set<int> s; for (int i = 0; i < n; i++) s.insert(a[i]); // stores the count of unique triplets int count = 0; // traverse for all i, j pairs such that j>i for (int i = 0; i < n-1; i++) { for (int j = i + 1; j < n; j++) { // xor of a[i] and a[j] int xr = a[i] ^ a[j]; // if xr of two numbers is present, // then increase the count if (s.find(xr) != s.end() && xr != a[i] && xr != a[j]) count++; } } // returns answer return count / 3;} // Driver code to test above functionint main(){ int a[] = {1, 3, 5, 10, 14, 15}; int n = sizeof(a) / sizeof(a[0]); cout << countTriplets(a, n); return 0;}",
"e": 28000,
"s": 26963,
"text": null
},
{
"code": "// Java program to count// the number of unique// triplets whose XOR is 0import java.io.*;import java.util.*; class GFG{ // function to count the // number of unique triplets // whose xor is 0 static int countTriplets(int []a, int n) { // To store values // that are present ArrayList<Integer> s = new ArrayList<Integer>(); for (int i = 0; i < n; i++) s.add(a[i]); // stores the count // of unique triplets int count = 0; // traverse for all i, // j pairs such that j>i for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { // xor of a[i] and a[j] int xr = a[i] ^ a[j]; // if xr of two numbers // is present, then // increase the count if (s.contains(xr) && xr != a[i] && xr != a[j]) count++; } } // returns answer return count / 3; } // Driver code public static void main(String srgs[]) { int []a = {1, 3, 5, 10, 14, 15}; int n = a.length; System.out.print(countTriplets(a, n)); }} // This code is contributed by// Manish Shaw(manishshaw1)",
"e": 29370,
"s": 28000,
"text": null
},
{
"code": "# Python 3 program to count the number of# unique triplets whose XOR is 0 # function to count the number of# unique triplets whose xor is 0def countTriplets(a, n): # To store values that are present s = set() for i in range(n): s.add(a[i]) # stores the count of unique triplets count = 0 # traverse for all i, j pairs such that j>i for i in range(n): for j in range(i + 1, n, 1): # xor of a[i] and a[j] xr = a[i] ^ a[j] # if xr of two numbers is present, # then increase the count if (xr in s and xr != a[i] and xr != a[j]): count += 1; # returns answer return int(count / 3) # Driver codeif __name__ == '__main__': a = [1, 3, 5, 10, 14, 15] n = len(a) print(countTriplets(a, n)) # This code is contributed by# Surendra_Gangwar",
"e": 30299,
"s": 29370,
"text": null
},
{
"code": "// C# program to count// the number of unique// triplets whose XOR is 0using System;using System.Collections.Generic; class GFG{ // function to count the // number of unique triplets // whose xor is 0 static int countTriplets(int []a, int n) { // To store values // that are present List<int> s = new List<int>(); for (int i = 0; i < n; i++) s.Add(a[i]); // stores the count // of unique triplets int count = 0; // traverse for all i, // j pairs such that j>i for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { // xor of a[i] and a[j] int xr = a[i] ^ a[j]; // if xr of two numbers // is present, then // increase the count if (s.Exists(item => item == xr) && xr != a[i] && xr != a[j]) count++; } } // returns answer return count / 3; } // Driver code static void Main() { int []a = new int[]{1, 3, 5, 10, 14, 15}; int n = a.Length; Console.Write(countTriplets(a, n)); }} // This code is contributed by// Manish Shaw(manishshaw1)",
"e": 31654,
"s": 30299,
"text": null
},
{
"code": "<script> // javascript program to count // the number of unique // triplets whose XOR is 0 // function to count the // number of unique triplets // whose xor is 0 function countTriplets(a , n) { // To store values // that are present var s = []; for (i = 0; i < n; i++) s.push(a[i]); // stores the count // of unique triplets var count = 0; // traverse for all i, // j pairs such that j>i for (i = 0; i < n; i++) { for (j = i + 1; j < n; j++) { // xor of a[i] and a[j] var xr = a[i] ^ a[j]; // if xr of two numbers // is present, then // increase the count if (s.includes(xr) && xr != a[i] && xr != a[j]) count++; } } // returns answer return count / 3; } // Driver code var a = [ 1, 3, 5, 10, 14, 15 ]; var n = a.length; document.write(countTriplets(a, n)); // This code contributed by Rajput-Ji</script>",
"e": 32736,
"s": 31654,
"text": null
},
{
"code": null,
"e": 32745,
"s": 32736,
"text": "Output: "
},
{
"code": null,
"e": 32747,
"s": 32745,
"text": "2"
},
{
"code": null,
"e": 32771,
"s": 32747,
"text": "Time Complexity: O(n2) "
},
{
"code": null,
"e": 32783,
"s": 32771,
"text": "manishshaw1"
},
{
"code": null,
"e": 32800,
"s": 32783,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 32809,
"s": 32800,
"text": "yepitsme"
},
{
"code": null,
"e": 32819,
"s": 32809,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 32831,
"s": 32819,
"text": "Bitwise-XOR"
},
{
"code": null,
"e": 32849,
"s": 32831,
"text": "cpp-unordered_set"
},
{
"code": null,
"e": 32856,
"s": 32849,
"text": "Arrays"
},
{
"code": null,
"e": 32866,
"s": 32856,
"text": "Bit Magic"
},
{
"code": null,
"e": 32876,
"s": 32866,
"text": "Searching"
},
{
"code": null,
"e": 32883,
"s": 32876,
"text": "Arrays"
},
{
"code": null,
"e": 32893,
"s": 32883,
"text": "Searching"
},
{
"code": null,
"e": 32903,
"s": 32893,
"text": "Bit Magic"
},
{
"code": null,
"e": 33001,
"s": 32903,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33010,
"s": 33001,
"text": "Comments"
},
{
"code": null,
"e": 33023,
"s": 33010,
"text": "Old Comments"
},
{
"code": null,
"e": 33071,
"s": 33023,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 33115,
"s": 33071,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 33138,
"s": 33115,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 33170,
"s": 33138,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 33184,
"s": 33170,
"text": "Linear Search"
},
{
"code": null,
"e": 33211,
"s": 33184,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 33257,
"s": 33211,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 33325,
"s": 33257,
"text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)"
},
{
"code": null,
"e": 33354,
"s": 33325,
"text": "Count set bits in an integer"
}
] |
Efficiency Of Token Ring - GeeksforGeeks | 11 Aug, 2021
Token Ring protocol is a communication protocol used in Local Area Network (LAN). In a token ring protocol, the topology of the network is used to define the order in which stations send. The stations are connected to one another in a single ring. It uses a special three-byte frame called a “token” that travels around a ring. It makes use of Token Passing controlled access mechanism. Frames are also transmitted in the direction of the token. This way they will circulate around the ring and reach the station which is the destination.
Ring Latency – The time taken by a single bit to travel around the ring is known as ring latency.
Where, d = length of the ring v = velocity of data in ring N = no. of stations in ring b = time taken by each station to hold the bit before transmitting it (bit delay)
Converting N*b into sec –
RL = d/v + (N*b)/B (B – bandwidth)
Converting d/v into bits –
RL = (d/v)*B + N*b (B – bandwidth)
Cycle Time – The time taken by the token to complete one revolution of the ring is known as cycle time.
Cycle time = Tp + (THT*N)
Where, THT - Token Holding Time
Tp - Propagation delay(d/v)
Token Holding Time (THT) – The maximum time a token frame can be held by a station is known as THT, by default it is set to 10msec. No station can hold the token beyond THT.
Calculating THT:
1. Delayed token reinsertion (DTR) –
In this, the sender transmit the data packet and waits till the time the whole packet takes the round trip of the ring and return to it. When the whole packet is received by the sender, then it releases the token
There is only one packet in the ring at an instance
More reliable than ETR
In this case,
THT = Tt + RL
= Tt + Tp + N*b (In most cases, bit delay is 0)
So, THT = Tt + Tp
where Tt = transmission delay
Tp = propagation delay
2. Early token reinsertion (ETR) –
Sender does not wait for the data packet to complete revolution before releasing the token. Token is released as soon as the data is transmitted
Multiple packets present in the ring
Less reliable than DTR
Station 1: Receives the token and transmits data D1 and then, releases the token. Station 2: Receives D1 (puts it onto the other end) and the token and then, transmits data D2 and releases the token. Station 3: Receives D1 –> transmits D1 Receives D2 –> transmits D2 Receives token –> transmits D3 Releases token. Station 4: Receives D1 –> transmits D1 Receives D2 –> transmits D2 Receives D3 –> transmits D3 Receives token –> transmits D4 Releases token.
Station 1: Receives D1 –> discards D1 as D1 has completed its journey Receives D2 –> transmits D2 Receives D3 –> transmits D3 Receives D4 –> transmits D4 Receives token –> transmits D1(new) Releases token. (and the cycle continues so on.....)
In this case,
THT = Tt
where Tt = transmission delay
Tp = propagation delay
Efficiency – Efficiency, e = useful time/ total time
useful time = N*Tt total time = cycle time = Tp + (THT*N)
So, e = (N*Tt)/(Tp + (THT*N))
1. Delayed token reinsertion – In this case, THT = Tt + Tp So, cycle time = Tp + N*(Tt + Tp)
Efficiency, e = (N*Tt)/(Tp + N*(Tt + Tp))
= 1/(1 + a*((N+1)/N))
where a = Tp/Tt
2. Early token reinsertion – In this case, THT = Tt So, cycle time = Tp + N*(Tt)
Efficiency, e = (N*Tt)/(Tp + N*(Tt))
= 1/(1 + a*(1/N))
where a = Tp/Tt
GATE Practice Questions –
GATE-CS-2014-(Set-1) | Question 65GATE-CS-2014-(Set-2) | Question 35GATE IT 2007 | Question 72GATE IT 2007 | Question 73GATE-IT-2004 | Question 82
GATE-CS-2014-(Set-1) | Question 65
GATE-CS-2014-(Set-2) | Question 35
GATE IT 2007 | Question 72
GATE IT 2007 | Question 73
GATE-IT-2004 | Question 82
kk773572498
Computer Networks
Technical Scripter
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Caesar Cipher in Cryptography
Socket Programming in Python
UDP Server-Client implementation in C
Differences between IPv4 and IPv6
Socket Programming in Java
Advanced Encryption Standard (AES)
GSM in Wireless Communication
Intrusion Detection System (IDS)
Secure Socket Layer (SSL)
Simple Chat Room using Python | [
{
"code": null,
"e": 36594,
"s": 36566,
"text": "\n11 Aug, 2021"
},
{
"code": null,
"e": 37134,
"s": 36594,
"text": "Token Ring protocol is a communication protocol used in Local Area Network (LAN). In a token ring protocol, the topology of the network is used to define the order in which stations send. The stations are connected to one another in a single ring. It uses a special three-byte frame called a “token” that travels around a ring. It makes use of Token Passing controlled access mechanism. Frames are also transmitted in the direction of the token. This way they will circulate around the ring and reach the station which is the destination. "
},
{
"code": null,
"e": 37235,
"s": 37136,
"text": "Ring Latency – The time taken by a single bit to travel around the ring is known as ring latency. "
},
{
"code": null,
"e": 37407,
"s": 37237,
"text": "Where, d = length of the ring v = velocity of data in ring N = no. of stations in ring b = time taken by each station to hold the bit before transmitting it (bit delay) "
},
{
"code": null,
"e": 37435,
"s": 37407,
"text": "Converting N*b into sec – "
},
{
"code": null,
"e": 37471,
"s": 37435,
"text": "RL = d/v + (N*b)/B (B – bandwidth)"
},
{
"code": null,
"e": 37500,
"s": 37471,
"text": "Converting d/v into bits – "
},
{
"code": null,
"e": 37536,
"s": 37500,
"text": "RL = (d/v)*B + N*b (B – bandwidth)"
},
{
"code": null,
"e": 37642,
"s": 37536,
"text": "Cycle Time – The time taken by the token to complete one revolution of the ring is known as cycle time. "
},
{
"code": null,
"e": 37729,
"s": 37642,
"text": "Cycle time = Tp + (THT*N)\nWhere, THT - Token Holding Time\nTp - Propagation delay(d/v) "
},
{
"code": null,
"e": 37904,
"s": 37729,
"text": "Token Holding Time (THT) – The maximum time a token frame can be held by a station is known as THT, by default it is set to 10msec. No station can hold the token beyond THT. "
},
{
"code": null,
"e": 37922,
"s": 37904,
"text": "Calculating THT: "
},
{
"code": null,
"e": 37963,
"s": 37924,
"text": "1. Delayed token reinsertion (DTR) – "
},
{
"code": null,
"e": 38176,
"s": 37963,
"text": "In this, the sender transmit the data packet and waits till the time the whole packet takes the round trip of the ring and return to it. When the whole packet is received by the sender, then it releases the token"
},
{
"code": null,
"e": 38228,
"s": 38176,
"text": "There is only one packet in the ring at an instance"
},
{
"code": null,
"e": 38251,
"s": 38228,
"text": "More reliable than ETR"
},
{
"code": null,
"e": 38269,
"s": 38253,
"text": "In this case, "
},
{
"code": null,
"e": 38417,
"s": 38269,
"text": "THT = Tt + RL\n = Tt + Tp + N*b (In most cases, bit delay is 0) \nSo, THT = Tt + Tp\n where Tt = transmission delay\n Tp = propagation delay"
},
{
"code": null,
"e": 38454,
"s": 38417,
"text": "2. Early token reinsertion (ETR) – "
},
{
"code": null,
"e": 38599,
"s": 38454,
"text": "Sender does not wait for the data packet to complete revolution before releasing the token. Token is released as soon as the data is transmitted"
},
{
"code": null,
"e": 38636,
"s": 38599,
"text": "Multiple packets present in the ring"
},
{
"code": null,
"e": 38659,
"s": 38636,
"text": "Less reliable than DTR"
},
{
"code": null,
"e": 39118,
"s": 38661,
"text": "Station 1: Receives the token and transmits data D1 and then, releases the token. Station 2: Receives D1 (puts it onto the other end) and the token and then, transmits data D2 and releases the token. Station 3: Receives D1 –> transmits D1 Receives D2 –> transmits D2 Receives token –> transmits D3 Releases token. Station 4: Receives D1 –> transmits D1 Receives D2 –> transmits D2 Receives D3 –> transmits D3 Receives token –> transmits D4 Releases token. "
},
{
"code": null,
"e": 39362,
"s": 39118,
"text": "Station 1: Receives D1 –> discards D1 as D1 has completed its journey Receives D2 –> transmits D2 Receives D3 –> transmits D3 Receives D4 –> transmits D4 Receives token –> transmits D1(new) Releases token. (and the cycle continues so on.....) "
},
{
"code": null,
"e": 39378,
"s": 39362,
"text": "In this case, "
},
{
"code": null,
"e": 39449,
"s": 39378,
"text": " THT = Tt\n where Tt = transmission delay\n Tp = propagation delay"
},
{
"code": null,
"e": 39503,
"s": 39449,
"text": "Efficiency – Efficiency, e = useful time/ total time "
},
{
"code": null,
"e": 39562,
"s": 39503,
"text": "useful time = N*Tt total time = cycle time = Tp + (THT*N) "
},
{
"code": null,
"e": 39593,
"s": 39562,
"text": "So, e = (N*Tt)/(Tp + (THT*N)) "
},
{
"code": null,
"e": 39688,
"s": 39593,
"text": "1. Delayed token reinsertion – In this case, THT = Tt + Tp So, cycle time = Tp + N*(Tt + Tp) "
},
{
"code": null,
"e": 39783,
"s": 39688,
"text": "Efficiency, e = (N*Tt)/(Tp + N*(Tt + Tp))\n = 1/(1 + a*((N+1)/N))\nwhere a = Tp/Tt"
},
{
"code": null,
"e": 39866,
"s": 39783,
"text": "2. Early token reinsertion – In this case, THT = Tt So, cycle time = Tp + N*(Tt) "
},
{
"code": null,
"e": 39952,
"s": 39866,
"text": "Efficiency, e = (N*Tt)/(Tp + N*(Tt))\n = 1/(1 + a*(1/N))\nwhere a = Tp/Tt"
},
{
"code": null,
"e": 39980,
"s": 39952,
"text": "GATE Practice Questions – "
},
{
"code": null,
"e": 40127,
"s": 39980,
"text": "GATE-CS-2014-(Set-1) | Question 65GATE-CS-2014-(Set-2) | Question 35GATE IT 2007 | Question 72GATE IT 2007 | Question 73GATE-IT-2004 | Question 82"
},
{
"code": null,
"e": 40162,
"s": 40127,
"text": "GATE-CS-2014-(Set-1) | Question 65"
},
{
"code": null,
"e": 40197,
"s": 40162,
"text": "GATE-CS-2014-(Set-2) | Question 35"
},
{
"code": null,
"e": 40224,
"s": 40197,
"text": "GATE IT 2007 | Question 72"
},
{
"code": null,
"e": 40251,
"s": 40224,
"text": "GATE IT 2007 | Question 73"
},
{
"code": null,
"e": 40278,
"s": 40251,
"text": "GATE-IT-2004 | Question 82"
},
{
"code": null,
"e": 40292,
"s": 40280,
"text": "kk773572498"
},
{
"code": null,
"e": 40310,
"s": 40292,
"text": "Computer Networks"
},
{
"code": null,
"e": 40329,
"s": 40310,
"text": "Technical Scripter"
},
{
"code": null,
"e": 40347,
"s": 40329,
"text": "Computer Networks"
},
{
"code": null,
"e": 40445,
"s": 40347,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 40475,
"s": 40445,
"text": "Caesar Cipher in Cryptography"
},
{
"code": null,
"e": 40504,
"s": 40475,
"text": "Socket Programming in Python"
},
{
"code": null,
"e": 40542,
"s": 40504,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 40576,
"s": 40542,
"text": "Differences between IPv4 and IPv6"
},
{
"code": null,
"e": 40603,
"s": 40576,
"text": "Socket Programming in Java"
},
{
"code": null,
"e": 40638,
"s": 40603,
"text": "Advanced Encryption Standard (AES)"
},
{
"code": null,
"e": 40668,
"s": 40638,
"text": "GSM in Wireless Communication"
},
{
"code": null,
"e": 40701,
"s": 40668,
"text": "Intrusion Detection System (IDS)"
},
{
"code": null,
"e": 40727,
"s": 40701,
"text": "Secure Socket Layer (SSL)"
}
] |
Next.js - Routing | Next.js uses file system based router. Whenever we add any page to pages directory, it is automatically available via url. Following are the rules of this router.
Index Routes − An index.js file present in a folder maps to root of directory. For example −
pages/index.js maps to '/'.
pages/posts/index.js maps to '/posts'.
Index Routes − An index.js file present in a folder maps to root of directory. For example −
pages/index.js maps to '/'.
pages/index.js maps to '/'.
pages/posts/index.js maps to '/posts'.
pages/posts/index.js maps to '/posts'.
Nested Routes − Any nested folder structure in pages directory because router url automatically. For example −
pages/settings/dashboard/about.js maps to '/settings/dashboard/about'.
pages/posts/first.js maps to '/posts/first'.
Nested Routes − Any nested folder structure in pages directory because router url automatically. For example −
pages/settings/dashboard/about.js maps to '/settings/dashboard/about'.
pages/settings/dashboard/about.js maps to '/settings/dashboard/about'.
pages/posts/first.js maps to '/posts/first'.
pages/posts/first.js maps to '/posts/first'.
Dynamic Routes − We can use named parameter as well to match url. Use brackets for the same. For example −
pages/posts/[id].js maps to '/posts/:id' where we can use URL like '/posts/1'.
pages/[user]/settings.js maps to '/posts/:user/settings' where we can use URL like '/abc/settings'.
pages/posts/[...all].js maps to '/posts/*' where we can use any URL like '/posts/2020/jun/'.
Dynamic Routes − We can use named parameter as well to match url. Use brackets for the same. For example −
pages/posts/[id].js maps to '/posts/:id' where we can use URL like '/posts/1'.
pages/posts/[id].js maps to '/posts/:id' where we can use URL like '/posts/1'.
pages/[user]/settings.js maps to '/posts/:user/settings' where we can use URL like '/abc/settings'.
pages/[user]/settings.js maps to '/posts/:user/settings' where we can use URL like '/abc/settings'.
pages/posts/[...all].js maps to '/posts/*' where we can use any URL like '/posts/2020/jun/'.
pages/posts/[...all].js maps to '/posts/*' where we can use any URL like '/posts/2020/jun/'.
Next.JS allows to link pages on client side using Link react component. It has following properties −
href − name of the page in pages directory. For example /posts/first which refers to first.js present in pages/posts directory.
href − name of the page in pages directory. For example /posts/first which refers to first.js present in pages/posts directory.
Let's create an example to demonstrate the same.
In this example, we'll update index.js and first.js page to make a server hit to get data.
Let's update the nextjs project used in Global CSS Support chapter.
Update index.js file in pages directory as following.
import Link from 'next/link'
import Head from 'next/head'
function HomePage(props) {
return (
<>
<Head>
<title>Welcome to Next.js!</title>
</Head>
<div>Welcome to Next.js!</div>
<Link href="/posts/first">> <a>First Post</a></Link>
<br/>
<div>Next stars: {props.stars}</div>
<img src="/logo.png" alt="TutorialsPoint Logo" />
</>
)
}
export async function getServerSideProps(context) {
const res = await fetch('https://api.github.com/repos/vercel/next.js')
const json = await res.json()
return {
props: { stars: json.stargazers_count }
}
}
export default HomePage
Run the following command to start the server −.
npm run dev
> [email protected] dev \Node\nextjs
> next
ready - started server on http://localhost:3000
event - compiled successfully
event - build page: /
wait - compiling...
event - compiled successfully
event - build page: /next/dist/pages/_error
wait - compiling...
event - compiled successfully
Open localhost:3000 in a browser and you will see the following output.
Click on First post link.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2270,
"s": 2107,
"text": "Next.js uses file system based router. Whenever we add any page to pages directory, it is automatically available via url. Following are the rules of this router."
},
{
"code": null,
"e": 2433,
"s": 2270,
"text": "Index Routes − An index.js file present in a folder maps to root of directory. For example −\n\npages/index.js maps to '/'.\npages/posts/index.js maps to '/posts'.\n\n"
},
{
"code": null,
"e": 2526,
"s": 2433,
"text": "Index Routes − An index.js file present in a folder maps to root of directory. For example −"
},
{
"code": null,
"e": 2554,
"s": 2526,
"text": "pages/index.js maps to '/'."
},
{
"code": null,
"e": 2582,
"s": 2554,
"text": "pages/index.js maps to '/'."
},
{
"code": null,
"e": 2621,
"s": 2582,
"text": "pages/posts/index.js maps to '/posts'."
},
{
"code": null,
"e": 2660,
"s": 2621,
"text": "pages/posts/index.js maps to '/posts'."
},
{
"code": null,
"e": 2890,
"s": 2660,
"text": "Nested Routes − Any nested folder structure in pages directory because router url automatically. For example −\n\npages/settings/dashboard/about.js maps to '/settings/dashboard/about'.\npages/posts/first.js maps to '/posts/first'.\n\n"
},
{
"code": null,
"e": 3001,
"s": 2890,
"text": "Nested Routes − Any nested folder structure in pages directory because router url automatically. For example −"
},
{
"code": null,
"e": 3072,
"s": 3001,
"text": "pages/settings/dashboard/about.js maps to '/settings/dashboard/about'."
},
{
"code": null,
"e": 3143,
"s": 3072,
"text": "pages/settings/dashboard/about.js maps to '/settings/dashboard/about'."
},
{
"code": null,
"e": 3188,
"s": 3143,
"text": "pages/posts/first.js maps to '/posts/first'."
},
{
"code": null,
"e": 3233,
"s": 3188,
"text": "pages/posts/first.js maps to '/posts/first'."
},
{
"code": null,
"e": 3615,
"s": 3233,
"text": "Dynamic Routes − We can use named parameter as well to match url. Use brackets for the same. For example −\n\npages/posts/[id].js maps to '/posts/:id' where we can use URL like '/posts/1'.\npages/[user]/settings.js maps to '/posts/:user/settings' where we can use URL like '/abc/settings'.\npages/posts/[...all].js maps to '/posts/*' where we can use any URL like '/posts/2020/jun/'.\n\n"
},
{
"code": null,
"e": 3722,
"s": 3615,
"text": "Dynamic Routes − We can use named parameter as well to match url. Use brackets for the same. For example −"
},
{
"code": null,
"e": 3801,
"s": 3722,
"text": "pages/posts/[id].js maps to '/posts/:id' where we can use URL like '/posts/1'."
},
{
"code": null,
"e": 3880,
"s": 3801,
"text": "pages/posts/[id].js maps to '/posts/:id' where we can use URL like '/posts/1'."
},
{
"code": null,
"e": 3980,
"s": 3880,
"text": "pages/[user]/settings.js maps to '/posts/:user/settings' where we can use URL like '/abc/settings'."
},
{
"code": null,
"e": 4080,
"s": 3980,
"text": "pages/[user]/settings.js maps to '/posts/:user/settings' where we can use URL like '/abc/settings'."
},
{
"code": null,
"e": 4173,
"s": 4080,
"text": "pages/posts/[...all].js maps to '/posts/*' where we can use any URL like '/posts/2020/jun/'."
},
{
"code": null,
"e": 4266,
"s": 4173,
"text": "pages/posts/[...all].js maps to '/posts/*' where we can use any URL like '/posts/2020/jun/'."
},
{
"code": null,
"e": 4368,
"s": 4266,
"text": "Next.JS allows to link pages on client side using Link react component. It has following properties −"
},
{
"code": null,
"e": 4496,
"s": 4368,
"text": "href − name of the page in pages directory. For example /posts/first which refers to first.js present in pages/posts directory."
},
{
"code": null,
"e": 4624,
"s": 4496,
"text": "href − name of the page in pages directory. For example /posts/first which refers to first.js present in pages/posts directory."
},
{
"code": null,
"e": 4673,
"s": 4624,
"text": "Let's create an example to demonstrate the same."
},
{
"code": null,
"e": 4764,
"s": 4673,
"text": "In this example, we'll update index.js and first.js page to make a server hit to get data."
},
{
"code": null,
"e": 4832,
"s": 4764,
"text": "Let's update the nextjs project used in Global CSS Support chapter."
},
{
"code": null,
"e": 4886,
"s": 4832,
"text": "Update index.js file in pages directory as following."
},
{
"code": null,
"e": 5567,
"s": 4886,
"text": "import Link from 'next/link'\nimport Head from 'next/head'\n\nfunction HomePage(props) {\n return (\n <>\n <Head>\n <title>Welcome to Next.js!</title>\n </Head>\n <div>Welcome to Next.js!</div>\n <Link href=\"/posts/first\">> <a>First Post</a></Link>\n <br/>\n <div>Next stars: {props.stars}</div>\n <img src=\"/logo.png\" alt=\"TutorialsPoint Logo\" />\n </>\t \n )\n}\n\nexport async function getServerSideProps(context) {\n const res = await fetch('https://api.github.com/repos/vercel/next.js')\n const json = await res.json()\n return {\n props: { stars: json.stargazers_count }\n }\n}\n\nexport default HomePage"
},
{
"code": null,
"e": 5616,
"s": 5567,
"text": "Run the following command to start the server −."
},
{
"code": null,
"e": 5915,
"s": 5616,
"text": "npm run dev\n> [email protected] dev \\Node\\nextjs\n> next\n\nready - started server on http://localhost:3000\nevent - compiled successfully\nevent - build page: /\nwait - compiling...\nevent - compiled successfully\nevent - build page: /next/dist/pages/_error\nwait - compiling...\nevent - compiled successfully\n"
},
{
"code": null,
"e": 5987,
"s": 5915,
"text": "Open localhost:3000 in a browser and you will see the following output."
},
{
"code": null,
"e": 6013,
"s": 5987,
"text": "Click on First post link."
},
{
"code": null,
"e": 6020,
"s": 6013,
"text": " Print"
},
{
"code": null,
"e": 6031,
"s": 6020,
"text": " Add Notes"
}
] |
Check if a circle lies inside another circle or not in C++ | Suppose we have two circles (center points, and the radius values), we have to check one circle is fit inside another circle or not. There are three possible causes.
The smaller circle lies completely inside the bigger one, without touching each other. In this case, the sum of the distance between the centers, and the smaller radius, is lesser than a bigger radius. So the smaller one will be inside the bigger one.
The smaller circle lies completely inside the bigger one, without touching each other. In this case, the sum of the distance between the centers, and the smaller radius, is lesser than a bigger radius. So the smaller one will be inside the bigger one.
The second case is the smaller circle is inside the bigger ones, but also touches the circumference of the bigger circle.
The second case is the smaller circle is inside the bigger ones, but also touches the circumference of the bigger circle.
The third case is, some part of the smaller circle is inside the bigger one.
The third case is, some part of the smaller circle is inside the bigger one.
To solve this, we have to find the distance between two centers, then using the distance and the radius values, we will determine those cases.
#include <iostream>
#include <cmath>
using namespace std;
void isCircleInside(int x_big, int y_big, int x_small, int y_small, int r_big, int r_small) {
int distSq = sqrt(((x_big - x_small) * (x_big - x_small)) + ((y_big - y_small) * (y_big - y_small)));
if (distSq + r_small == r_big)
cout << "Inside the bigger circle, touching circimferene" << endl;
else if (distSq + r_small < r_big)
cout << "Completely inside the bigger circle" << endl;
else
cout << "Not inside the bigger circle" << endl;
}
int main() {
int x1 = 10, y1 = 8;
int x2 = 1, y2 = 2;
int r1 = 30, r2 = 10;
isCircleInside(x1, y1, x2, y2, r1, r2);
}
Completely inside the bigger circle | [
{
"code": null,
"e": 1228,
"s": 1062,
"text": "Suppose we have two circles (center points, and the radius values), we have to check one circle is fit inside another circle or not. There are three possible causes."
},
{
"code": null,
"e": 1480,
"s": 1228,
"text": "The smaller circle lies completely inside the bigger one, without touching each other. In this case, the sum of the distance between the centers, and the smaller radius, is lesser than a bigger radius. So the smaller one will be inside the bigger one."
},
{
"code": null,
"e": 1732,
"s": 1480,
"text": "The smaller circle lies completely inside the bigger one, without touching each other. In this case, the sum of the distance between the centers, and the smaller radius, is lesser than a bigger radius. So the smaller one will be inside the bigger one."
},
{
"code": null,
"e": 1854,
"s": 1732,
"text": "The second case is the smaller circle is inside the bigger ones, but also touches the circumference of the bigger circle."
},
{
"code": null,
"e": 1976,
"s": 1854,
"text": "The second case is the smaller circle is inside the bigger ones, but also touches the circumference of the bigger circle."
},
{
"code": null,
"e": 2053,
"s": 1976,
"text": "The third case is, some part of the smaller circle is inside the bigger one."
},
{
"code": null,
"e": 2130,
"s": 2053,
"text": "The third case is, some part of the smaller circle is inside the bigger one."
},
{
"code": null,
"e": 2273,
"s": 2130,
"text": "To solve this, we have to find the distance between two centers, then using the distance and the radius values, we will determine those cases."
},
{
"code": null,
"e": 2936,
"s": 2273,
"text": "#include <iostream>\n#include <cmath>\nusing namespace std;\nvoid isCircleInside(int x_big, int y_big, int x_small, int y_small, int r_big, int r_small) {\n int distSq = sqrt(((x_big - x_small) * (x_big - x_small)) + ((y_big - y_small) * (y_big - y_small)));\n if (distSq + r_small == r_big)\n cout << \"Inside the bigger circle, touching circimferene\" << endl;\n else if (distSq + r_small < r_big)\n cout << \"Completely inside the bigger circle\" << endl;\n else\n cout << \"Not inside the bigger circle\" << endl;\n}\nint main() {\n int x1 = 10, y1 = 8;\n int x2 = 1, y2 = 2;\n int r1 = 30, r2 = 10;\n isCircleInside(x1, y1, x2, y2, r1, r2);\n}"
},
{
"code": null,
"e": 2972,
"s": 2936,
"text": "Completely inside the bigger circle"
}
] |
Using Cosine Similarity to Build a Movie Recommendation System | by Mahnoor Javed | Towards Data Science | Have you ever imagined that a simple formula that you have studied in high school would play a part in recommending you a movie on the basis of the one you already like?
Well, here we are, using the Cosine Similarity (the dot product for normalized vectors) to build a Movie Recommender System!
Recommender systems are an important class of machine learning algorithms that offer “relevant” suggestions to users. Youtube, Amazon, Netflix, all function on recommendation systems where the system recommends you the next video or product based on your past activity (Content-based Filtering) or based on activities and preferences of other users similar to you (Collaborative Filtering). Likewise, Facebook also uses a recommendation system to suggest Facebook users you may know offline.
Recommendation Systems work based on the similarity between either the content or the users who access the content.
There are several ways to measure the similarity between two items. The recommendation systems use this similarity matrix to recommend the next most similar product to the user.
In this article, we will build a machine learning algorithm that would recommend movies based on a movie the user likes. This Machine Learning model would be based on Cosine Similarity.
The first step to build a movie recommendation system is getting the appropriate data. You may download the movies dataset from the web, or from the link below which contains a 22MB CSV file titled “movie_dataset.csv”:
github.com
Let’s explore the dataset now!
Our CSV file contains a total of 4802 movies and 24 columns: index, budget, genres, homepage, id, keywords, original_language, original_title, overview, popularity, production_companies, production_countries, release_date, revenue, runtime, spoken_languages, status, tagline, title, vote_average, vote_count, cast, crew and director (sigh!).
Among all these different features, the ones we are interested in to find the similarity for making the next recommendation are the following:
keywords, cast, genres & director.
A user who likes a horror movie will most probably like another horror movie. Some users may like seeing their favorite actors in the cast of the movie. Others may love movies directed by a particular person. Combining all of these aspects, our shortlisted 4 features are sufficient to train our recommendation algorithm.
Now, let us start with the coding. First things first, let’s import the libraries we need, as well as the CSV file of the movies’ dataset.
import pandas as pdimport numpy as npfrom sklearn.feature_extraction.text import CountVectorizerfrom sklearn.metrics.pairwise import cosine_similaritydf = pd.read_csv(r"...\movie_dataset.csv")
We will import the two important libraries for data analysis and manipulation; pandas and numpy. We will also import Scikit-learn’s CountVectorizer, used to convert a collection of text documents to a vector of term/token counts.
Lastly, we will import the cosine_similarity from sklearn, as the metric of our similarity matrix (which will be discussed in details later).
We will read our CSV file into a dataframe df, which can then be accessed in the variable explorer of our Python IDE.
We will make a list of the features that we will be using. As discussed above, we will only use the features most relevant to us, considering our problem at hand. Hence, our chosen features will be keywords, cast, genres & director.
Moreover, we will do a little bit of data preprocessing and replace any rows having NaN values with a space/empty string, so it does not generate an error while running the code. This pre-processing has been done in the for loop.
features = ['keywords', 'cast', 'genres', 'director']for feature in features: df[feature] = df[feature].fillna('')
Next, we will define a function called combined_features. The function will combine all our useful features (keywords, cast, genres & director) from their respective rows, and return a row with all the combined features in a single string.
def combined_features(row): return row['keywords']+" "+row['cast']+" "+row['genres']+" "+row['director']df["combined_features"] = df.apply(combined_features, axis =1)
We will add a new column, combined_features to our existing dataframe (df) and apply the above function to each row (axis = 1). The dataframe will now have an extra column at the end, which will comprise of rows of the combined features.
Next, we will extract features from our data.
The sklearn.feature_extraction module can be used to extract features in a format supported by machine learning algorithms from datasets consisting of formats such as text and image. We will use CountVectorizer’s fit.tranform to count the number of texts and we will print the transformed matrix count_matrix into an array for better understanding.
cv = CountVectorizer()count_matrix = cv.fit_transform(df["combined_features"])print("Count Matrix:", count_matrix.toarray())
We will use the Cosine Similarity from Sklearn, as the metric to compute the similarity between two movies.
Cosine similarity is a metric used to measure how similar two items are. Mathematically, it measures the cosine of the angle between two vectors projected in a multi-dimensional space. The output value ranges from 0–1.
0 means no similarity, where as 1 means that both the items are 100% similar.
The python Cosine Similarity or cosine kernel, computes similarity as the normalized dot product of input samples X and Y. We will use the sklearn cosine_similarity to find the cos θ for the two vectors in the count matrix.
cosine_sim = cosine_similarity(count_matrix)
The cosine_sim matrix is a numpy array with calculated cosine similarity between each movies. As you can see in the image below, the cosine similarity of movie 0 with movie 0 is 1; they are 100% similar (as should be).
Similarly the cosine similarity between movie 0 and movie 1 is 0.105409 (the same score between movie 1 and movie 0 — order does not matter).
Movies 0 and 4 are more similar to each other (with a similarity score of 0.23094) than movies 0 and 3 (score = 0.0377426).
The diagonal with 1s suggests what the case is, each movie ‘x’ is 100% similar to itself!
The next step is to take as input a movie that the user likes in the movie_user_likes variable.
Since we are building a content based filtering system, we need to know the users’ likes in order to predict a similar item.
movie_user_likes = "Dead Poets Society"def get_index_from_title(title): return df[df.title == title]["index"].values[0]movie_index = get_index_from_title(movie_user_likes)
Suppose I like the movie “Dead Poets Society”. Next, I will build a function to get the index from the name of this movie. The index will be saved in the movie_index variable.
Next we will generate a list of similar movies. We will use the movie_index of the movie we have given as input movie_user_likes. The enumerate() method will add a counter to the iterable list cosine_sim and return it in a form of a list similar_movies with the similarity score of each index.
similar_movies = list(enumerate(cosine_sim[movie_index]))
Next step is to sort the movies in the list similar_movies. We have used the parameter reverse=True since we want the list in the descending order, with the most similar item at the top.
sorted_similar_movies = sorted(similar_movies, key=lambda x:x[1], reverse=True)
The sorted_similar_movies will be a list of all the movies sorted in descending order with respect to their similarity score with the input movie movie_user_likes.
As can be seen in the image below, the most similar one with a similarity score of 0.9999999999999993 is at the top most, with its index number 2453 (the movie is ‘Dead Poets Society’ which we gave as input, makes sense, right?).
Now, here comes the last part of the project, which is to print the names of the movies similar to the one we have given as input to the system through the movie_user_likes variable.
As seen in the sorted_similar_movies list, the movies are sorted by their index number. Printing the index number will be of no use to us, so we will define a simple function that takes the index number and covert it into the movie title as in the dataframe.
Index Number → Movie Title
Next we will call this function inside the for loop to print the first ‘x’ number of movies from the sorted_similar_movies.
In our case, we will print the 15 most similar movies from a pool of 4802 movies.
def get_title_from_index(index): return df[df.index == index]["title"].values[0]i=0for movie in sorted_similar_movies: print(get_title_from_index(movie[0])) i=i+1 if i>15: break
Now comes the application. Use the steps above to code your own recommender systems and run the code by giving a movie you like to the movie_user_likes.
I have given “Dead Poets Society”, and it prints me the following similar movies:
As can be seen, the most similar one is obviously the movie itself. The algorithm defines “Much Ado About Nothing” as the next most similar movie! (will add it to my “To-watch list” 😄 )
That’s it for this article! The article provided a hands-on approach to build a recommendation system, from scratch, by coding it on any python IDE.
Now, once the algorithm is built, its time to grab some popcorn, and watch the movie your system recommends!! 😁 | [
{
"code": null,
"e": 216,
"s": 46,
"text": "Have you ever imagined that a simple formula that you have studied in high school would play a part in recommending you a movie on the basis of the one you already like?"
},
{
"code": null,
"e": 341,
"s": 216,
"text": "Well, here we are, using the Cosine Similarity (the dot product for normalized vectors) to build a Movie Recommender System!"
},
{
"code": null,
"e": 833,
"s": 341,
"text": "Recommender systems are an important class of machine learning algorithms that offer “relevant” suggestions to users. Youtube, Amazon, Netflix, all function on recommendation systems where the system recommends you the next video or product based on your past activity (Content-based Filtering) or based on activities and preferences of other users similar to you (Collaborative Filtering). Likewise, Facebook also uses a recommendation system to suggest Facebook users you may know offline."
},
{
"code": null,
"e": 949,
"s": 833,
"text": "Recommendation Systems work based on the similarity between either the content or the users who access the content."
},
{
"code": null,
"e": 1127,
"s": 949,
"text": "There are several ways to measure the similarity between two items. The recommendation systems use this similarity matrix to recommend the next most similar product to the user."
},
{
"code": null,
"e": 1313,
"s": 1127,
"text": "In this article, we will build a machine learning algorithm that would recommend movies based on a movie the user likes. This Machine Learning model would be based on Cosine Similarity."
},
{
"code": null,
"e": 1532,
"s": 1313,
"text": "The first step to build a movie recommendation system is getting the appropriate data. You may download the movies dataset from the web, or from the link below which contains a 22MB CSV file titled “movie_dataset.csv”:"
},
{
"code": null,
"e": 1543,
"s": 1532,
"text": "github.com"
},
{
"code": null,
"e": 1574,
"s": 1543,
"text": "Let’s explore the dataset now!"
},
{
"code": null,
"e": 1916,
"s": 1574,
"text": "Our CSV file contains a total of 4802 movies and 24 columns: index, budget, genres, homepage, id, keywords, original_language, original_title, overview, popularity, production_companies, production_countries, release_date, revenue, runtime, spoken_languages, status, tagline, title, vote_average, vote_count, cast, crew and director (sigh!)."
},
{
"code": null,
"e": 2059,
"s": 1916,
"text": "Among all these different features, the ones we are interested in to find the similarity for making the next recommendation are the following:"
},
{
"code": null,
"e": 2094,
"s": 2059,
"text": "keywords, cast, genres & director."
},
{
"code": null,
"e": 2416,
"s": 2094,
"text": "A user who likes a horror movie will most probably like another horror movie. Some users may like seeing their favorite actors in the cast of the movie. Others may love movies directed by a particular person. Combining all of these aspects, our shortlisted 4 features are sufficient to train our recommendation algorithm."
},
{
"code": null,
"e": 2555,
"s": 2416,
"text": "Now, let us start with the coding. First things first, let’s import the libraries we need, as well as the CSV file of the movies’ dataset."
},
{
"code": null,
"e": 2748,
"s": 2555,
"text": "import pandas as pdimport numpy as npfrom sklearn.feature_extraction.text import CountVectorizerfrom sklearn.metrics.pairwise import cosine_similaritydf = pd.read_csv(r\"...\\movie_dataset.csv\")"
},
{
"code": null,
"e": 2978,
"s": 2748,
"text": "We will import the two important libraries for data analysis and manipulation; pandas and numpy. We will also import Scikit-learn’s CountVectorizer, used to convert a collection of text documents to a vector of term/token counts."
},
{
"code": null,
"e": 3120,
"s": 2978,
"text": "Lastly, we will import the cosine_similarity from sklearn, as the metric of our similarity matrix (which will be discussed in details later)."
},
{
"code": null,
"e": 3238,
"s": 3120,
"text": "We will read our CSV file into a dataframe df, which can then be accessed in the variable explorer of our Python IDE."
},
{
"code": null,
"e": 3471,
"s": 3238,
"text": "We will make a list of the features that we will be using. As discussed above, we will only use the features most relevant to us, considering our problem at hand. Hence, our chosen features will be keywords, cast, genres & director."
},
{
"code": null,
"e": 3701,
"s": 3471,
"text": "Moreover, we will do a little bit of data preprocessing and replace any rows having NaN values with a space/empty string, so it does not generate an error while running the code. This pre-processing has been done in the for loop."
},
{
"code": null,
"e": 3819,
"s": 3701,
"text": "features = ['keywords', 'cast', 'genres', 'director']for feature in features: df[feature] = df[feature].fillna('')"
},
{
"code": null,
"e": 4059,
"s": 3819,
"text": "Next, we will define a function called combined_features. The function will combine all our useful features (keywords, cast, genres & director) from their respective rows, and return a row with all the combined features in a single string."
},
{
"code": null,
"e": 4229,
"s": 4059,
"text": "def combined_features(row): return row['keywords']+\" \"+row['cast']+\" \"+row['genres']+\" \"+row['director']df[\"combined_features\"] = df.apply(combined_features, axis =1)"
},
{
"code": null,
"e": 4467,
"s": 4229,
"text": "We will add a new column, combined_features to our existing dataframe (df) and apply the above function to each row (axis = 1). The dataframe will now have an extra column at the end, which will comprise of rows of the combined features."
},
{
"code": null,
"e": 4513,
"s": 4467,
"text": "Next, we will extract features from our data."
},
{
"code": null,
"e": 4862,
"s": 4513,
"text": "The sklearn.feature_extraction module can be used to extract features in a format supported by machine learning algorithms from datasets consisting of formats such as text and image. We will use CountVectorizer’s fit.tranform to count the number of texts and we will print the transformed matrix count_matrix into an array for better understanding."
},
{
"code": null,
"e": 4987,
"s": 4862,
"text": "cv = CountVectorizer()count_matrix = cv.fit_transform(df[\"combined_features\"])print(\"Count Matrix:\", count_matrix.toarray())"
},
{
"code": null,
"e": 5095,
"s": 4987,
"text": "We will use the Cosine Similarity from Sklearn, as the metric to compute the similarity between two movies."
},
{
"code": null,
"e": 5314,
"s": 5095,
"text": "Cosine similarity is a metric used to measure how similar two items are. Mathematically, it measures the cosine of the angle between two vectors projected in a multi-dimensional space. The output value ranges from 0–1."
},
{
"code": null,
"e": 5392,
"s": 5314,
"text": "0 means no similarity, where as 1 means that both the items are 100% similar."
},
{
"code": null,
"e": 5616,
"s": 5392,
"text": "The python Cosine Similarity or cosine kernel, computes similarity as the normalized dot product of input samples X and Y. We will use the sklearn cosine_similarity to find the cos θ for the two vectors in the count matrix."
},
{
"code": null,
"e": 5661,
"s": 5616,
"text": "cosine_sim = cosine_similarity(count_matrix)"
},
{
"code": null,
"e": 5880,
"s": 5661,
"text": "The cosine_sim matrix is a numpy array with calculated cosine similarity between each movies. As you can see in the image below, the cosine similarity of movie 0 with movie 0 is 1; they are 100% similar (as should be)."
},
{
"code": null,
"e": 6022,
"s": 5880,
"text": "Similarly the cosine similarity between movie 0 and movie 1 is 0.105409 (the same score between movie 1 and movie 0 — order does not matter)."
},
{
"code": null,
"e": 6146,
"s": 6022,
"text": "Movies 0 and 4 are more similar to each other (with a similarity score of 0.23094) than movies 0 and 3 (score = 0.0377426)."
},
{
"code": null,
"e": 6236,
"s": 6146,
"text": "The diagonal with 1s suggests what the case is, each movie ‘x’ is 100% similar to itself!"
},
{
"code": null,
"e": 6332,
"s": 6236,
"text": "The next step is to take as input a movie that the user likes in the movie_user_likes variable."
},
{
"code": null,
"e": 6457,
"s": 6332,
"text": "Since we are building a content based filtering system, we need to know the users’ likes in order to predict a similar item."
},
{
"code": null,
"e": 6632,
"s": 6457,
"text": "movie_user_likes = \"Dead Poets Society\"def get_index_from_title(title): return df[df.title == title][\"index\"].values[0]movie_index = get_index_from_title(movie_user_likes)"
},
{
"code": null,
"e": 6808,
"s": 6632,
"text": "Suppose I like the movie “Dead Poets Society”. Next, I will build a function to get the index from the name of this movie. The index will be saved in the movie_index variable."
},
{
"code": null,
"e": 7102,
"s": 6808,
"text": "Next we will generate a list of similar movies. We will use the movie_index of the movie we have given as input movie_user_likes. The enumerate() method will add a counter to the iterable list cosine_sim and return it in a form of a list similar_movies with the similarity score of each index."
},
{
"code": null,
"e": 7160,
"s": 7102,
"text": "similar_movies = list(enumerate(cosine_sim[movie_index]))"
},
{
"code": null,
"e": 7347,
"s": 7160,
"text": "Next step is to sort the movies in the list similar_movies. We have used the parameter reverse=True since we want the list in the descending order, with the most similar item at the top."
},
{
"code": null,
"e": 7427,
"s": 7347,
"text": "sorted_similar_movies = sorted(similar_movies, key=lambda x:x[1], reverse=True)"
},
{
"code": null,
"e": 7591,
"s": 7427,
"text": "The sorted_similar_movies will be a list of all the movies sorted in descending order with respect to their similarity score with the input movie movie_user_likes."
},
{
"code": null,
"e": 7821,
"s": 7591,
"text": "As can be seen in the image below, the most similar one with a similarity score of 0.9999999999999993 is at the top most, with its index number 2453 (the movie is ‘Dead Poets Society’ which we gave as input, makes sense, right?)."
},
{
"code": null,
"e": 8004,
"s": 7821,
"text": "Now, here comes the last part of the project, which is to print the names of the movies similar to the one we have given as input to the system through the movie_user_likes variable."
},
{
"code": null,
"e": 8263,
"s": 8004,
"text": "As seen in the sorted_similar_movies list, the movies are sorted by their index number. Printing the index number will be of no use to us, so we will define a simple function that takes the index number and covert it into the movie title as in the dataframe."
},
{
"code": null,
"e": 8290,
"s": 8263,
"text": "Index Number → Movie Title"
},
{
"code": null,
"e": 8414,
"s": 8290,
"text": "Next we will call this function inside the for loop to print the first ‘x’ number of movies from the sorted_similar_movies."
},
{
"code": null,
"e": 8496,
"s": 8414,
"text": "In our case, we will print the 15 most similar movies from a pool of 4802 movies."
},
{
"code": null,
"e": 8693,
"s": 8496,
"text": "def get_title_from_index(index): return df[df.index == index][\"title\"].values[0]i=0for movie in sorted_similar_movies: print(get_title_from_index(movie[0])) i=i+1 if i>15: break"
},
{
"code": null,
"e": 8846,
"s": 8693,
"text": "Now comes the application. Use the steps above to code your own recommender systems and run the code by giving a movie you like to the movie_user_likes."
},
{
"code": null,
"e": 8928,
"s": 8846,
"text": "I have given “Dead Poets Society”, and it prints me the following similar movies:"
},
{
"code": null,
"e": 9114,
"s": 8928,
"text": "As can be seen, the most similar one is obviously the movie itself. The algorithm defines “Much Ado About Nothing” as the next most similar movie! (will add it to my “To-watch list” 😄 )"
},
{
"code": null,
"e": 9263,
"s": 9114,
"text": "That’s it for this article! The article provided a hands-on approach to build a recommendation system, from scratch, by coding it on any python IDE."
}
] |
How to dynamically build MongoDB query? | To build query dynamically, you need to write some script. Let us first create a collection with documents −
> db.dynamicQueryDemo.insertOne({"Name":"John","Subject":["MongoDB","MySQL"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cef5c5def71edecf6a1f69a")
}
> db.dynamicQueryDemo.insertOne({"Name":"John","Subject":["C","C++"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cef5c73ef71edecf6a1f69b")
}
> db.dynamicQueryDemo.insertOne({"Name":"John","Subject":["MongoDB","Java"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cef5c8bef71edecf6a1f69c")
}
Display all documents from a collection with the help of find() method −
> db.dynamicQueryDemo.find().pretty();
This will produce the following output −
{
"_id" : ObjectId("5cef5c5def71edecf6a1f69a"),
"Name" : "John",
"Subject" : [
"MongoDB",
"MySQL"
]
}
{
"_id" : ObjectId("5cef5c73ef71edecf6a1f69b"),
"Name" : "John",
"Subject" : [
"C",
"C++"
]
}
{
"_id" : ObjectId("5cef5c8bef71edecf6a1f69c"),
"Name" : "John",
"Subject" : [
"MongoDB",
"Java"
]
}
Following is the query to dynamically build MongoDB query −
> function findDocument(subject) {
var find = {};
if (subject.length == 0)
find["$nin"] = subject;
else
find["$in"] = subject;
return find;
}
> var sub = ["MySQL","MongoDB"];
> var myDoc = findDocument(sub);
> db.dynamicQueryDemo.aggregate([{
$match: {
"Subject": myDoc,
}
}]);
This will produce the following output −
{ "_id" : ObjectId("5cef5c5def71edecf6a1f69a"), "Name" : "John", "Subject" : [ "MongoDB", "MySQL" ] }
{ "_id" : ObjectId("5cef5c8bef71edecf6a1f69c"), "Name" : "John", "Subject" : [ "MongoDB", "Java" ] } | [
{
"code": null,
"e": 1171,
"s": 1062,
"text": "To build query dynamically, you need to write some script. Let us first create a collection with documents −"
},
{
"code": null,
"e": 1663,
"s": 1171,
"text": "> db.dynamicQueryDemo.insertOne({\"Name\":\"John\",\"Subject\":[\"MongoDB\",\"MySQL\"]});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5cef5c5def71edecf6a1f69a\")\n}\n> db.dynamicQueryDemo.insertOne({\"Name\":\"John\",\"Subject\":[\"C\",\"C++\"]});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5cef5c73ef71edecf6a1f69b\")\n}\n> db.dynamicQueryDemo.insertOne({\"Name\":\"John\",\"Subject\":[\"MongoDB\",\"Java\"]});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5cef5c8bef71edecf6a1f69c\")\n}"
},
{
"code": null,
"e": 1736,
"s": 1663,
"text": "Display all documents from a collection with the help of find() method −"
},
{
"code": null,
"e": 1775,
"s": 1736,
"text": "> db.dynamicQueryDemo.find().pretty();"
},
{
"code": null,
"e": 1816,
"s": 1775,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2185,
"s": 1816,
"text": "{\n \"_id\" : ObjectId(\"5cef5c5def71edecf6a1f69a\"),\n \"Name\" : \"John\",\n \"Subject\" : [\n \"MongoDB\",\n \"MySQL\"\n ]\n}\n{\n \"_id\" : ObjectId(\"5cef5c73ef71edecf6a1f69b\"),\n \"Name\" : \"John\",\n \"Subject\" : [\n \"C\",\n \"C++\"\n ]\n}\n{\n \"_id\" : ObjectId(\"5cef5c8bef71edecf6a1f69c\"),\n \"Name\" : \"John\",\n \"Subject\" : [\n \"MongoDB\",\n \"Java\"\n ]\n}"
},
{
"code": null,
"e": 2245,
"s": 2185,
"text": "Following is the query to dynamically build MongoDB query −"
},
{
"code": null,
"e": 2560,
"s": 2245,
"text": "> function findDocument(subject) {\n var find = {};\n if (subject.length == 0)\n find[\"$nin\"] = subject;\n else\n find[\"$in\"] = subject;\n return find;\n}\n> var sub = [\"MySQL\",\"MongoDB\"];\n> var myDoc = findDocument(sub);\n\n> db.dynamicQueryDemo.aggregate([{\n $match: {\n \"Subject\": myDoc,\n }\n}]);"
},
{
"code": null,
"e": 2601,
"s": 2560,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2804,
"s": 2601,
"text": "{ \"_id\" : ObjectId(\"5cef5c5def71edecf6a1f69a\"), \"Name\" : \"John\", \"Subject\" : [ \"MongoDB\", \"MySQL\" ] }\n{ \"_id\" : ObjectId(\"5cef5c8bef71edecf6a1f69c\"), \"Name\" : \"John\", \"Subject\" : [ \"MongoDB\", \"Java\" ] }"
}
] |
Create a wave array from the given Binary Search Tree - GeeksforGeeks | 25 Feb, 2022
Given a Binary Search Tree, the task is to create a wave array from the given Binary Search Tree. An array arr[0..n-1] is called a wave array if arr[0] >= arr[1] <= arr[2] >= arr[3] <= arr[4] >= ...
Examples:
Input:
Output: 4 2 8 6 12 10 14Explanation: The above mentioned array {4, 2, 8, 6, 12, 10, 14} is one of the many valid wave arrays.
Input:
Output: 4 2 8 6 12
Approach: The given problem can be solved by the observation that the Inorder Traversal of the Binary Search Tree gives nodes in non-decreasing order. Therefore, store the inorder traversal of the given tree into a vector. Since the vector contains elements in sorted order, it can be converted into a wave array by swapping the adjacent elements for all elements in the range [0, N) using the approach discussed in this article.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Node of the Binary Search treestruct Node { int data; Node* right; Node* left; // Constructor Node(int data) { this->data = data; this->left = NULL; this->right = NULL; }}; // Function to convert Binary Search// Tree into a wave Arrayvoid toWaveArray(Node* root){ // Stores the final wave array vector<int> waveArr; stack<Node*> s; Node* curr = root; // Perform the Inorder traversal // of the given BST while (curr != NULL || s.empty() == false) { // Reach the left most Node of // the curr Node while (curr != NULL) { // Place pointer to a tree node // in stack before traversing // the node's left subtree s.push(curr); curr = curr->left; } curr = s.top(); s.pop(); // Insert into wave array waveArr.push_back(curr->data); // Visit the right subtree curr = curr->right; } // Convert sorted array into wave array for (int i = 0; i + 1 < waveArr.size(); i += 2) { swap(waveArr[i], waveArr[i + 1]); } // Print the answer for (int i = 0; i < waveArr.size(); i++) { cout << waveArr[i] << " "; }} // Driver Codeint main(){ Node* root = new Node(8); root->left = new Node(4); root->right = new Node(12); root->right->left = new Node(10); root->right->right = new Node(14); root->left->left = new Node(2); root->left->right = new Node(6); toWaveArray(root); return 0;}
// Java program for the above approachimport java.util.*; class GFG{ // Node of the Binary Search treestatic class Node { int data; Node right; Node left; // Constructor Node(int data) { this.data = data; this.left = null; this.right = null; }}; // Function to convert Binary Search// Tree into a wave Arraystatic void toWaveArray(Node root){ // Stores the final wave array Vector<Integer> waveArr = new Vector<>(); Stack<Node> s = new Stack<>(); Node curr = root; // Perform the Inorder traversal // of the given BST while (curr != null || s.isEmpty() == false) { // Reach the left most Node of // the curr Node while (curr != null) { // Place pointer to a tree node // in stack before traversing // the node's left subtree s.add(curr); curr = curr.left; } curr = s.peek(); s.pop(); // Insert into wave array waveArr.add(curr.data); // Visit the right subtree curr = curr.right; } // Convert sorted array into wave array for (int i = 0; i + 1 < waveArr.size(); i += 2) { int t = waveArr.get(i); waveArr.set(i, waveArr.get(i+1)); waveArr.set(i+1, t); } // Print the answer for (int i = 0; i < waveArr.size(); i++) { System.out.print(waveArr.get(i)+ " "); }} // Driver Codepublic static void main(String[] args){ Node root = new Node(8); root.left = new Node(4); root.right = new Node(12); root.right.left = new Node(10); root.right.right = new Node(14); root.left.left = new Node(2); root.left.right = new Node(6); toWaveArray(root); }} // This code is contributed by umadevi9616
# Python program for the above approach # Node of the Binary Search treeclass Node: def __init__(self, data): self.data = data; self.right = None; self.left = None; # Function to convert Binary Search# Tree into a wave Arraydef toWaveArray(root): # Stores the final wave array waveArr = []; s = []; curr = root; # Perform the Inorder traversal # of the given BST while (curr != None or len(s) != 0): # Reach the left most Node of # the curr Node while (curr != None): # Place pointer to a tree Node # in stack before traversing # the Node's left subtree s.append(curr); curr = curr.left; curr = s.pop(); # Insert into wave array waveArr.append(curr.data); # Visit the right subtree curr = curr.right; # Convert sorted array into wave array for i in range(0,len(waveArr)-1, 2): t = waveArr[i]; waveArr[i] = waveArr[i + 1]; waveArr[i + 1]= t; # Print the answer for i in range(len(waveArr)): print(waveArr[i], end=" "); # Driver Codeif __name__ == '__main__': root = Node(8); root.left = Node(4); root.right = Node(12); root.right.left = Node(10); root.right.right = Node(14); root.left.left = Node(2); root.left.right = Node(6); toWaveArray(root); # This code is contributed by Rajput-Ji
// C# program for the above approachusing System;using System.Collections.Generic; public class GFG{ // Node of the Binary Search treepublic class Node { public int data; public Node right; public Node left; // Constructor public Node(int data) { this.data = data; this.left = null; this.right = null; }}; // Function to convert Binary Search// Tree into a wave Arraystatic void toWaveArray(Node root){ // Stores the readonly wave array List<int> waveArr = new List<int>(); Stack<Node> s = new Stack<Node>(); Node curr = root; // Perform the Inorder traversal // of the given BST while (curr != null || s.Count!=0 ) { // Reach the left most Node of // the curr Node while (curr != null) { // Place pointer to a tree node // in stack before traversing // the node's left subtree s.Push(curr); curr = curr.left; } curr = s.Peek(); s.Pop(); // Insert into wave array waveArr.Add(curr.data); // Visit the right subtree curr = curr.right; } // Convert sorted array into wave array for (int i = 0; i + 1 < waveArr.Count; i += 2) { int t = waveArr[i]; waveArr[i]= waveArr[i+1]; waveArr[i+1]= t; } // Print the answer for (int i = 0; i < waveArr.Count; i++) { Console.Write(waveArr[i]+ " "); }} // Driver Codepublic static void Main(String[] args){ Node root = new Node(8); root.left = new Node(4); root.right = new Node(12); root.right.left = new Node(10); root.right.right = new Node(14); root.left.left = new Node(2); root.left.right = new Node(6); toWaveArray(root);}} // This code is contributed by umadevi9616
<script> // JavaScript Program to implement // the above approach class Node { constructor(data) { this.data = data; this.left = this.right = null; } } // Function to convert Binary Search // Tree into a wave Array function toWaveArray(root) { // Stores the final wave array let waveArr = []; let s = []; let curr = root; // Perform the Inorder traversal // of the given BST while (curr != null || s.length != 0) { // Reach the left most Node of // the curr Node while (curr != null) { // Place pointer to a tree node // in stack before traversing // the node's left subtree s.push(curr); curr = curr.left; } curr = s[s.length - 1]; s.pop(); // Insert into wave array waveArr.push(curr.data); // Visit the right subtree curr = curr.right; } // Convert sorted array into wave array for (let i = 0; i + 1 < waveArr.length; i += 2) { let temp = waveArr[i] waveArr[i] = waveArr[i + 1] waveArr[i + 1] = temp } // Print the answer for (let i = 0; i < waveArr.length; i++) { document.write(waveArr[i] + " "); } } // Driver Code let root = new Node(8); root.left = new Node(4); root.right = new Node(12); root.right.left = new Node(10); root.right.right = new Node(14); root.left.left = new Node(2); root.left.right = new Node(6); toWaveArray(root); // This code is contributed by Potta Lokesh </script>
4 2 8 6 12 10 14
Time Complexity: O(N)Auxiliary Space: O(N)
lokeshpotta20
umadevi9616
Rajput-Ji
simranarora5sos
BST
Inorder Traversal
Tree Traversals
tree-traversal
Arrays
Binary Search Tree
Mathematical
Tree
Arrays
Mathematical
Binary Search Tree
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Window Sliding Technique
Trapping Rain Water
Reversal algorithm for array rotation
Move all negative numbers to beginning and positive to end with constant extra space
Program to find sum of elements in a given array
Binary Search Tree | Set 1 (Search and Insertion)
AVL Tree | Set 1 (Insertion)
Binary Search Tree | Set 2 (Delete)
A program to check if a binary tree is BST or not
Sorted Array to Balanced BST | [
{
"code": null,
"e": 24820,
"s": 24792,
"text": "\n25 Feb, 2022"
},
{
"code": null,
"e": 25019,
"s": 24820,
"text": "Given a Binary Search Tree, the task is to create a wave array from the given Binary Search Tree. An array arr[0..n-1] is called a wave array if arr[0] >= arr[1] <= arr[2] >= arr[3] <= arr[4] >= ..."
},
{
"code": null,
"e": 25029,
"s": 25019,
"text": "Examples:"
},
{
"code": null,
"e": 25036,
"s": 25029,
"text": "Input:"
},
{
"code": null,
"e": 25162,
"s": 25036,
"text": "Output: 4 2 8 6 12 10 14Explanation: The above mentioned array {4, 2, 8, 6, 12, 10, 14} is one of the many valid wave arrays."
},
{
"code": null,
"e": 25169,
"s": 25162,
"text": "Input:"
},
{
"code": null,
"e": 25189,
"s": 25169,
"text": "Output: 4 2 8 6 12 "
},
{
"code": null,
"e": 25619,
"s": 25189,
"text": "Approach: The given problem can be solved by the observation that the Inorder Traversal of the Binary Search Tree gives nodes in non-decreasing order. Therefore, store the inorder traversal of the given tree into a vector. Since the vector contains elements in sorted order, it can be converted into a wave array by swapping the adjacent elements for all elements in the range [0, N) using the approach discussed in this article."
},
{
"code": null,
"e": 25670,
"s": 25619,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 25674,
"s": 25670,
"text": "C++"
},
{
"code": null,
"e": 25679,
"s": 25674,
"text": "Java"
},
{
"code": null,
"e": 25687,
"s": 25679,
"text": "Python3"
},
{
"code": null,
"e": 25690,
"s": 25687,
"text": "C#"
},
{
"code": null,
"e": 25701,
"s": 25690,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Node of the Binary Search treestruct Node { int data; Node* right; Node* left; // Constructor Node(int data) { this->data = data; this->left = NULL; this->right = NULL; }}; // Function to convert Binary Search// Tree into a wave Arrayvoid toWaveArray(Node* root){ // Stores the final wave array vector<int> waveArr; stack<Node*> s; Node* curr = root; // Perform the Inorder traversal // of the given BST while (curr != NULL || s.empty() == false) { // Reach the left most Node of // the curr Node while (curr != NULL) { // Place pointer to a tree node // in stack before traversing // the node's left subtree s.push(curr); curr = curr->left; } curr = s.top(); s.pop(); // Insert into wave array waveArr.push_back(curr->data); // Visit the right subtree curr = curr->right; } // Convert sorted array into wave array for (int i = 0; i + 1 < waveArr.size(); i += 2) { swap(waveArr[i], waveArr[i + 1]); } // Print the answer for (int i = 0; i < waveArr.size(); i++) { cout << waveArr[i] << \" \"; }} // Driver Codeint main(){ Node* root = new Node(8); root->left = new Node(4); root->right = new Node(12); root->right->left = new Node(10); root->right->right = new Node(14); root->left->left = new Node(2); root->left->right = new Node(6); toWaveArray(root); return 0;}",
"e": 27319,
"s": 25701,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*; class GFG{ // Node of the Binary Search treestatic class Node { int data; Node right; Node left; // Constructor Node(int data) { this.data = data; this.left = null; this.right = null; }}; // Function to convert Binary Search// Tree into a wave Arraystatic void toWaveArray(Node root){ // Stores the final wave array Vector<Integer> waveArr = new Vector<>(); Stack<Node> s = new Stack<>(); Node curr = root; // Perform the Inorder traversal // of the given BST while (curr != null || s.isEmpty() == false) { // Reach the left most Node of // the curr Node while (curr != null) { // Place pointer to a tree node // in stack before traversing // the node's left subtree s.add(curr); curr = curr.left; } curr = s.peek(); s.pop(); // Insert into wave array waveArr.add(curr.data); // Visit the right subtree curr = curr.right; } // Convert sorted array into wave array for (int i = 0; i + 1 < waveArr.size(); i += 2) { int t = waveArr.get(i); waveArr.set(i, waveArr.get(i+1)); waveArr.set(i+1, t); } // Print the answer for (int i = 0; i < waveArr.size(); i++) { System.out.print(waveArr.get(i)+ \" \"); }} // Driver Codepublic static void main(String[] args){ Node root = new Node(8); root.left = new Node(4); root.right = new Node(12); root.right.left = new Node(10); root.right.right = new Node(14); root.left.left = new Node(2); root.left.right = new Node(6); toWaveArray(root); }} // This code is contributed by umadevi9616",
"e": 29084,
"s": 27319,
"text": null
},
{
"code": "# Python program for the above approach # Node of the Binary Search treeclass Node: def __init__(self, data): self.data = data; self.right = None; self.left = None; # Function to convert Binary Search# Tree into a wave Arraydef toWaveArray(root): # Stores the final wave array waveArr = []; s = []; curr = root; # Perform the Inorder traversal # of the given BST while (curr != None or len(s) != 0): # Reach the left most Node of # the curr Node while (curr != None): # Place pointer to a tree Node # in stack before traversing # the Node's left subtree s.append(curr); curr = curr.left; curr = s.pop(); # Insert into wave array waveArr.append(curr.data); # Visit the right subtree curr = curr.right; # Convert sorted array into wave array for i in range(0,len(waveArr)-1, 2): t = waveArr[i]; waveArr[i] = waveArr[i + 1]; waveArr[i + 1]= t; # Print the answer for i in range(len(waveArr)): print(waveArr[i], end=\" \"); # Driver Codeif __name__ == '__main__': root = Node(8); root.left = Node(4); root.right = Node(12); root.right.left = Node(10); root.right.right = Node(14); root.left.left = Node(2); root.left.right = Node(6); toWaveArray(root); # This code is contributed by Rajput-Ji",
"e": 30523,
"s": 29084,
"text": null
},
{
"code": "// C# program for the above approachusing System;using System.Collections.Generic; public class GFG{ // Node of the Binary Search treepublic class Node { public int data; public Node right; public Node left; // Constructor public Node(int data) { this.data = data; this.left = null; this.right = null; }}; // Function to convert Binary Search// Tree into a wave Arraystatic void toWaveArray(Node root){ // Stores the readonly wave array List<int> waveArr = new List<int>(); Stack<Node> s = new Stack<Node>(); Node curr = root; // Perform the Inorder traversal // of the given BST while (curr != null || s.Count!=0 ) { // Reach the left most Node of // the curr Node while (curr != null) { // Place pointer to a tree node // in stack before traversing // the node's left subtree s.Push(curr); curr = curr.left; } curr = s.Peek(); s.Pop(); // Insert into wave array waveArr.Add(curr.data); // Visit the right subtree curr = curr.right; } // Convert sorted array into wave array for (int i = 0; i + 1 < waveArr.Count; i += 2) { int t = waveArr[i]; waveArr[i]= waveArr[i+1]; waveArr[i+1]= t; } // Print the answer for (int i = 0; i < waveArr.Count; i++) { Console.Write(waveArr[i]+ \" \"); }} // Driver Codepublic static void Main(String[] args){ Node root = new Node(8); root.left = new Node(4); root.right = new Node(12); root.right.left = new Node(10); root.right.right = new Node(14); root.left.left = new Node(2); root.left.right = new Node(6); toWaveArray(root);}} // This code is contributed by umadevi9616",
"e": 32316,
"s": 30523,
"text": null
},
{
"code": "<script> // JavaScript Program to implement // the above approach class Node { constructor(data) { this.data = data; this.left = this.right = null; } } // Function to convert Binary Search // Tree into a wave Array function toWaveArray(root) { // Stores the final wave array let waveArr = []; let s = []; let curr = root; // Perform the Inorder traversal // of the given BST while (curr != null || s.length != 0) { // Reach the left most Node of // the curr Node while (curr != null) { // Place pointer to a tree node // in stack before traversing // the node's left subtree s.push(curr); curr = curr.left; } curr = s[s.length - 1]; s.pop(); // Insert into wave array waveArr.push(curr.data); // Visit the right subtree curr = curr.right; } // Convert sorted array into wave array for (let i = 0; i + 1 < waveArr.length; i += 2) { let temp = waveArr[i] waveArr[i] = waveArr[i + 1] waveArr[i + 1] = temp } // Print the answer for (let i = 0; i < waveArr.length; i++) { document.write(waveArr[i] + \" \"); } } // Driver Code let root = new Node(8); root.left = new Node(4); root.right = new Node(12); root.right.left = new Node(10); root.right.right = new Node(14); root.left.left = new Node(2); root.left.right = new Node(6); toWaveArray(root); // This code is contributed by Potta Lokesh </script>",
"e": 34276,
"s": 32316,
"text": null
},
{
"code": null,
"e": 34293,
"s": 34276,
"text": "4 2 8 6 12 10 14"
},
{
"code": null,
"e": 34338,
"s": 34295,
"text": "Time Complexity: O(N)Auxiliary Space: O(N)"
},
{
"code": null,
"e": 34352,
"s": 34338,
"text": "lokeshpotta20"
},
{
"code": null,
"e": 34364,
"s": 34352,
"text": "umadevi9616"
},
{
"code": null,
"e": 34374,
"s": 34364,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 34390,
"s": 34374,
"text": "simranarora5sos"
},
{
"code": null,
"e": 34394,
"s": 34390,
"text": "BST"
},
{
"code": null,
"e": 34412,
"s": 34394,
"text": "Inorder Traversal"
},
{
"code": null,
"e": 34428,
"s": 34412,
"text": "Tree Traversals"
},
{
"code": null,
"e": 34443,
"s": 34428,
"text": "tree-traversal"
},
{
"code": null,
"e": 34450,
"s": 34443,
"text": "Arrays"
},
{
"code": null,
"e": 34469,
"s": 34450,
"text": "Binary Search Tree"
},
{
"code": null,
"e": 34482,
"s": 34469,
"text": "Mathematical"
},
{
"code": null,
"e": 34487,
"s": 34482,
"text": "Tree"
},
{
"code": null,
"e": 34494,
"s": 34487,
"text": "Arrays"
},
{
"code": null,
"e": 34507,
"s": 34494,
"text": "Mathematical"
},
{
"code": null,
"e": 34526,
"s": 34507,
"text": "Binary Search Tree"
},
{
"code": null,
"e": 34531,
"s": 34526,
"text": "Tree"
},
{
"code": null,
"e": 34629,
"s": 34531,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34654,
"s": 34629,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 34674,
"s": 34654,
"text": "Trapping Rain Water"
},
{
"code": null,
"e": 34712,
"s": 34674,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 34797,
"s": 34712,
"text": "Move all negative numbers to beginning and positive to end with constant extra space"
},
{
"code": null,
"e": 34846,
"s": 34797,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 34896,
"s": 34846,
"text": "Binary Search Tree | Set 1 (Search and Insertion)"
},
{
"code": null,
"e": 34925,
"s": 34896,
"text": "AVL Tree | Set 1 (Insertion)"
},
{
"code": null,
"e": 34961,
"s": 34925,
"text": "Binary Search Tree | Set 2 (Delete)"
},
{
"code": null,
"e": 35011,
"s": 34961,
"text": "A program to check if a binary tree is BST or not"
}
] |
Java enum Keyword | ❮ Java Keywords
Create an enum with constants (unchangeable variables):
enum Level {
LOW,
MEDIUM,
HIGH
}
You can access enum constants with the dot syntax:
The enum keyword declares an enumerated (unchangeable) type.
An enum is a special "class" that represents a group of constants (unchangeable variables, like final variables).
To create an enum, use the enum keyword (instead of class or interface), and separate the constants with a comma. Note that they should be in uppercase letters.
An enum can, just like a class, have attributes and methods. The only
difference is that enum constants are public, static and final
(unchangeable - cannot be overridden).
An enum cannot be used to create objects, and it can not extend other classes (but it can implement interfaces).
Use enums when you have values that you know aren't going to change, like month days, days, colors, deck of cards, etc.
Read more about enums in our Java Enum Tutorial.
❮ Java Keywords
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
[email protected]
Your message has been sent to W3Schools. | [
{
"code": null,
"e": 18,
"s": 0,
"text": "\n❮ Java Keywords\n"
},
{
"code": null,
"e": 74,
"s": 18,
"text": "Create an enum with constants (unchangeable variables):"
},
{
"code": null,
"e": 114,
"s": 74,
"text": "enum Level {\n LOW,\n MEDIUM,\n HIGH\n}\n"
},
{
"code": null,
"e": 165,
"s": 114,
"text": "You can access enum constants with the dot syntax:"
},
{
"code": null,
"e": 226,
"s": 165,
"text": "The enum keyword declares an enumerated (unchangeable) type."
},
{
"code": null,
"e": 340,
"s": 226,
"text": "An enum is a special \"class\" that represents a group of constants (unchangeable variables, like final variables)."
},
{
"code": null,
"e": 501,
"s": 340,
"text": "To create an enum, use the enum keyword (instead of class or interface), and separate the constants with a comma. Note that they should be in uppercase letters."
},
{
"code": null,
"e": 675,
"s": 501,
"text": "An enum can, just like a class, have attributes and methods. The only \ndifference is that enum constants are public, static and final \n(unchangeable - cannot be overridden)."
},
{
"code": null,
"e": 788,
"s": 675,
"text": "An enum cannot be used to create objects, and it can not extend other classes (but it can implement interfaces)."
},
{
"code": null,
"e": 908,
"s": 788,
"text": "Use enums when you have values that you know aren't going to change, like month days, days, colors, deck of cards, etc."
},
{
"code": null,
"e": 957,
"s": 908,
"text": "Read more about enums in our Java Enum Tutorial."
},
{
"code": null,
"e": 975,
"s": 957,
"text": "\n❮ Java Keywords\n"
},
{
"code": null,
"e": 1008,
"s": 975,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 1050,
"s": 1008,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 1157,
"s": 1050,
"text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:"
},
{
"code": null,
"e": 1176,
"s": 1157,
"text": "[email protected]"
}
] |
How to Insert Form Data into Database using PHP ? - GeeksforGeeks | 31 Jul, 2021
In this article, we are going to store data in database which is submitted through HTML form.
Requirements:
XAMPP Server (Web Server)
HTML
PHP
MySQL
HTML form: First we create an HTML form that need to take user input from keyboard. HTML form is a document which stores information of a user on a web server using interactive controls. An HTML form contains different kind of information such as username, password, contact number, email id etc.
The elements that are used in an HTML form are check box, input box, radio buttons, submit buttons etc. With the help of these elements, the information of an user is submitted on the web server. The form tag is used to create an HTML form.
Syntax:
<form> Form Elements... </form>
or
To pass the values to next page, we use the page name with the following syntax. We can use either GET or POST method to sent data to server.
<form action=other_page.php method= POST/GET>
Form Elements...
</form>
Database Connection: The collection of related data is called a database. XAMPP stands for cross-platform, Apache, MySQL, PHP, and Perl. It is among the simple light-weight local servers for website development. In PHP, we can connect to database using localhost XAMPP web server.
Syntax:
PHP
<?php $servername = "localhost";$username = "username";$password = "password";$dbname = "database_name"; // Create connection$conn = new mysqli($servername, $username, $password, $dbname); // Check connectionif ($conn->connect_error) { die("Connection failed: " . $conn->connect_error);} $sqlquery = "INSERT INTO table VALUES ('John', 'Doe', '[email protected]')" if ($conn->query($sql) === TRUE) { echo "record inserted successfully";} else { echo "Error: " . $sql . "<br>" . $conn->error;}
How to get form data: We are going to collect the form data submitted through HTML form. PHP $_REQUEST method is a PHP super global variable which is used to collect data after submitting the HTML form.
Syntax:
PHP
<?php if ($_SERVER["REQUEST_METHOD"] == "POST") { // collect value of input field $data = $_REQUEST['val1']; if (empty($data)) { echo "data is empty"; } else { echo $data; }}?> // Closing the connection.$conn->close(); ?>
Complete Steps to Design Project:
Start XAMPP Server.
Open localhost/phpmyadmin in your web browser.
Create database of name staff and table of name college.
Write HTML and PHP code in your Notepad in a particular folder.
Submit data through HTML Form.
Verify the results.
Steps In detail:
Start XAMPP Server by opening XAMPP and click on XAMPP Start.
Open localhost/phpmyadmin in your web browser and create database with database name as staff and click on create.
Then create table name college.
Enter columns and click on save
Now open Notepad and start writing PHP code and save it as index.php and open other notepad and save it as insert.php Save both files in one folder under htdocs.
Filename: index.php
PHP
<!DOCTYPE html><html lang="en"> <head> <title>GFG- Store Data</title></head> <body> <center> <h1>Storing Form data in Database</h1> <form action="insert.php" method="post"> <p> <label for="firstName">First Name:</label> <input type="text" name="first_name" id="firstName"> </p> <p> <label for="lastName">Last Name:</label> <input type="text" name="last_name" id="lastName"> </p> <p> <label for="Gender">Gender:</label> <input type="text" name="gender" id="Gender"> </p> <p> <label for="Address">Address:</label> <input type="text" name="address" id="Address"> </p> <p> <label for="emailAddress">Email Address:</label> <input type="text" name="email" id="emailAddress"> </p> <input type="submit" value="Submit"> </form> </center></body> </html>
Filename: insert.php
PHP
<!DOCTYPE html><html> <head> <title>Insert Page page</title></head> <body> <center> <?php // servername => localhost // username => root // password => empty // database name => staff $conn = mysqli_connect("localhost", "root", "", "staff"); // Check connection if($conn === false){ die("ERROR: Could not connect. " . mysqli_connect_error()); } // Taking all 5 values from the form data(input) $first_name = $_REQUEST['first_name']; $last_name = $_REQUEST['last_name']; $gender = $_REQUEST['gender']; $address = $_REQUEST['address']; $email = $_REQUEST['email']; // Performing insert query execution // here our table name is college $sql = "INSERT INTO college VALUES ('$first_name', '$last_name','$gender','$address','$email')"; if(mysqli_query($conn, $sql)){ echo "<h3>data stored in a database successfully." . " Please browse your localhost php my admin" . " to view the updated data</h3>"; echo nl2br("\n$first_name\n $last_name\n " . "$gender\n $address\n $email"); } else{ echo "ERROR: Hush! Sorry $sql. " . mysqli_error($conn); } // Close connection mysqli_close($conn); ?> </center></body> </html>
Output: Type localhost/7058/index.php in your browser, it will display the form. After submitting the form, the form data is submitted into database.
Let’s check in our database
HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples.
PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
akshaysingh98088
HTML-Misc
PHP-Misc
HTML
PHP
PHP Programs
Web Technologies
Web technologies Questions
HTML
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to update Node.js and NPM to next version ?
REST API (Introduction)
CSS to put icon inside an input element in a form
Types of CSS (Cascading Style Sheet)
HTML | <img> align Attribute
How to execute PHP code using command line ?
PHP in_array() Function
How to convert array to string in PHP ?
How to pop an alert message box using PHP ?
How to delete an array element based on key in PHP? | [
{
"code": null,
"e": 24946,
"s": 24918,
"text": "\n31 Jul, 2021"
},
{
"code": null,
"e": 25041,
"s": 24946,
"text": "In this article, we are going to store data in database which is submitted through HTML form. "
},
{
"code": null,
"e": 25055,
"s": 25041,
"text": "Requirements:"
},
{
"code": null,
"e": 25081,
"s": 25055,
"text": "XAMPP Server (Web Server)"
},
{
"code": null,
"e": 25086,
"s": 25081,
"text": "HTML"
},
{
"code": null,
"e": 25090,
"s": 25086,
"text": "PHP"
},
{
"code": null,
"e": 25096,
"s": 25090,
"text": "MySQL"
},
{
"code": null,
"e": 25393,
"s": 25096,
"text": "HTML form: First we create an HTML form that need to take user input from keyboard. HTML form is a document which stores information of a user on a web server using interactive controls. An HTML form contains different kind of information such as username, password, contact number, email id etc."
},
{
"code": null,
"e": 25634,
"s": 25393,
"text": "The elements that are used in an HTML form are check box, input box, radio buttons, submit buttons etc. With the help of these elements, the information of an user is submitted on the web server. The form tag is used to create an HTML form."
},
{
"code": null,
"e": 25642,
"s": 25634,
"text": "Syntax:"
},
{
"code": null,
"e": 25674,
"s": 25642,
"text": "<form> Form Elements... </form>"
},
{
"code": null,
"e": 25677,
"s": 25674,
"text": "or"
},
{
"code": null,
"e": 25819,
"s": 25677,
"text": "To pass the values to next page, we use the page name with the following syntax. We can use either GET or POST method to sent data to server."
},
{
"code": null,
"e": 25895,
"s": 25819,
"text": "<form action=other_page.php method= POST/GET>\n Form Elements...\n</form>"
},
{
"code": null,
"e": 26176,
"s": 25895,
"text": "Database Connection: The collection of related data is called a database. XAMPP stands for cross-platform, Apache, MySQL, PHP, and Perl. It is among the simple light-weight local servers for website development. In PHP, we can connect to database using localhost XAMPP web server."
},
{
"code": null,
"e": 26184,
"s": 26176,
"text": "Syntax:"
},
{
"code": null,
"e": 26188,
"s": 26184,
"text": "PHP"
},
{
"code": "<?php $servername = \"localhost\";$username = \"username\";$password = \"password\";$dbname = \"database_name\"; // Create connection$conn = new mysqli($servername, $username, $password, $dbname); // Check connectionif ($conn->connect_error) { die(\"Connection failed: \" . $conn->connect_error);} $sqlquery = \"INSERT INTO table VALUES ('John', 'Doe', '[email protected]')\" if ($conn->query($sql) === TRUE) { echo \"record inserted successfully\";} else { echo \"Error: \" . $sql . \"<br>\" . $conn->error;}",
"e": 26709,
"s": 26188,
"text": null
},
{
"code": null,
"e": 26916,
"s": 26713,
"text": "How to get form data: We are going to collect the form data submitted through HTML form. PHP $_REQUEST method is a PHP super global variable which is used to collect data after submitting the HTML form."
},
{
"code": null,
"e": 26926,
"s": 26918,
"text": "Syntax:"
},
{
"code": null,
"e": 26932,
"s": 26928,
"text": "PHP"
},
{
"code": "<?php if ($_SERVER[\"REQUEST_METHOD\"] == \"POST\") { // collect value of input field $data = $_REQUEST['val1']; if (empty($data)) { echo \"data is empty\"; } else { echo $data; }}?> // Closing the connection.$conn->close(); ?>",
"e": 27190,
"s": 26932,
"text": null
},
{
"code": null,
"e": 27228,
"s": 27194,
"text": "Complete Steps to Design Project:"
},
{
"code": null,
"e": 27250,
"s": 27230,
"text": "Start XAMPP Server."
},
{
"code": null,
"e": 27297,
"s": 27250,
"text": "Open localhost/phpmyadmin in your web browser."
},
{
"code": null,
"e": 27354,
"s": 27297,
"text": "Create database of name staff and table of name college."
},
{
"code": null,
"e": 27418,
"s": 27354,
"text": "Write HTML and PHP code in your Notepad in a particular folder."
},
{
"code": null,
"e": 27449,
"s": 27418,
"text": "Submit data through HTML Form."
},
{
"code": null,
"e": 27469,
"s": 27449,
"text": "Verify the results."
},
{
"code": null,
"e": 27488,
"s": 27471,
"text": "Steps In detail:"
},
{
"code": null,
"e": 27554,
"s": 27490,
"text": "Start XAMPP Server by opening XAMPP and click on XAMPP Start. "
},
{
"code": null,
"e": 27671,
"s": 27554,
"text": "Open localhost/phpmyadmin in your web browser and create database with database name as staff and click on create. "
},
{
"code": null,
"e": 27705,
"s": 27671,
"text": "Then create table name college. "
},
{
"code": null,
"e": 27737,
"s": 27705,
"text": "Enter columns and click on save"
},
{
"code": null,
"e": 27899,
"s": 27737,
"text": "Now open Notepad and start writing PHP code and save it as index.php and open other notepad and save it as insert.php Save both files in one folder under htdocs."
},
{
"code": null,
"e": 27921,
"s": 27901,
"text": "Filename: index.php"
},
{
"code": null,
"e": 27927,
"s": 27923,
"text": "PHP"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <title>GFG- Store Data</title></head> <body> <center> <h1>Storing Form data in Database</h1> <form action=\"insert.php\" method=\"post\"> <p> <label for=\"firstName\">First Name:</label> <input type=\"text\" name=\"first_name\" id=\"firstName\"> </p> <p> <label for=\"lastName\">Last Name:</label> <input type=\"text\" name=\"last_name\" id=\"lastName\"> </p> <p> <label for=\"Gender\">Gender:</label> <input type=\"text\" name=\"gender\" id=\"Gender\"> </p> <p> <label for=\"Address\">Address:</label> <input type=\"text\" name=\"address\" id=\"Address\"> </p> <p> <label for=\"emailAddress\">Email Address:</label> <input type=\"text\" name=\"email\" id=\"emailAddress\"> </p> <input type=\"submit\" value=\"Submit\"> </form> </center></body> </html>",
"e": 29123,
"s": 27927,
"text": null
},
{
"code": null,
"e": 29148,
"s": 29127,
"text": "Filename: insert.php"
},
{
"code": null,
"e": 29154,
"s": 29150,
"text": "PHP"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Insert Page page</title></head> <body> <center> <?php // servername => localhost // username => root // password => empty // database name => staff $conn = mysqli_connect(\"localhost\", \"root\", \"\", \"staff\"); // Check connection if($conn === false){ die(\"ERROR: Could not connect. \" . mysqli_connect_error()); } // Taking all 5 values from the form data(input) $first_name = $_REQUEST['first_name']; $last_name = $_REQUEST['last_name']; $gender = $_REQUEST['gender']; $address = $_REQUEST['address']; $email = $_REQUEST['email']; // Performing insert query execution // here our table name is college $sql = \"INSERT INTO college VALUES ('$first_name', '$last_name','$gender','$address','$email')\"; if(mysqli_query($conn, $sql)){ echo \"<h3>data stored in a database successfully.\" . \" Please browse your localhost php my admin\" . \" to view the updated data</h3>\"; echo nl2br(\"\\n$first_name\\n $last_name\\n \" . \"$gender\\n $address\\n $email\"); } else{ echo \"ERROR: Hush! Sorry $sql. \" . mysqli_error($conn); } // Close connection mysqli_close($conn); ?> </center></body> </html>",
"e": 30635,
"s": 29154,
"text": null
},
{
"code": null,
"e": 30785,
"s": 30635,
"text": "Output: Type localhost/7058/index.php in your browser, it will display the form. After submitting the form, the form data is submitted into database."
},
{
"code": null,
"e": 30813,
"s": 30785,
"text": "Let’s check in our database"
},
{
"code": null,
"e": 31007,
"s": 30813,
"text": "HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples."
},
{
"code": null,
"e": 31176,
"s": 31007,
"text": "PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples."
},
{
"code": null,
"e": 31313,
"s": 31176,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 31330,
"s": 31313,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 31340,
"s": 31330,
"text": "HTML-Misc"
},
{
"code": null,
"e": 31349,
"s": 31340,
"text": "PHP-Misc"
},
{
"code": null,
"e": 31354,
"s": 31349,
"text": "HTML"
},
{
"code": null,
"e": 31358,
"s": 31354,
"text": "PHP"
},
{
"code": null,
"e": 31371,
"s": 31358,
"text": "PHP Programs"
},
{
"code": null,
"e": 31388,
"s": 31371,
"text": "Web Technologies"
},
{
"code": null,
"e": 31415,
"s": 31388,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 31420,
"s": 31415,
"text": "HTML"
},
{
"code": null,
"e": 31424,
"s": 31420,
"text": "PHP"
},
{
"code": null,
"e": 31522,
"s": 31424,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31531,
"s": 31522,
"text": "Comments"
},
{
"code": null,
"e": 31544,
"s": 31531,
"text": "Old Comments"
},
{
"code": null,
"e": 31592,
"s": 31544,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 31616,
"s": 31592,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 31666,
"s": 31616,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 31703,
"s": 31666,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 31732,
"s": 31703,
"text": "HTML | <img> align Attribute"
},
{
"code": null,
"e": 31777,
"s": 31732,
"text": "How to execute PHP code using command line ?"
},
{
"code": null,
"e": 31801,
"s": 31777,
"text": "PHP in_array() Function"
},
{
"code": null,
"e": 31841,
"s": 31801,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 31885,
"s": 31841,
"text": "How to pop an alert message box using PHP ?"
}
] |
lftp - Unix, Linux Command | lftp can handle several file access methods - ftp, ftps, http, https,
hftp, fish, sftp and file (https and ftps are only available when lftp is
compiled with GNU TLS or OpenSSL library). You can specify the method to use in ‘open
URL’ command, e.g. ‘open http://www.us.kernel.org/pub/linux’. hftp is
ftp-over-http-proxy protocol. It can be used automatically instead of ftp
if ftp:proxy is set to ‘http://proxy[:port]’. Fish is a protocol working
over an ssh connection to a unix account. SFtp is a protocol implemented
in ssh2 as sftp subsystem.
Every operation in lftp is reliable, that is any not fatal error is
ignored and the operation is repeated. So if downloading breaks, it
will be restarted from the point automatically. Even if ftp server
does not support REST command, lftp will try to retrieve the file from
the very beginning until the file is transferred completely.
lftp has shell-like command syntax allowing you to launch several
commands in parallel in background (&). It is also possible to group
commands within () and execute them in background. All background jobs
are executed in the same single process. You can bring a foreground
job to background with ^Z (c-z) and back with command ‘wait’ (or ‘fg’ which
is alias to ‘wait’). To list running jobs, use command ‘jobs’. Some
commands allow redirecting their output (cat, ls, ...) to file or via
pipe to external command. Commands can be executed conditionally based
on termination status of previous command (&&, ||).
If you exit lftp when some jobs are not finished yet, lftp will move
itself to nohup mode in background. The same happens when you have a
real modem hangup or when you close an xterm.
lftp has builtin mirror which can download or update a whole directory
tree. There is also reverse mirror (mirror -R) which uploads or
updates a directory tree on server. Mirror can also synchronize directories
between two remote servers, using FXP if available.
There is command ‘at’ to launch a job at specified time in current
context, command ‘queue’ to queue commands for sequential execution
for current server, and much more.
On startup, lftp executes /etc/lftp.conf and then ~/.lftprc and
~/.lftp/rc. You can place aliases and ‘set’ commands there. Some
people prefer to see full protocol debug, use ‘debug’ to turn the
debug on. Use ‘debug 3’ to see only greeting messages and error
messages.
lftp has a number of settable variables. You can use ‘set -a’ to see
all variables and their values or ‘set -d’ to see list of defaults.
Variable names can be abbreviated and prefix can be omitted unless the
rest becomes ambiguous.
If lftp was compiled with OpenSSL (configure --with-openssl), then it includes software developed
by the OpenSSL Project for use in the OpenSSL Toolkit. (http://www.openssl.org/)
! shell command
Launch shell or shell command.
!ls
To do a directory listing of the local host.
alias [name [value]]
Define or undefine alias name. If value is omitted, the alias is
undefined, else it takes the value value. If no argument is given
the current aliases are listed.
alias dir ls -lF
alias less zmore
anon
Sets the user to anonymous. This is the default.
at time [ -- command ]
Wait until the given time and execute given (optional) command. See also at(1).
bookmark [subcommand]
The bookmark command controls bookmarks.
add <name> [<loc>] add current place or given location
to bookmarks and bind to given name
del <name> remove bookmark with name
edit start editor on bookmarks file
import <type> import foreign bookmarks
list list bookmarks (default)
cache [subcommand]
The cache command controls local memory cache.
The following subcommands are recognized:
stat print cache status (default)
on|off turn on/off caching
flush flush cache
size lim set memory limit, -1 means unlimited
expire Nx set cache expiration time to N seconds (x=s)
minutes (x=m) hours (x=h) or days (x=d)
cat files
cat outputs the remote file(s) to stdout. (See also more,
zcat and zmore)
cd rdir
Change current remote directory. The previous remote directory is
stored as ‘-’. You can do ‘cd -’ to change the directory back.
The previous directory for each site is also stored on disk,
so you can do ‘open site; cd -’ even after lftp restart.
chmod mode files
Change permission mask on remote files. The mode must be an octal number.
close [-a]
Close idle connections. By default only with the current server, use
-a to close all idle connections.
cls [OPTS] files...
‘cls’ tries to retrieve information about specified files or directories
and outputs the information according to format options. The difference between
‘ls’ and ‘cls’ is that ‘ls’ requests the server to format file listing, and
‘cls’ formats it itself, after retrieving all the needed information.
See ‘help cls’ for options.
commandcmdargs...
execute given command ignoring aliases.
debug [-o file] level|off
Switch debugging to level or turn it off. Use -o to redirect
the debug output to a file.
echo [-n] string
guess what it does.
eval [-f format ] args...
without -f it just executes given arguments as a command. With -f, arguments
are transformed into a new command. The format can contain plain text and
placeholders $0...$9 and $@, corresponding to the arguments.
exit [bg] [top] [kill] [code]
exit will exit from lftp or move to background if there are active jobs. If
no job is active, code is passed to operating system as lftp’s
termination status. If code is omitted, the exit code of last
command is used.
‘exit bg’ forces moving to background when cmd:move-background is false.
‘exit top’ makes top level ‘shell’ (internal lftp command executor) terminate.
‘exit kill’ kills all numbered jobs before exiting. The options can be combined, e.g.
‘at 08:00 -- exit top kill &’ kills all jobs and makes lftp exit at specified time.
fg
Alias for ‘wait’.
find [directory]
List files in the directory (current directory by default) recursively.
This can help with servers lacking ls -R support. You can redirect output
of this command.
ftpcopy
Obsolete. Use one of the following instead:
get ftp://... -o ftp://...
get -O ftp://... file1 file2...
put ftp://...
mput ftp://.../*
mget -O ftp://... ftp://.../*
get [-E] [-a] [-c] [-O base] rfile [-o lfile] ...
Retrieve the remote file rfile and store it as the local file
lfile. If -o is omitted, the file is stored to local file named as
base name of rfile. You can get multiple files by specifying multiple
instances of rfile (and -o lfile). Does not expand wildcards, use
mget for that.
-c continue, reget
-E delete source files after successful transfer
-a use ascii mode (binary is the default)
-O <base> specifies base directory or URL where files should be placed
Examples:
get README
get README -o debian.README
get README README.mirrors
get README -o debian.README README.mirrors -o debian.mirrors
get README -o ftp://some.host.org/debian.README
get README -o ftp://some.host.org/debian-dir/ (end slash is important)
get1 [OPTS] rfile
Transfer a single file. Options:
-o <lfile> destination file name (default - basename of rfile)
-c continue, reget
-E delete source files after successful transfer
-a use ascii mode (binary is the default)
--source-region=<from-to>
transfer specified region of source file
--target-position=<pos>
position in target file to write data at
glob [-d] [-a] [-f] command patterns
Glob given patterns containing metacharacters and pass result to given command.
E.g. ‘‘glob echo *’’.
-f plain files (default)
-d directories
-a all types
help [cmd]
Print help for cmd or if no cmd was specified print a list of
available commands.
jobs [-v]
List running jobs. -v means verbose, several -v can be specified.
kill all|job_no
Delete specified job with job_no or all jobs.
(For job_no see jobs)
lcd ldir
Change current local directory ldir. The previous local
directory is stored as ‘-’. You can do ‘lcd -’ to change the directory back.
lpwd
Print current working directory on local machine.
ls params
List remote files. You can redirect output of this command to file or
via pipe to external command. By default, ls output is cached, to see
new listing use
rels or
cache flush.
mget [-c] [-d] [-a] [-E] [-O base] files
Gets selected files with expanded wildcards.
-c continue, reget.
-d create directories the same as file names and get
the files into them instead of current directory.
-E delete source files after successful transfer
-a use ascii mode (binary is the default)
-O <base> specifies base directory or URL where files should be placed
mirror [OPTS] [source [target]]
Mirror specified source directory to local target directory. If target
directory ends with a slash, the source base name is appended to target
directory name. Source and/or target can be URLs pointing to directories.
-c, --continue continue a mirror job if possible
-e, --delete delete files not present at remote site
--delete-first delete old files before transferring new ones
--depth-first descend into subdirectories before transferring files
-s, --allow-suid set suid/sgid bits according to remote site
--allow-chown try to set owner and group on files
--ascii use ascii mode transfers (implies --ignore-size)
--ignore-time ignore time when deciding whether to download
--ignore-size ignore size when deciding whether to download
--only-missing download only missing files
--only-existing download only files already existing at target
-n, --only-newer download only newer files (-c won’t work)
--no-empty-dirs don’t create empty directories (implies --depth-first)
-r, --no-recursion don’t go to subdirectories
--no-symlinks don’t create symbolic links
-p, --no-perms don’t set file permissions
--no-umask don’t apply umask to file modes
-R, --reverse reverse mirror (put files)
-L, --dereference download symbolic links as files
-N, --newer-than=SPEC download only files newer than specified time
--on-change=CMD execute the command if anything has been changed
--older-than=SPEC download only files older than specified time
--size-range=RANGE download only files with size in specified range
-P, --parallel[=N] download N files in parallel
--use-pget[-n=N] use pget to transfer every single file
--loop loop until no changes found
-i RX, --include RX include matching files
-x RX, --exclude RX exclude matching files
-I GP, --include-glob GP include matching files
-X GP, --exclude-glob GP exclude matching files
-v, --verbose[=level] verbose operation
--log=FILE write lftp commands being executed to FILE
--script=FILE write lftp commands to FILE, but don’t execute them
--just-print, --dry-run same as --script=-
--use-cache use cached directory listings
--Remove-source-files remove files after transfer (use with caution)
-a same as --allow-chown --allow-suid --no-umask
When using -R, the first directory is local and the second is remote.
If the second directory is omitted, base name of first directory is used.
If both directories are omitted, current local and remote directories are used.
If target directory ends with a slash (except root directory) then base
name of source directory is appended.
RX is an extended regular expression, just like in egrep(1).
GP is a glob pattern, e.g. ‘*.zip’.
Include and exclude options can be specified multiple times. It means that
a file or directory would be mirrored if it matches an include and does
not match to excludes after the include, or does not match anything
and the first check is exclude. Directories are matched with a slash appended.
Note that symbolic links are not created when uploading to remote server,
because ftp protocol cannot do it. To upload files the links refer
to, use ‘mirror -RL’ command (treat symbolic links as files).
For option --newer-than you can either specify a file or time specification
like that used by at(1) command, e.g. ‘now-7days’ or ‘week ago’. If you
specify a file, then modification time of that file will be used.
Verbosity level can be selected using --verbose=level option or by several
-v options, e.g. -vvv. Levels are:
0 - no output (default)
1 - print actions
2 - +print not deleted file names (when -e is not specified)
3 - +print directory names which are mirrored
--only-newer turns off file size comparison and uploads/downloads
only newer files even if size is different. By default older files are transferred and replace newer ones.
You can mirror between two servers if you specify URLs instead of directories.
FXP is used automatically for transfers between ftp servers, if possible.
Some ftp servers hide dot-files by default (e.g. .htaccess), and show
them only when LIST command is used with -a option. In such case try to use
‘set ftp:list-options -a’.
mkdir [-p] dir(s)
Make remote directories. If -p is used, make all components of paths.
module module [ args ]
Load given module using dlopen(3) function. If module name does not contain
a slash, it is searched in directories specified by module:path variable.
Arguments are passed to module_init function. See README.modules for technical
details.
more files
Same as ‘cat files | more’. if PAGER is set, it is used as filter.
(See also cat, zcat and zmore)
mput [-c] [-d] [-a] [-E] [-O base] files
Upload files with wildcard expansion. By default it uses the base name of
local name as remote one. This can be changed by ‘-d’ option.
-c continue, reput
-d create directories the same as in file names and put the
files into them instead of current directory
-E delete source files after successful transfer (dangerous)
-a use ascii mode (binary is the default)
-O <base> specifies base directory or URL where files should be placed
mrm file(s)
Same as ‘glob rm’. Removes specified file(s) with wildcard expansion.
mv file1 file2
Rename file1 to file2.
nlist [args]
List remote file names
open [-e cmd] [-u user[,pass]] [-p port] host|url
Select an ftp server.
pget [OPTS] rfile [-o lfile]
Gets the specified file using several connections. This can speed up
transfer, but loads the net and server heavily impacting other users. Use only if
you really have to transfer the file ASAP.
Options:
-c continue transfer. Requires lfile.lftp-pget-status file.
-n maxconn set maximum number of connections (default is taken from pget:default-n setting)
put [-E] [-a] [-c] [-O base] lfile [-o rfile]
Upload lfile with remote name rfile. If -o omitted, the base name
of lfile is used as remote name. Does not expand wildcards, use mput for that.
-o <rfile> specifies remote file name (default - basename of lfile)
-c continue, reput
it requires permission to overwrite remote files
-E delete source files after successful transfer (dangerous)
-a use ascii mode (binary is the default)
-O <base> specifies base directory or URL where files should be placed
pwd [-p]
Print current remote URL. Use ‘-p’ option to show password in the URL.
queue [-n num ] cmd
Add the given command to queue for sequential execution. Each site has its own
queue. ‘-n’ adds the command before the given item in the queue. Don’t try to
queue ‘cd’ or ‘lcd’ commands, it may confuse lftp. Instead
do the cd/lcd before ‘queue’ command, and it will remember the place in which
the command is to be done. It is possible to queue up an already running job
by ‘queue wait <jobno>’, but the job will continue execution even if it is not
the first in queue.
‘queue stop’ will stop the queue, it will not execute any new commands,
but already running jobs will continue to run. You can use ‘queue stop’ to
create an empty stopped queue. ‘queue start’ will resume queue execution.
When you exit lftp, it will start all stopped queues automatically.
‘queue’ with no arguments will either create a stopped queue or print queue
status.
queue --delete|-d [index or wildcard expression]
Delete one or more items from the queue. If no argument is given, the last
entry in the queue is deleted.
queue --move|-m <index or wildcard expression> [index]
Move the given items before the given queue index, or to the end if no
destination is given.
-q Be quiet.
-v Be verbose.
-Q Output in a format that can be used to re-queue.
Useful with --delete.
> get file &
[1] get file
> queue wait 1
> queue get another_file
> cd a_directory
> queue get yet_another_file
queue -d 3 Delete the third item in the queue.
queue -m 6 4 Move the sixth item in the queue before the fourth.
queue -m "get*zip" 1 Move all commands matching "get*zip" to the beginning
of the queue. (The order of the items is preserved.)
queue -d "get*zip" Delete all commands matching "get*zip".
quote cmd
For FTP - send the command uninterpreted. Use with caution - it can lead to
unknown remote state and thus will cause reconnect. You cannot
be sure that any change of remote state because of quoted command
is solid - it can be reset by reconnect at any time.
For HTTP - specific to HTTP action. Syntax: ‘‘quote <command> [<args>]’’.
Command may be ‘‘set-cookie’’ or ‘‘post’’.
open http://www.site.net
quote set-cookie "variable=value; othervar=othervalue"
set http:post-content-type application/x-www-form-urlencoded
quote post /cgi-bin/script.cgi "var=value&othervar=othervalue" > local_file
For FISH - send the command uninterpreted. This can be used to execute
arbitrary commands on server. The command must not take input or print ###
at new line beginning. If it does, the protocol will become out of sync.
open fish://server
quote find -name \*.zip
reget rfile [-o lfile]
Same as ‘get -c’.
rels [args]
Same as ‘ls’, but ignores the cache.
renlist [args]
Same as ‘nlist’, but ignores the cache.
repeat [ -c <count>] [[-d] delay] [command]
Repeat the command. Between the commands a delay is inserted, by default 1 second.
Option ‘-c’ limits number of repeations. Option ‘--while-ok’ breaks loop when
command returns non-zero exit code; ‘--until-ok’ breaks on zero exit code.
Examples:
repeat at tomorrow -- mirror
repeat 1d mirror
reput lfile [-o rfile]
Same as ‘put -c’.
rm [-r] [-f] files
Remove remote files. Does not expand wildcards, use mrm for
that. -r is for recursive directory remove. Be careful, if something goes
wrong you can lose files. -f suppress error messages.
rmdir dir(s)
Remove remote directories.
scache [session]
List cached sessions or switch to specified session.
set [var [val]]
Set variable to given value. If the value is omitted, unset the variable.
Variable name has format ‘‘name/closure’’, where closure can specify
exact application of the setting. See below for details.
If set is called with no variable then only altered settings are listed.
It can be changed by options:
-a list all settings, including default values
-d list only default values, not necessary current ones
site site_cmd
Execute site command site_cmd and output the result.
You can redirect its output.
sleep interval
Sleep given time interval and exit. Interval is in seconds by default, but
can be suffixed with ’m’, ’h’, ’d’ for minutes, hours and days respectively.
See also at.
slot [name]
Select specified slot or list all slots allocated. A slot is a connection
to a server, somewhat like a virtual console. You can create multiple slots
connected to different servers and switch between them. You can also use
slot:name as a pseudo-URL evaluating to that slot location.
Default readline binding allows quick switching between slots named 0-9 using
Meta-0 - Meta-9 keys (often you can use Alt instead of Meta).
source file
source -e command
Execute commands recorded in file file or returned by specified external command.
source ~/.lftp/rc
source -e echo help
suspend
Stop lftp process. Note that transfers will be also stopped until you
continue the process with shell’s fg or bg commands.
user user [pass]
user URL [pass]
Use specified info for remote login. If you specify an URL with user name,
the entered password will be cached so that future URL references can use it.
version
Print lftp version.
wait [jobno]
wait all
Wait for specified job to terminate. If jobno is omitted, wait for last
backgrounded job.
‘wait all’ waits for all jobs termination.
zcat files
Same as cat, but filter each file through zcat. (See also cat,
more and zmore)
zmore files
Same as more, but filter each file through zcat. (See also cat,
zcat and more)
On startup, lftp executes
~/.lftprc and ~/.lftp/rc. You can place aliases
and ‘set’ commands there. Some people prefer to see full protocol
debug, use ‘debug’ to turn the debug on.
There is also a system-wide startup file in
/etc/lftp.conf. It can be in different directory, see FILES section.
lftp has the following settable variables (you can also use
‘set -a’ to see all variables and their values):
set cmd:verify-path/hftp://* false
cd directory &
set sftp:connect-program rsh
set sftp:server-program /usr/libexec/openssh/sftp-server
The closure for ‘dns:’, ‘net:’, ‘ftp:’, ‘http:’, ‘hftp:’ domain variables
is currently just the host name as you specify it in the ‘open’ command
(with some exceptions where closure is meaningless, e.g. dns:cache-size).
For some ‘cmd:’ domain variables the closure is current URL without path.
For other variables it is not currently used. See examples in the sample
lftp.conf.
Certain commands and settings take a time interval parameter. It has
the format Nx[Nx...], where N is time amount (floating point) and x is time unit: d - days,
h - hours, m - minutes, s - seconds. Default unit is second. E.g. 5h30m or 5.5h.
Also the interval can be ‘infinity’, ‘inf’, ‘never’, ‘forever’ - it means
infinite interval. E.g. ‘sleep forever’ or ‘set dns:cache-expire never’.
Boolean settings can be one of (true, on, yes, 1, +) for a True value
or one of (false, off, no, 0, -) for a False value.
Integer settings can have a suffix: k - kibi, m - mebi, g - gigi, etc.
They can also have a prefix: 0 - octal, 0x - hexadecimal.
Lftp can speed up ftp operations by sending several commands at once and
then checking all the responses. See ftp:sync-mode variable. Sometimes
this does not work, thus synchronous mode is the default. You can try
to turn synchronous mode off and see if it works for you. It is known
that some network software dealing with address translation works
incorrectly in the case of several FTP commands in one network packet.
RFC959 says: ‘‘The user-process sending another command before the
completion reply would be in violation of protocol; but server-FTP
processes should queue any commands that arrive while a preceding
command is in progress’’. Also, RFC1123 says: ‘‘Implementors MUST
NOT assume any correspondence between READ boundaries on the control
connection and the Telnet EOL sequences (CR LF).’’ and ‘‘a single READ
from the control connection may include more than one FTP command’’.
So it must be safe to send several commands at once, which speeds up
operation a lot and seems to work with all Unix and VMS based ftp
servers. Unfortunately, windows based servers often cannot handle
several commands in one packet, and so cannot some broken routers.
ftpd (1)
ftpd (1)
Alexander V. Lukyanov
[email protected]
Advertisements
129 Lectures
23 hours
Eduonix Learning Solutions
5 Lectures
4.5 hours
Frahaan Hussain
35 Lectures
2 hours
Pradeep D
41 Lectures
2.5 hours
Musab Zayadneh
46 Lectures
4 hours
GUHARAJANM
6 Lectures
4 hours
Uplatz
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 11130,
"s": 10581,
"text": "\nlftp can handle several file access methods - ftp, ftps, http, https,\nhftp, fish, sftp and file (https and ftps are only available when lftp is\ncompiled with GNU TLS or OpenSSL library). You can specify the method to use in ‘open\nURL’ command, e.g. ‘open http://www.us.kernel.org/pub/linux’. hftp is\nftp-over-http-proxy protocol. It can be used automatically instead of ftp\nif ftp:proxy is set to ‘http://proxy[:port]’. Fish is a protocol working\nover an ssh connection to a unix account. SFtp is a protocol implemented\nin ssh2 as sftp subsystem.\n"
},
{
"code": null,
"e": 11469,
"s": 11132,
"text": "\nEvery operation in lftp is reliable, that is any not fatal error is\nignored and the operation is repeated. So if downloading breaks, it\nwill be restarted from the point automatically. Even if ftp server\ndoes not support REST command, lftp will try to retrieve the file from\nthe very beginning until the file is transferred completely.\n"
},
{
"code": null,
"e": 12082,
"s": 11469,
"text": "\nlftp has shell-like command syntax allowing you to launch several\ncommands in parallel in background (&). It is also possible to group\ncommands within () and execute them in background. All background jobs\nare executed in the same single process. You can bring a foreground\njob to background with ^Z (c-z) and back with command ‘wait’ (or ‘fg’ which\nis alias to ‘wait’). To list running jobs, use command ‘jobs’. Some\ncommands allow redirecting their output (cat, ls, ...) to file or via\npipe to external command. Commands can be executed conditionally based\non termination status of previous command (&&, ||).\n"
},
{
"code": null,
"e": 12268,
"s": 12082,
"text": "\nIf you exit lftp when some jobs are not finished yet, lftp will move\nitself to nohup mode in background. The same happens when you have a\nreal modem hangup or when you close an xterm.\n"
},
{
"code": null,
"e": 12533,
"s": 12268,
"text": "\nlftp has builtin mirror which can download or update a whole directory\ntree. There is also reverse mirror (mirror -R) which uploads or\nupdates a directory tree on server. Mirror can also synchronize directories\nbetween two remote servers, using FXP if available.\n"
},
{
"code": null,
"e": 12705,
"s": 12533,
"text": "\nThere is command ‘at’ to launch a job at specified time in current\ncontext, command ‘queue’ to queue commands for sequential execution\nfor current server, and much more.\n"
},
{
"code": null,
"e": 12976,
"s": 12705,
"text": "\nOn startup, lftp executes /etc/lftp.conf and then ~/.lftprc and\n~/.lftp/rc. You can place aliases and ‘set’ commands there. Some\npeople prefer to see full protocol debug, use ‘debug’ to turn the\ndebug on. Use ‘debug 3’ to see only greeting messages and error\nmessages.\n"
},
{
"code": null,
"e": 13210,
"s": 12976,
"text": "\nlftp has a number of settable variables. You can use ‘set -a’ to see\nall variables and their values or ‘set -d’ to see list of defaults.\nVariable names can be abbreviated and prefix can be omitted unless the\nrest becomes ambiguous.\n"
},
{
"code": null,
"e": 13391,
"s": 13210,
"text": "\nIf lftp was compiled with OpenSSL (configure --with-openssl), then it includes software developed\nby the OpenSSL Project for use in the OpenSSL Toolkit. (http://www.openssl.org/)\n"
},
{
"code": null,
"e": 13413,
"s": 13395,
"text": "\n! shell command "
},
{
"code": null,
"e": 13446,
"s": 13413,
"text": "\nLaunch shell or shell command.\n"
},
{
"code": null,
"e": 13456,
"s": 13451,
"text": "!ls\n"
},
{
"code": null,
"e": 13503,
"s": 13456,
"text": "\nTo do a directory listing of the local host.\n"
},
{
"code": null,
"e": 13527,
"s": 13503,
"text": "\nalias [name [value]] "
},
{
"code": null,
"e": 13692,
"s": 13527,
"text": "\nDefine or undefine alias name. If value is omitted, the alias is\nundefined, else it takes the value value. If no argument is given\nthe current aliases are listed.\n"
},
{
"code": null,
"e": 13732,
"s": 13697,
"text": "alias dir ls -lF\nalias less zmore\n"
},
{
"code": null,
"e": 13739,
"s": 13732,
"text": "\nanon "
},
{
"code": null,
"e": 13791,
"s": 13739,
"text": "\nSets the user to anonymous. This is the default.\n"
},
{
"code": null,
"e": 13817,
"s": 13791,
"text": "\nat time [ -- command ] "
},
{
"code": null,
"e": 13899,
"s": 13817,
"text": "\nWait until the given time and execute given (optional) command. See also at(1).\n"
},
{
"code": null,
"e": 13924,
"s": 13899,
"text": "\nbookmark [subcommand] "
},
{
"code": null,
"e": 13967,
"s": 13924,
"text": "\nThe bookmark command controls bookmarks.\n"
},
{
"code": null,
"e": 14294,
"s": 13970,
"text": "add <name> [<loc>] add current place or given location\n to bookmarks and bind to given name\ndel <name> remove bookmark with name\nedit start editor on bookmarks file\nimport <type> import foreign bookmarks\nlist list bookmarks (default)\n"
},
{
"code": null,
"e": 14316,
"s": 14294,
"text": "\ncache [subcommand] "
},
{
"code": null,
"e": 14407,
"s": 14316,
"text": "\nThe cache command controls local memory cache.\nThe following subcommands are recognized:\n"
},
{
"code": null,
"e": 14746,
"s": 14410,
"text": "stat print cache status (default)\non|off turn on/off caching\nflush flush cache\nsize lim set memory limit, -1 means unlimited\nexpire Nx set cache expiration time to N seconds (x=s)\n minutes (x=m) hours (x=h) or days (x=d)\n"
},
{
"code": null,
"e": 14760,
"s": 14748,
"text": "\ncat files "
},
{
"code": null,
"e": 14837,
"s": 14760,
"text": "\ncat outputs the remote file(s) to stdout. (See also more,\nzcat and zmore)\n"
},
{
"code": null,
"e": 14847,
"s": 14837,
"text": "\ncd rdir "
},
{
"code": null,
"e": 15097,
"s": 14847,
"text": "\nChange current remote directory. The previous remote directory is\nstored as ‘-’. You can do ‘cd -’ to change the directory back.\nThe previous directory for each site is also stored on disk,\nso you can do ‘open site; cd -’ even after lftp restart.\n"
},
{
"code": null,
"e": 15116,
"s": 15097,
"text": "\nchmod mode files "
},
{
"code": null,
"e": 15192,
"s": 15116,
"text": "\nChange permission mask on remote files. The mode must be an octal number.\n"
},
{
"code": null,
"e": 15205,
"s": 15192,
"text": "\nclose [-a] "
},
{
"code": null,
"e": 15311,
"s": 15205,
"text": "\nClose idle connections. By default only with the current server, use\n-a to close all idle connections.\n"
},
{
"code": null,
"e": 15333,
"s": 15311,
"text": "\ncls [OPTS] files... "
},
{
"code": null,
"e": 15662,
"s": 15333,
"text": "\n‘cls’ tries to retrieve information about specified files or directories\nand outputs the information according to format options. The difference between\n‘ls’ and ‘cls’ is that ‘ls’ requests the server to format file listing, and\n‘cls’ formats it itself, after retrieving all the needed information.\nSee ‘help cls’ for options.\n"
},
{
"code": null,
"e": 15682,
"s": 15662,
"text": "\ncommandcmdargs... "
},
{
"code": null,
"e": 15724,
"s": 15682,
"text": "\nexecute given command ignoring aliases.\n"
},
{
"code": null,
"e": 15752,
"s": 15724,
"text": "\ndebug [-o file] level|off "
},
{
"code": null,
"e": 15844,
"s": 15752,
"text": "\nSwitch debugging to level or turn it off. Use -o to redirect\nthe debug output to a file.\n"
},
{
"code": null,
"e": 15863,
"s": 15844,
"text": "\necho [-n] string "
},
{
"code": null,
"e": 15885,
"s": 15863,
"text": "\nguess what it does.\n"
},
{
"code": null,
"e": 15913,
"s": 15885,
"text": "\neval [-f format ] args... "
},
{
"code": null,
"e": 16127,
"s": 15913,
"text": "\nwithout -f it just executes given arguments as a command. With -f, arguments\nare transformed into a new command. The format can contain plain text and\nplaceholders $0...$9 and $@, corresponding to the arguments.\n"
},
{
"code": null,
"e": 16159,
"s": 16127,
"text": "\nexit [bg] [top] [kill] [code] "
},
{
"code": null,
"e": 16379,
"s": 16159,
"text": "\nexit will exit from lftp or move to background if there are active jobs. If\nno job is active, code is passed to operating system as lftp’s\ntermination status. If code is omitted, the exit code of last\ncommand is used.\n"
},
{
"code": null,
"e": 16703,
"s": 16379,
"text": "\n‘exit bg’ forces moving to background when cmd:move-background is false.\n‘exit top’ makes top level ‘shell’ (internal lftp command executor) terminate.\n‘exit kill’ kills all numbered jobs before exiting. The options can be combined, e.g.\n‘at 08:00 -- exit top kill &’ kills all jobs and makes lftp exit at specified time.\n"
},
{
"code": null,
"e": 16708,
"s": 16703,
"text": "\nfg "
},
{
"code": null,
"e": 16728,
"s": 16708,
"text": "\nAlias for ‘wait’.\n"
},
{
"code": null,
"e": 16749,
"s": 16728,
"text": "\nfind [directory] "
},
{
"code": null,
"e": 16914,
"s": 16749,
"text": "\nList files in the directory (current directory by default) recursively.\nThis can help with servers lacking ls -R support. You can redirect output\nof this command.\n"
},
{
"code": null,
"e": 16924,
"s": 16914,
"text": "\nftpcopy "
},
{
"code": null,
"e": 16970,
"s": 16924,
"text": "\nObsolete. Use one of the following instead:\n"
},
{
"code": null,
"e": 17094,
"s": 16973,
"text": "get ftp://... -o ftp://...\nget -O ftp://... file1 file2...\nput ftp://...\nmput ftp://.../*\nmget -O ftp://... ftp://.../*\n"
},
{
"code": null,
"e": 17146,
"s": 17094,
"text": "\nget [-E] [-a] [-c] [-O base] rfile [-o lfile] ... "
},
{
"code": null,
"e": 17429,
"s": 17146,
"text": "\nRetrieve the remote file rfile and store it as the local file\nlfile. If -o is omitted, the file is stored to local file named as\nbase name of rfile. You can get multiple files by specifying multiple\ninstances of rfile (and -o lfile). Does not expand wildcards, use\nmget for that.\n"
},
{
"code": null,
"e": 17659,
"s": 17432,
"text": "-c continue, reget\n-E delete source files after successful transfer\n-a use ascii mode (binary is the default)\n-O <base> specifies base directory or URL where files should be placed\n"
},
{
"code": null,
"e": 17671,
"s": 17659,
"text": "\nExamples:\n"
},
{
"code": null,
"e": 17920,
"s": 17674,
"text": "get README\nget README -o debian.README\nget README README.mirrors\nget README -o debian.README README.mirrors -o debian.mirrors\nget README -o ftp://some.host.org/debian.README\nget README -o ftp://some.host.org/debian-dir/ (end slash is important)\n"
},
{
"code": null,
"e": 17940,
"s": 17920,
"text": "\nget1 [OPTS] rfile "
},
{
"code": null,
"e": 17975,
"s": 17940,
"text": "\nTransfer a single file. Options:\n"
},
{
"code": null,
"e": 18360,
"s": 17978,
"text": "-o <lfile> destination file name (default - basename of rfile)\n-c continue, reget\n-E delete source files after successful transfer\n-a use ascii mode (binary is the default)\n--source-region=<from-to>\n transfer specified region of source file\n--target-position=<pos>\n position in target file to write data at\n"
},
{
"code": null,
"e": 18399,
"s": 18360,
"text": "\nglob [-d] [-a] [-f] command patterns "
},
{
"code": null,
"e": 18503,
"s": 18399,
"text": "\nGlob given patterns containing metacharacters and pass result to given command.\nE.g. ‘‘glob echo *’’.\n"
},
{
"code": null,
"e": 18575,
"s": 18506,
"text": "-f plain files (default)\n-d directories\n-a all types\n"
},
{
"code": null,
"e": 18588,
"s": 18575,
"text": "\nhelp [cmd]\n"
},
{
"code": null,
"e": 18672,
"s": 18588,
"text": "\nPrint help for cmd or if no cmd was specified print a list of\navailable commands.\n"
},
{
"code": null,
"e": 18684,
"s": 18672,
"text": "\njobs [-v] "
},
{
"code": null,
"e": 18752,
"s": 18684,
"text": "\nList running jobs. -v means verbose, several -v can be specified.\n"
},
{
"code": null,
"e": 18770,
"s": 18752,
"text": "\nkill all|job_no\n"
},
{
"code": null,
"e": 18840,
"s": 18770,
"text": "\nDelete specified job with job_no or all jobs.\n(For job_no see jobs)\n"
},
{
"code": null,
"e": 18851,
"s": 18840,
"text": "\nlcd ldir\n"
},
{
"code": null,
"e": 18986,
"s": 18851,
"text": "\nChange current local directory ldir. The previous local\ndirectory is stored as ‘-’. You can do ‘lcd -’ to change the directory back.\n"
},
{
"code": null,
"e": 18993,
"s": 18986,
"text": "\nlpwd "
},
{
"code": null,
"e": 19045,
"s": 18993,
"text": "\nPrint current working directory on local machine.\n"
},
{
"code": null,
"e": 19057,
"s": 19045,
"text": "\nls params\n"
},
{
"code": null,
"e": 19237,
"s": 19057,
"text": "\nList remote files. You can redirect output of this command to file or\nvia pipe to external command. By default, ls output is cached, to see\nnew listing use\nrels or\ncache flush. "
},
{
"code": null,
"e": 19280,
"s": 19237,
"text": "\nmget [-c] [-d] [-a] [-E] [-O base] files "
},
{
"code": null,
"e": 19327,
"s": 19280,
"text": "\nGets selected files with expanded wildcards.\n"
},
{
"code": null,
"e": 19692,
"s": 19332,
"text": "-c continue, reget.\n-d create directories the same as file names and get\n the files into them instead of current directory.\n-E delete source files after successful transfer\n-a use ascii mode (binary is the default)\n-O <base> specifies base directory or URL where files should be placed\n"
},
{
"code": null,
"e": 19726,
"s": 19692,
"text": "\nmirror [OPTS] [source [target]] "
},
{
"code": null,
"e": 19945,
"s": 19726,
"text": "\nMirror specified source directory to local target directory. If target\ndirectory ends with a slash, the source base name is appended to target\ndirectory name. Source and/or target can be URLs pointing to directories.\n"
},
{
"code": null,
"e": 22293,
"s": 19950,
"text": "-c, --continue continue a mirror job if possible\n-e, --delete delete files not present at remote site\n --delete-first delete old files before transferring new ones\n --depth-first descend into subdirectories before transferring files\n-s, --allow-suid set suid/sgid bits according to remote site\n --allow-chown try to set owner and group on files\n --ascii use ascii mode transfers (implies --ignore-size)\n --ignore-time ignore time when deciding whether to download\n --ignore-size ignore size when deciding whether to download\n --only-missing download only missing files\n --only-existing download only files already existing at target\n-n, --only-newer download only newer files (-c won’t work)\n --no-empty-dirs don’t create empty directories (implies --depth-first)\n-r, --no-recursion don’t go to subdirectories\n --no-symlinks don’t create symbolic links\n-p, --no-perms don’t set file permissions\n --no-umask don’t apply umask to file modes\n-R, --reverse reverse mirror (put files)\n-L, --dereference download symbolic links as files\n-N, --newer-than=SPEC download only files newer than specified time\n --on-change=CMD execute the command if anything has been changed\n --older-than=SPEC download only files older than specified time\n --size-range=RANGE download only files with size in specified range\n-P, --parallel[=N] download N files in parallel\n --use-pget[-n=N] use pget to transfer every single file\n --loop loop until no changes found\n-i RX, --include RX include matching files\n-x RX, --exclude RX exclude matching files\n-I GP, --include-glob GP include matching files\n-X GP, --exclude-glob GP exclude matching files\n-v, --verbose[=level] verbose operation\n --log=FILE write lftp commands being executed to FILE\n --script=FILE write lftp commands to FILE, but don’t execute them\n --just-print, --dry-run same as --script=-\n --use-cache use cached directory listings\n--Remove-source-files remove files after transfer (use with caution)\n-a same as --allow-chown --allow-suid --no-umask\n"
},
{
"code": null,
"e": 22629,
"s": 22293,
"text": "\nWhen using -R, the first directory is local and the second is remote.\nIf the second directory is omitted, base name of first directory is used.\nIf both directories are omitted, current local and remote directories are used.\nIf target directory ends with a slash (except root directory) then base\nname of source directory is appended.\n"
},
{
"code": null,
"e": 22692,
"s": 22629,
"text": "\nRX is an extended regular expression, just like in egrep(1).\n"
},
{
"code": null,
"e": 22730,
"s": 22692,
"text": "\nGP is a glob pattern, e.g. ‘*.zip’.\n"
},
{
"code": null,
"e": 23026,
"s": 22730,
"text": "\nInclude and exclude options can be specified multiple times. It means that\na file or directory would be mirrored if it matches an include and does\nnot match to excludes after the include, or does not match anything\nand the first check is exclude. Directories are matched with a slash appended.\n"
},
{
"code": null,
"e": 23231,
"s": 23026,
"text": "\nNote that symbolic links are not created when uploading to remote server,\nbecause ftp protocol cannot do it. To upload files the links refer\nto, use ‘mirror -RL’ command (treat symbolic links as files).\n"
},
{
"code": null,
"e": 23447,
"s": 23231,
"text": "\nFor option --newer-than you can either specify a file or time specification\nlike that used by at(1) command, e.g. ‘now-7days’ or ‘week ago’. If you\nspecify a file, then modification time of that file will be used.\n"
},
{
"code": null,
"e": 23559,
"s": 23447,
"text": "\nVerbosity level can be selected using --verbose=level option or by several\n-v options, e.g. -vvv. Levels are:\n"
},
{
"code": null,
"e": 23712,
"s": 23562,
"text": "0 - no output (default)\n1 - print actions\n2 - +print not deleted file names (when -e is not specified)\n3 - +print directory names which are mirrored\n"
},
{
"code": null,
"e": 23887,
"s": 23712,
"text": "\n--only-newer turns off file size comparison and uploads/downloads\nonly newer files even if size is different. By default older files are transferred and replace newer ones.\n"
},
{
"code": null,
"e": 24042,
"s": 23887,
"text": "\nYou can mirror between two servers if you specify URLs instead of directories.\nFXP is used automatically for transfers between ftp servers, if possible.\n"
},
{
"code": null,
"e": 24217,
"s": 24042,
"text": "\nSome ftp servers hide dot-files by default (e.g. .htaccess), and show\nthem only when LIST command is used with -a option. In such case try to use\n‘set ftp:list-options -a’.\n"
},
{
"code": null,
"e": 24237,
"s": 24217,
"text": "\nmkdir [-p] dir(s) "
},
{
"code": null,
"e": 24309,
"s": 24237,
"text": "\nMake remote directories. If -p is used, make all components of paths.\n"
},
{
"code": null,
"e": 24334,
"s": 24309,
"text": "\nmodule module [ args ] "
},
{
"code": null,
"e": 24574,
"s": 24334,
"text": "\nLoad given module using dlopen(3) function. If module name does not contain\na slash, it is searched in directories specified by module:path variable.\nArguments are passed to module_init function. See README.modules for technical\ndetails.\n"
},
{
"code": null,
"e": 24587,
"s": 24574,
"text": "\nmore files\n"
},
{
"code": null,
"e": 24687,
"s": 24587,
"text": "\nSame as ‘cat files | more’. if PAGER is set, it is used as filter.\n(See also cat, zcat and zmore)\n"
},
{
"code": null,
"e": 24730,
"s": 24687,
"text": "\nmput [-c] [-d] [-a] [-E] [-O base] files "
},
{
"code": null,
"e": 24868,
"s": 24730,
"text": "\nUpload files with wildcard expansion. By default it uses the base name of\nlocal name as remote one. This can be changed by ‘-d’ option.\n"
},
{
"code": null,
"e": 25244,
"s": 24871,
"text": "-c continue, reput\n-d create directories the same as in file names and put the\n files into them instead of current directory\n-E delete source files after successful transfer (dangerous)\n-a use ascii mode (binary is the default)\n-O <base> specifies base directory or URL where files should be placed\n"
},
{
"code": null,
"e": 25258,
"s": 25244,
"text": "\nmrm file(s)\n"
},
{
"code": null,
"e": 25330,
"s": 25258,
"text": "\nSame as ‘glob rm’. Removes specified file(s) with wildcard expansion.\n"
},
{
"code": null,
"e": 25347,
"s": 25330,
"text": "\nmv file1 file2\n"
},
{
"code": null,
"e": 25372,
"s": 25347,
"text": "\nRename file1 to file2.\n"
},
{
"code": null,
"e": 25387,
"s": 25372,
"text": "\nnlist [args]\n"
},
{
"code": null,
"e": 25412,
"s": 25387,
"text": "\nList remote file names\n"
},
{
"code": null,
"e": 25464,
"s": 25412,
"text": "\nopen [-e cmd] [-u user[,pass]] [-p port] host|url "
},
{
"code": null,
"e": 25488,
"s": 25464,
"text": "\nSelect an ftp server.\n"
},
{
"code": null,
"e": 25519,
"s": 25488,
"text": "\npget [OPTS] rfile [-o lfile] "
},
{
"code": null,
"e": 25724,
"s": 25519,
"text": "\nGets the specified file using several connections. This can speed up\ntransfer, but loads the net and server heavily impacting other users. Use only if\nyou really have to transfer the file ASAP.\nOptions:\n"
},
{
"code": null,
"e": 25898,
"s": 25727,
"text": "-c continue transfer. Requires lfile.lftp-pget-status file.\n-n maxconn set maximum number of connections (default is taken from pget:default-n setting)\n"
},
{
"code": null,
"e": 25948,
"s": 25900,
"text": "\nput [-E] [-a] [-c] [-O base] lfile [-o rfile] "
},
{
"code": null,
"e": 26095,
"s": 25948,
"text": "\nUpload lfile with remote name rfile. If -o omitted, the base name\nof lfile is used as remote name. Does not expand wildcards, use mput for that.\n"
},
{
"code": null,
"e": 26475,
"s": 26098,
"text": "-o <rfile> specifies remote file name (default - basename of lfile)\n-c continue, reput\n it requires permission to overwrite remote files\n-E delete source files after successful transfer (dangerous)\n-a use ascii mode (binary is the default)\n-O <base> specifies base directory or URL where files should be placed\n"
},
{
"code": null,
"e": 26486,
"s": 26475,
"text": "\npwd [-p] "
},
{
"code": null,
"e": 26559,
"s": 26486,
"text": "\nPrint current remote URL. Use ‘-p’ option to show password in the URL.\n"
},
{
"code": null,
"e": 26581,
"s": 26559,
"text": "\nqueue [-n num ] cmd "
},
{
"code": null,
"e": 27053,
"s": 26581,
"text": "\nAdd the given command to queue for sequential execution. Each site has its own\nqueue. ‘-n’ adds the command before the given item in the queue. Don’t try to\nqueue ‘cd’ or ‘lcd’ commands, it may confuse lftp. Instead\ndo the cd/lcd before ‘queue’ command, and it will remember the place in which\nthe command is to be done. It is possible to queue up an already running job\nby ‘queue wait <jobno>’, but the job will continue execution even if it is not\nthe first in queue.\n"
},
{
"code": null,
"e": 27344,
"s": 27053,
"text": "\n‘queue stop’ will stop the queue, it will not execute any new commands,\nbut already running jobs will continue to run. You can use ‘queue stop’ to\ncreate an empty stopped queue. ‘queue start’ will resume queue execution.\nWhen you exit lftp, it will start all stopped queues automatically.\n"
},
{
"code": null,
"e": 27430,
"s": 27344,
"text": "\n‘queue’ with no arguments will either create a stopped queue or print queue\nstatus.\n"
},
{
"code": null,
"e": 27481,
"s": 27430,
"text": "\nqueue --delete|-d [index or wildcard expression] "
},
{
"code": null,
"e": 27589,
"s": 27481,
"text": "\nDelete one or more items from the queue. If no argument is given, the last\nentry in the queue is deleted.\n"
},
{
"code": null,
"e": 27646,
"s": 27589,
"text": "\nqueue --move|-m <index or wildcard expression> [index] "
},
{
"code": null,
"e": 27741,
"s": 27646,
"text": "\nMove the given items before the given queue index, or to the end if no\ndestination is given.\n"
},
{
"code": null,
"e": 27872,
"s": 27746,
"text": "-q Be quiet.\n-v Be verbose.\n-Q Output in a format that can be used to re-queue.\n Useful with --delete.\n"
},
{
"code": null,
"e": 27990,
"s": 27877,
"text": "> get file &\n[1] get file\n> queue wait 1\n> queue get another_file\n> cd a_directory\n> queue get yet_another_file\n"
},
{
"code": null,
"e": 28352,
"s": 27995,
"text": "queue -d 3 Delete the third item in the queue.\nqueue -m 6 4 Move the sixth item in the queue before the fourth.\nqueue -m \"get*zip\" 1 Move all commands matching \"get*zip\" to the beginning\n of the queue. (The order of the items is preserved.)\nqueue -d \"get*zip\" Delete all commands matching \"get*zip\".\n"
},
{
"code": null,
"e": 28364,
"s": 28352,
"text": "\nquote cmd\n"
},
{
"code": null,
"e": 28624,
"s": 28364,
"text": "\nFor FTP - send the command uninterpreted. Use with caution - it can lead to\nunknown remote state and thus will cause reconnect. You cannot\nbe sure that any change of remote state because of quoted command\nis solid - it can be reset by reconnect at any time.\n"
},
{
"code": null,
"e": 28743,
"s": 28624,
"text": "\nFor HTTP - specific to HTTP action. Syntax: ‘‘quote <command> [<args>]’’.\nCommand may be ‘‘set-cookie’’ or ‘‘post’’.\n"
},
{
"code": null,
"e": 28964,
"s": 28746,
"text": "open http://www.site.net\nquote set-cookie \"variable=value; othervar=othervalue\"\nset http:post-content-type application/x-www-form-urlencoded\nquote post /cgi-bin/script.cgi \"var=value&othervar=othervalue\" > local_file\n"
},
{
"code": null,
"e": 29185,
"s": 28964,
"text": "\nFor FISH - send the command uninterpreted. This can be used to execute\narbitrary commands on server. The command must not take input or print ###\nat new line beginning. If it does, the protocol will become out of sync.\n"
},
{
"code": null,
"e": 29232,
"s": 29188,
"text": "open fish://server\nquote find -name \\*.zip\n"
},
{
"code": null,
"e": 29257,
"s": 29232,
"text": "\nreget rfile [-o lfile] "
},
{
"code": null,
"e": 29277,
"s": 29257,
"text": "\nSame as ‘get -c’.\n"
},
{
"code": null,
"e": 29291,
"s": 29277,
"text": "\nrels [args]\n"
},
{
"code": null,
"e": 29330,
"s": 29291,
"text": "\nSame as ‘ls’, but ignores the cache.\n"
},
{
"code": null,
"e": 29347,
"s": 29330,
"text": "\nrenlist [args]\n"
},
{
"code": null,
"e": 29389,
"s": 29347,
"text": "\nSame as ‘nlist’, but ignores the cache.\n"
},
{
"code": null,
"e": 29435,
"s": 29389,
"text": "\nrepeat [ -c <count>] [[-d] delay] [command] "
},
{
"code": null,
"e": 29684,
"s": 29435,
"text": "\nRepeat the command. Between the commands a delay is inserted, by default 1 second.\nOption ‘-c’ limits number of repeations. Option ‘--while-ok’ breaks loop when\ncommand returns non-zero exit code; ‘--until-ok’ breaks on zero exit code.\n\nExamples:\n"
},
{
"code": null,
"e": 29734,
"s": 29687,
"text": "repeat at tomorrow -- mirror\nrepeat 1d mirror\n"
},
{
"code": null,
"e": 29759,
"s": 29734,
"text": "\nreput lfile [-o rfile] "
},
{
"code": null,
"e": 29779,
"s": 29759,
"text": "\nSame as ‘put -c’.\n"
},
{
"code": null,
"e": 29800,
"s": 29779,
"text": "\nrm [-r] [-f] files\n"
},
{
"code": null,
"e": 29991,
"s": 29800,
"text": "\nRemove remote files. Does not expand wildcards, use mrm for\nthat. -r is for recursive directory remove. Be careful, if something goes\nwrong you can lose files. -f suppress error messages.\n"
},
{
"code": null,
"e": 30006,
"s": 29991,
"text": "\nrmdir dir(s)\n"
},
{
"code": null,
"e": 30035,
"s": 30006,
"text": "\nRemove remote directories.\n"
},
{
"code": null,
"e": 30054,
"s": 30035,
"text": "\nscache [session]\n"
},
{
"code": null,
"e": 30109,
"s": 30054,
"text": "\nList cached sessions or switch to specified session.\n"
},
{
"code": null,
"e": 30127,
"s": 30109,
"text": "\nset [var [val]]\n"
},
{
"code": null,
"e": 30432,
"s": 30127,
"text": "\nSet variable to given value. If the value is omitted, unset the variable.\nVariable name has format ‘‘name/closure’’, where closure can specify\nexact application of the setting. See below for details.\nIf set is called with no variable then only altered settings are listed.\nIt can be changed by options:\n"
},
{
"code": null,
"e": 30551,
"s": 30437,
"text": "-a list all settings, including default values\n-d list only default values, not necessary current ones\n"
},
{
"code": null,
"e": 30569,
"s": 30553,
"text": "\nsite site_cmd\n"
},
{
"code": null,
"e": 30653,
"s": 30569,
"text": "\nExecute site command site_cmd and output the result.\nYou can redirect its output.\n"
},
{
"code": null,
"e": 30670,
"s": 30653,
"text": "\nsleep interval "
},
{
"code": null,
"e": 30837,
"s": 30670,
"text": "\nSleep given time interval and exit. Interval is in seconds by default, but\ncan be suffixed with ’m’, ’h’, ’d’ for minutes, hours and days respectively.\nSee also at.\n"
},
{
"code": null,
"e": 30851,
"s": 30837,
"text": "\nslot [name] "
},
{
"code": null,
"e": 31136,
"s": 30851,
"text": "\nSelect specified slot or list all slots allocated. A slot is a connection\nto a server, somewhat like a virtual console. You can create multiple slots\nconnected to different servers and switch between them. You can also use\nslot:name as a pseudo-URL evaluating to that slot location.\n"
},
{
"code": null,
"e": 31278,
"s": 31136,
"text": "\nDefault readline binding allows quick switching between slots named 0-9 using\nMeta-0 - Meta-9 keys (often you can use Alt instead of Meta).\n"
},
{
"code": null,
"e": 31311,
"s": 31278,
"text": "\nsource file\n\nsource -e command\n"
},
{
"code": null,
"e": 31395,
"s": 31311,
"text": "\nExecute commands recorded in file file or returned by specified external command.\n"
},
{
"code": null,
"e": 31437,
"s": 31398,
"text": "source ~/.lftp/rc\nsource -e echo help\n"
},
{
"code": null,
"e": 31447,
"s": 31437,
"text": "\nsuspend "
},
{
"code": null,
"e": 31572,
"s": 31447,
"text": "\nStop lftp process. Note that transfers will be also stopped until you\ncontinue the process with shell’s fg or bg commands.\n"
},
{
"code": null,
"e": 31608,
"s": 31572,
"text": "\nuser user [pass]\n\nuser URL [pass]\n"
},
{
"code": null,
"e": 31763,
"s": 31608,
"text": "\nUse specified info for remote login. If you specify an URL with user name,\nthe entered password will be cached so that future URL references can use it.\n"
},
{
"code": null,
"e": 31773,
"s": 31763,
"text": "\nversion "
},
{
"code": null,
"e": 31795,
"s": 31773,
"text": "\nPrint lftp version.\n"
},
{
"code": null,
"e": 31820,
"s": 31795,
"text": "\nwait [jobno]\n\nwait all "
},
{
"code": null,
"e": 31912,
"s": 31820,
"text": "\nWait for specified job to terminate. If jobno is omitted, wait for last\nbackgrounded job.\n"
},
{
"code": null,
"e": 31957,
"s": 31912,
"text": "\n‘wait all’ waits for all jobs termination.\n"
},
{
"code": null,
"e": 31970,
"s": 31957,
"text": "\nzcat files\n"
},
{
"code": null,
"e": 32051,
"s": 31970,
"text": "\nSame as cat, but filter each file through zcat. (See also cat,\nmore and zmore)\n"
},
{
"code": null,
"e": 32065,
"s": 32051,
"text": "\nzmore files\n"
},
{
"code": null,
"e": 32146,
"s": 32065,
"text": "\nSame as more, but filter each file through zcat. (See also cat,\nzcat and more)\n"
},
{
"code": null,
"e": 32331,
"s": 32148,
"text": "\nOn startup, lftp executes\n~/.lftprc and ~/.lftp/rc. You can place aliases\nand ‘set’ commands there. Some people prefer to see full protocol\ndebug, use ‘debug’ to turn the debug on.\n"
},
{
"code": null,
"e": 32446,
"s": 32331,
"text": "\nThere is also a system-wide startup file in\n/etc/lftp.conf. It can be in different directory, see FILES section.\n"
},
{
"code": null,
"e": 32557,
"s": 32446,
"text": "\nlftp has the following settable variables (you can also use\n‘set -a’ to see all variables and their values):\n"
},
{
"code": null,
"e": 32615,
"s": 32564,
"text": "set cmd:verify-path/hftp://* false\ncd directory &\n"
},
{
"code": null,
"e": 32705,
"s": 32618,
"text": "set sftp:connect-program rsh\nset sftp:server-program /usr/libexec/openssh/sftp-server\n"
},
{
"code": null,
"e": 33087,
"s": 32707,
"text": "\nThe closure for ‘dns:’, ‘net:’, ‘ftp:’, ‘http:’, ‘hftp:’ domain variables\nis currently just the host name as you specify it in the ‘open’ command\n(with some exceptions where closure is meaningless, e.g. dns:cache-size).\nFor some ‘cmd:’ domain variables the closure is current URL without path.\nFor other variables it is not currently used. See examples in the sample\nlftp.conf.\n"
},
{
"code": null,
"e": 33478,
"s": 33087,
"text": "\nCertain commands and settings take a time interval parameter. It has\nthe format Nx[Nx...], where N is time amount (floating point) and x is time unit: d - days,\nh - hours, m - minutes, s - seconds. Default unit is second. E.g. 5h30m or 5.5h.\nAlso the interval can be ‘infinity’, ‘inf’, ‘never’, ‘forever’ - it means\ninfinite interval. E.g. ‘sleep forever’ or ‘set dns:cache-expire never’.\n"
},
{
"code": null,
"e": 33602,
"s": 33478,
"text": "\nBoolean settings can be one of (true, on, yes, 1, +) for a True value\nor one of (false, off, no, 0, -) for a False value.\n"
},
{
"code": null,
"e": 33733,
"s": 33602,
"text": "\nInteger settings can have a suffix: k - kibi, m - mebi, g - gigi, etc.\nThey can also have a prefix: 0 - octal, 0x - hexadecimal.\n"
},
{
"code": null,
"e": 34158,
"s": 33735,
"text": "\nLftp can speed up ftp operations by sending several commands at once and\nthen checking all the responses. See ftp:sync-mode variable. Sometimes\nthis does not work, thus synchronous mode is the default. You can try\nto turn synchronous mode off and see if it works for you. It is known\nthat some network software dealing with address translation works\nincorrectly in the case of several FTP commands in one network packet.\n"
},
{
"code": null,
"e": 34635,
"s": 34158,
"text": "\nRFC959 says: ‘‘The user-process sending another command before the\ncompletion reply would be in violation of protocol; but server-FTP\nprocesses should queue any commands that arrive while a preceding\ncommand is in progress’’. Also, RFC1123 says: ‘‘Implementors MUST\nNOT assume any correspondence between READ boundaries on the control\nconnection and the Telnet EOL sequences (CR LF).’’ and ‘‘a single READ\nfrom the control connection may include more than one FTP command’’.\n"
},
{
"code": null,
"e": 34905,
"s": 34635,
"text": "\nSo it must be safe to send several commands at once, which speeds up\noperation a lot and seems to work with all Unix and VMS based ftp\nservers. Unfortunately, windows based servers often cannot handle\nseveral commands in one packet, and so cannot some broken routers.\n"
},
{
"code": null,
"e": 34924,
"s": 34915,
"text": "ftpd (1)"
},
{
"code": null,
"e": 34933,
"s": 34924,
"text": "ftpd (1)"
},
{
"code": null,
"e": 34976,
"s": 34935,
"text": "Alexander V. Lukyanov\[email protected]\n"
},
{
"code": null,
"e": 34995,
"s": 34978,
"text": "\nAdvertisements\n"
},
{
"code": null,
"e": 35030,
"s": 34995,
"text": "\n 129 Lectures \n 23 hours \n"
},
{
"code": null,
"e": 35058,
"s": 35030,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 35092,
"s": 35058,
"text": "\n 5 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 35109,
"s": 35092,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 35142,
"s": 35109,
"text": "\n 35 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 35153,
"s": 35142,
"text": " Pradeep D"
},
{
"code": null,
"e": 35188,
"s": 35153,
"text": "\n 41 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 35204,
"s": 35188,
"text": " Musab Zayadneh"
},
{
"code": null,
"e": 35237,
"s": 35204,
"text": "\n 46 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 35249,
"s": 35237,
"text": " GUHARAJANM"
},
{
"code": null,
"e": 35281,
"s": 35249,
"text": "\n 6 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 35289,
"s": 35281,
"text": " Uplatz"
},
{
"code": null,
"e": 35296,
"s": 35289,
"text": " Print"
},
{
"code": null,
"e": 35307,
"s": 35296,
"text": " Add Notes"
}
] |
Python | Box-Cox Transformation - GeeksforGeeks | 20 Jul, 2021
Imagine you are watching a horse race and like any other race, there are fast runners and slow runners. So, logically speaking, the horse which came first and the fast horses along with it will have the same difference of completion time whereas the slowest ones will have a larger difference in their completion time.
We can relate this to a very famous term in statistics called variance which refers to how much is the data varying with respect to the mean. Here in our example, there is an inconsistent variance (Heteroscedasticity) between the fast horses and the slow horses because there will be small variations for shorter completion time and vice versa.
Hence, the distribution for our data will not be a bell curve or normally distributed as there will be a longer tail on the right side. These types of distributions follow Power law or 80-20 rule where the relative change in one quantity varies as the power of another.
In the above plot, we can see power-law distribution which is having peaked for short running times because of the small variance and heavy tail due to longer running times. These power-law distributions are found in the field of physics, biology, economics, etc.
So, just think for a second that if these distributions are found in so many fields, what if we could transform it to a much comfortable distribution like normal distribution? That would make our life a lot easier. Fortunately, we have a way to transform power-law or any non-linear distribution to normal using a Box-Cox Transformation
Let us think intuitively that if we were to do this transform ourselves, how would we proceed?
It is clear from the above-shown figure that if somehow we could inflate the variability for the left-hand side of non-normal distribution i.e peak and reduce the variability at the tails. In short, trying to move the peak towards the centre then we can get a curve close to the bell-shaped curve.
Formally, A Box cox transformation is defined as a way to transform non-normal dependent variables in our data to a normal shape through which we can run a lot more tests than we could have.
Mathematics behind Box-Cox Transformation:
How can we convert our intuitive thinking into a mathematical transformation function? Logarithmic transformation is all we need. When a log transformation is applied to non-normal distribution, it tries to expand the differences between the smaller values because the slope for the logarithmic function is steeper for smaller values whereas the differences between the larger values can be reduced because, for large values, log distribution has a moderate slope. That is what we thought of doing, right?
Box-cox Transformation only cares about computing the value of which varies from – 5 to 5. A value of is said to be best if it is able to approximate the non-normal curve to a normal curve. The transformation equation is as follows:
This function requires input to be positive. Using this formula manually is a very laborious task thus many popular libraries provide this function.
Implementation:
SciPy’s stats package provides a function called boxcox for performing box-cox power transformation that takes in original non-normal data as input and returns fitted data along with the lambda value that was used to fit the non-normal distribution to normal distribution.
Following is the code for the same.
Example:
# Python3 code to show Box-cox Transformation # of non-normal data # import modulesimport numpy as npfrom scipy import stats # plotting modulesimport seaborn as snsimport matplotlib.pyplot as plt # generate non-normal data (exponential)original_data = np.random.exponential(size = 1000) # transform training data & save lambda valuefitted_data, fitted_lambda = stats.boxcox(original_data) # creating axes to draw plotsfig, ax = plt.subplots(1, 2) # plotting the original data(non-normal) and # fitted data (normal)sns.distplot(original_data, hist = False, kde = True, kde_kws = {'shade': True, 'linewidth': 2}, label = "Non-Normal", color ="green", ax = ax[0]) sns.distplot(fitted_data, hist = False, kde = True, kde_kws = {'shade': True, 'linewidth': 2}, label = "Normal", color ="green", ax = ax[1]) # adding legends to the subplotsplt.legend(loc = "upper right") # rescaling the subplotsfig.set_figheight(5)fig.set_figwidth(10) print(f"Lambda value used for Transformation: {fitted_lambda}")
Output:
We can see that the non-normal distribution was converted into a normal distribution or rather close to normal using the SciPy.stats.boxcox().
Does Box-cox always work?
The answer is NO. Box-cox does not guarantee normality because it never checks for the normality which is necessary to be foolproof that it has correctly transformed the non-normal distribution or not. It only checks for the smallest Standard deviation.
Therefore, it is absolutely necessary to always check the transformed data for normality using a probability plot.
Machine Learning
Mathematical
Python
Mathematical
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
ML | Linear Regression
Search Algorithms in AI
Python | Decision tree implementation
Reinforcement learning
Decision Tree Introduction with example
Program for Fibonacci numbers
C++ Data Types
Write a program to print all permutations of a given string
Set in C++ Standard Template Library (STL)
Program to find GCD or HCF of two numbers | [
{
"code": null,
"e": 24986,
"s": 24958,
"text": "\n20 Jul, 2021"
},
{
"code": null,
"e": 25305,
"s": 24986,
"text": "Imagine you are watching a horse race and like any other race, there are fast runners and slow runners. So, logically speaking, the horse which came first and the fast horses along with it will have the same difference of completion time whereas the slowest ones will have a larger difference in their completion time."
},
{
"code": null,
"e": 25650,
"s": 25305,
"text": "We can relate this to a very famous term in statistics called variance which refers to how much is the data varying with respect to the mean. Here in our example, there is an inconsistent variance (Heteroscedasticity) between the fast horses and the slow horses because there will be small variations for shorter completion time and vice versa."
},
{
"code": null,
"e": 25920,
"s": 25650,
"text": "Hence, the distribution for our data will not be a bell curve or normally distributed as there will be a longer tail on the right side. These types of distributions follow Power law or 80-20 rule where the relative change in one quantity varies as the power of another."
},
{
"code": null,
"e": 26184,
"s": 25920,
"text": "In the above plot, we can see power-law distribution which is having peaked for short running times because of the small variance and heavy tail due to longer running times. These power-law distributions are found in the field of physics, biology, economics, etc."
},
{
"code": null,
"e": 26521,
"s": 26184,
"text": "So, just think for a second that if these distributions are found in so many fields, what if we could transform it to a much comfortable distribution like normal distribution? That would make our life a lot easier. Fortunately, we have a way to transform power-law or any non-linear distribution to normal using a Box-Cox Transformation"
},
{
"code": null,
"e": 26616,
"s": 26521,
"text": "Let us think intuitively that if we were to do this transform ourselves, how would we proceed?"
},
{
"code": null,
"e": 26914,
"s": 26616,
"text": "It is clear from the above-shown figure that if somehow we could inflate the variability for the left-hand side of non-normal distribution i.e peak and reduce the variability at the tails. In short, trying to move the peak towards the centre then we can get a curve close to the bell-shaped curve."
},
{
"code": null,
"e": 27105,
"s": 26914,
"text": "Formally, A Box cox transformation is defined as a way to transform non-normal dependent variables in our data to a normal shape through which we can run a lot more tests than we could have."
},
{
"code": null,
"e": 27148,
"s": 27105,
"text": "Mathematics behind Box-Cox Transformation:"
},
{
"code": null,
"e": 27654,
"s": 27148,
"text": "How can we convert our intuitive thinking into a mathematical transformation function? Logarithmic transformation is all we need. When a log transformation is applied to non-normal distribution, it tries to expand the differences between the smaller values because the slope for the logarithmic function is steeper for smaller values whereas the differences between the larger values can be reduced because, for large values, log distribution has a moderate slope. That is what we thought of doing, right?"
},
{
"code": null,
"e": 27889,
"s": 27654,
"text": "Box-cox Transformation only cares about computing the value of which varies from – 5 to 5. A value of is said to be best if it is able to approximate the non-normal curve to a normal curve. The transformation equation is as follows:"
},
{
"code": null,
"e": 28038,
"s": 27889,
"text": "This function requires input to be positive. Using this formula manually is a very laborious task thus many popular libraries provide this function."
},
{
"code": null,
"e": 28054,
"s": 28038,
"text": "Implementation:"
},
{
"code": null,
"e": 28327,
"s": 28054,
"text": "SciPy’s stats package provides a function called boxcox for performing box-cox power transformation that takes in original non-normal data as input and returns fitted data along with the lambda value that was used to fit the non-normal distribution to normal distribution."
},
{
"code": null,
"e": 28363,
"s": 28327,
"text": "Following is the code for the same."
},
{
"code": null,
"e": 28372,
"s": 28363,
"text": "Example:"
},
{
"code": "# Python3 code to show Box-cox Transformation # of non-normal data # import modulesimport numpy as npfrom scipy import stats # plotting modulesimport seaborn as snsimport matplotlib.pyplot as plt # generate non-normal data (exponential)original_data = np.random.exponential(size = 1000) # transform training data & save lambda valuefitted_data, fitted_lambda = stats.boxcox(original_data) # creating axes to draw plotsfig, ax = plt.subplots(1, 2) # plotting the original data(non-normal) and # fitted data (normal)sns.distplot(original_data, hist = False, kde = True, kde_kws = {'shade': True, 'linewidth': 2}, label = \"Non-Normal\", color =\"green\", ax = ax[0]) sns.distplot(fitted_data, hist = False, kde = True, kde_kws = {'shade': True, 'linewidth': 2}, label = \"Normal\", color =\"green\", ax = ax[1]) # adding legends to the subplotsplt.legend(loc = \"upper right\") # rescaling the subplotsfig.set_figheight(5)fig.set_figwidth(10) print(f\"Lambda value used for Transformation: {fitted_lambda}\")",
"e": 29423,
"s": 28372,
"text": null
},
{
"code": null,
"e": 29431,
"s": 29423,
"text": "Output:"
},
{
"code": null,
"e": 29574,
"s": 29431,
"text": "We can see that the non-normal distribution was converted into a normal distribution or rather close to normal using the SciPy.stats.boxcox()."
},
{
"code": null,
"e": 29600,
"s": 29574,
"text": "Does Box-cox always work?"
},
{
"code": null,
"e": 29854,
"s": 29600,
"text": "The answer is NO. Box-cox does not guarantee normality because it never checks for the normality which is necessary to be foolproof that it has correctly transformed the non-normal distribution or not. It only checks for the smallest Standard deviation."
},
{
"code": null,
"e": 29969,
"s": 29854,
"text": "Therefore, it is absolutely necessary to always check the transformed data for normality using a probability plot."
},
{
"code": null,
"e": 29986,
"s": 29969,
"text": "Machine Learning"
},
{
"code": null,
"e": 29999,
"s": 29986,
"text": "Mathematical"
},
{
"code": null,
"e": 30006,
"s": 29999,
"text": "Python"
},
{
"code": null,
"e": 30019,
"s": 30006,
"text": "Mathematical"
},
{
"code": null,
"e": 30036,
"s": 30019,
"text": "Machine Learning"
},
{
"code": null,
"e": 30134,
"s": 30036,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30143,
"s": 30134,
"text": "Comments"
},
{
"code": null,
"e": 30156,
"s": 30143,
"text": "Old Comments"
},
{
"code": null,
"e": 30179,
"s": 30156,
"text": "ML | Linear Regression"
},
{
"code": null,
"e": 30203,
"s": 30179,
"text": "Search Algorithms in AI"
},
{
"code": null,
"e": 30241,
"s": 30203,
"text": "Python | Decision tree implementation"
},
{
"code": null,
"e": 30264,
"s": 30241,
"text": "Reinforcement learning"
},
{
"code": null,
"e": 30304,
"s": 30264,
"text": "Decision Tree Introduction with example"
},
{
"code": null,
"e": 30334,
"s": 30304,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 30349,
"s": 30334,
"text": "C++ Data Types"
},
{
"code": null,
"e": 30409,
"s": 30349,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 30452,
"s": 30409,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
Find HCF of two numbers without using recursion or Euclidean algorithm - GeeksforGeeks | 07 Apr, 2021
Given two integer x and y, the task is to find the HCF of the numbers without using recursion or Euclidean method.
Examples:
Input: x = 16, y = 32 Output: 16
Input: x = 12, y = 15 Output: 3
Approach: HCF of two numbers is the greatest number which can divide both the numbers. If the smaller of the two numbers can divide the larger number then the HCF is the smaller number. Else starting from (smaller / 2) to 1 check whether the current element divides both the numbers . If yes, then it is the required HCF.
Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation of the approach#include <iostream>using namespace std; // Function to return the HCF of x and yint getHCF(int x, int y){ // Minimum of the two numbers int minimum = min(x, y); // If both the numbers are divisible // by the minimum of these two then // the HCF is equal to the minimum if (x % minimum == 0 && y % minimum == 0) return minimum; // Highest number between 2 and minimum/2 // which can divide both the numbers // is the required HCF for (int i = minimum / 2; i >= 2; i--) { // If both the numbers // are divisible by i if (x % i == 0 && y % i == 0) return i; } // 1 divides every number return 1;} // Driver codeint main(){ int x = 16, y = 32; cout << getHCF(x, y); return 0;}
// Java implementation of the approachclass GFG{ // Function to return the HCF of x and ystatic int getHCF(int x, int y){ // Minimum of the two numbers int minimum = Math.min(x, y); // If both the numbers are divisible // by the minimum of these two then // the HCF is equal to the minimum if (x % minimum == 0 && y % minimum == 0) return minimum; // Highest number between 2 and minimum/2 // which can divide both the numbers // is the required HCF for (int i = minimum / 2; i >= 2; i--) { // If both the numbers // are divisible by i if (x % i == 0 && y % i == 0) return i; } // 1 divides every number return 1;} // Driver codepublic static void main(String[] args){ int x = 16, y = 32; System.out.println(getHCF(x, y));}} // This code is contributed by Code_Mech.
# Python3 implementation of the approach # Function to return the HCF of x and ydef getHCF(x, y): # Minimum of the two numbers minimum = min(x, y) # If both the numbers are divisible # by the minimum of these two then # the HCF is equal to the minimum if (x % minimum == 0 and y % minimum == 0): return minimum # Highest number between 2 and minimum/2 # which can divide both the numbers # is the required HCF for i in range(minimum // 2, 1, -1): # If both the numbers are divisible by i if (x % i == 0 and y % i == 0): return i # 1 divides every number return 1 # Driver codex, y = 16, 32print(getHCF(x, y)) # This code is contributed by mohit kumar
// C# implementation of the approachusing System; class GFG{ // Function to return the HCF of x and ystatic int getHCF(int x, int y){ // Minimum of the two numbers int minimum = Math.Min(x, y); // If both the numbers are divisible // by the minimum of these two then // the HCF is equal to the minimum if (x % minimum == 0 && y % minimum == 0) return minimum; // Highest number between 2 and minimum/2 // which can divide both the numbers // is the required HCF for (int i = minimum / 2; i >= 2; i--) { // If both the numbers // are divisible by i if (x % i == 0 && y % i == 0) return i; } // 1 divides every number return 1;} // Driver codestatic void Main(){ int x = 16, y = 32; Console.WriteLine(getHCF(x, y));}} // This code is contributed by mits
<?php// PHP implementation of the approach // Function to return the HCF of x and yfunction getHCF($x, $y){ // Minimum of the two numbers $minimum = min($x, $y); // If both the numbers are divisible // by the minimum of these two then // the HCF is equal to the minimum if ($x % $minimum == 0 && $y % $minimum == 0) return $minimum; // Highest number between 2 and minimum/2 // which can divide both the numbers // is the required HCF for ($i = $minimum / 2; $i >= 2; $i--) { // If both the numbers // are divisible by i if ($x % $i == 0 && $y % $i == 0) return $i; } // 1 divides every number return 1;} // Driver code$x = 16; $y = 32;echo(getHCF($x, $y)); // This code is contributed// by Code_Mech.?>
<script> // Javascript implementation of the approach // Function to return the HCF of x and yfunction getHCF(x, y){ // Minimum of the two numbers var minimum = Math.min(x, y); // If both the numbers are divisible // by the minimum of these two then // the HCF is equal to the minimum if (x % minimum == 0 && y % minimum == 0) return minimum; // Highest number between 2 and minimum/2 // which can divide both the numbers // is the required HCF for(var i = minimum / 2; i >= 2; i--) { // If both the numbers // are divisible by i if (x % i == 0 && y % i == 0) return i; } // 1 divides every number return 1;} // Driver codevar x = 16, y = 32; document.write(getHCF(x, y)); // This code is contributed by noob2000 </script>
16
Mithun Kumar
mohit kumar 29
Code_Mech
noob2000
GCD-LCM
HCF
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Algorithm to solve Rubik's Cube
Program to print prime numbers from 1 to N.
Program to multiply two matrices
Fizz Buzz Implementation
Complexity Analysis of Binary Search
Check if a number is Palindrome
Modular multiplicative inverse
Find Union and Intersection of two unsorted arrays
Count ways to reach the n'th stair
Find first and last digits of a number | [
{
"code": null,
"e": 24716,
"s": 24688,
"text": "\n07 Apr, 2021"
},
{
"code": null,
"e": 24831,
"s": 24716,
"text": "Given two integer x and y, the task is to find the HCF of the numbers without using recursion or Euclidean method."
},
{
"code": null,
"e": 24842,
"s": 24831,
"text": "Examples: "
},
{
"code": null,
"e": 24875,
"s": 24842,
"text": "Input: x = 16, y = 32 Output: 16"
},
{
"code": null,
"e": 24909,
"s": 24875,
"text": "Input: x = 12, y = 15 Output: 3 "
},
{
"code": null,
"e": 25231,
"s": 24909,
"text": "Approach: HCF of two numbers is the greatest number which can divide both the numbers. If the smaller of the two numbers can divide the larger number then the HCF is the smaller number. Else starting from (smaller / 2) to 1 check whether the current element divides both the numbers . If yes, then it is the required HCF."
},
{
"code": null,
"e": 25284,
"s": 25231,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25288,
"s": 25284,
"text": "C++"
},
{
"code": null,
"e": 25293,
"s": 25288,
"text": "Java"
},
{
"code": null,
"e": 25301,
"s": 25293,
"text": "Python3"
},
{
"code": null,
"e": 25304,
"s": 25301,
"text": "C#"
},
{
"code": null,
"e": 25308,
"s": 25304,
"text": "PHP"
},
{
"code": null,
"e": 25319,
"s": 25308,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <iostream>using namespace std; // Function to return the HCF of x and yint getHCF(int x, int y){ // Minimum of the two numbers int minimum = min(x, y); // If both the numbers are divisible // by the minimum of these two then // the HCF is equal to the minimum if (x % minimum == 0 && y % minimum == 0) return minimum; // Highest number between 2 and minimum/2 // which can divide both the numbers // is the required HCF for (int i = minimum / 2; i >= 2; i--) { // If both the numbers // are divisible by i if (x % i == 0 && y % i == 0) return i; } // 1 divides every number return 1;} // Driver codeint main(){ int x = 16, y = 32; cout << getHCF(x, y); return 0;}",
"e": 26122,
"s": 25319,
"text": null
},
{
"code": "// Java implementation of the approachclass GFG{ // Function to return the HCF of x and ystatic int getHCF(int x, int y){ // Minimum of the two numbers int minimum = Math.min(x, y); // If both the numbers are divisible // by the minimum of these two then // the HCF is equal to the minimum if (x % minimum == 0 && y % minimum == 0) return minimum; // Highest number between 2 and minimum/2 // which can divide both the numbers // is the required HCF for (int i = minimum / 2; i >= 2; i--) { // If both the numbers // are divisible by i if (x % i == 0 && y % i == 0) return i; } // 1 divides every number return 1;} // Driver codepublic static void main(String[] args){ int x = 16, y = 32; System.out.println(getHCF(x, y));}} // This code is contributed by Code_Mech.",
"e": 26985,
"s": 26122,
"text": null
},
{
"code": "# Python3 implementation of the approach # Function to return the HCF of x and ydef getHCF(x, y): # Minimum of the two numbers minimum = min(x, y) # If both the numbers are divisible # by the minimum of these two then # the HCF is equal to the minimum if (x % minimum == 0 and y % minimum == 0): return minimum # Highest number between 2 and minimum/2 # which can divide both the numbers # is the required HCF for i in range(minimum // 2, 1, -1): # If both the numbers are divisible by i if (x % i == 0 and y % i == 0): return i # 1 divides every number return 1 # Driver codex, y = 16, 32print(getHCF(x, y)) # This code is contributed by mohit kumar",
"e": 27717,
"s": 26985,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ // Function to return the HCF of x and ystatic int getHCF(int x, int y){ // Minimum of the two numbers int minimum = Math.Min(x, y); // If both the numbers are divisible // by the minimum of these two then // the HCF is equal to the minimum if (x % minimum == 0 && y % minimum == 0) return minimum; // Highest number between 2 and minimum/2 // which can divide both the numbers // is the required HCF for (int i = minimum / 2; i >= 2; i--) { // If both the numbers // are divisible by i if (x % i == 0 && y % i == 0) return i; } // 1 divides every number return 1;} // Driver codestatic void Main(){ int x = 16, y = 32; Console.WriteLine(getHCF(x, y));}} // This code is contributed by mits",
"e": 28565,
"s": 27717,
"text": null
},
{
"code": "<?php// PHP implementation of the approach // Function to return the HCF of x and yfunction getHCF($x, $y){ // Minimum of the two numbers $minimum = min($x, $y); // If both the numbers are divisible // by the minimum of these two then // the HCF is equal to the minimum if ($x % $minimum == 0 && $y % $minimum == 0) return $minimum; // Highest number between 2 and minimum/2 // which can divide both the numbers // is the required HCF for ($i = $minimum / 2; $i >= 2; $i--) { // If both the numbers // are divisible by i if ($x % $i == 0 && $y % $i == 0) return $i; } // 1 divides every number return 1;} // Driver code$x = 16; $y = 32;echo(getHCF($x, $y)); // This code is contributed// by Code_Mech.?>",
"e": 29373,
"s": 28565,
"text": null
},
{
"code": "<script> // Javascript implementation of the approach // Function to return the HCF of x and yfunction getHCF(x, y){ // Minimum of the two numbers var minimum = Math.min(x, y); // If both the numbers are divisible // by the minimum of these two then // the HCF is equal to the minimum if (x % minimum == 0 && y % minimum == 0) return minimum; // Highest number between 2 and minimum/2 // which can divide both the numbers // is the required HCF for(var i = minimum / 2; i >= 2; i--) { // If both the numbers // are divisible by i if (x % i == 0 && y % i == 0) return i; } // 1 divides every number return 1;} // Driver codevar x = 16, y = 32; document.write(getHCF(x, y)); // This code is contributed by noob2000 </script>",
"e": 30194,
"s": 29373,
"text": null
},
{
"code": null,
"e": 30197,
"s": 30194,
"text": "16"
},
{
"code": null,
"e": 30212,
"s": 30199,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 30227,
"s": 30212,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 30237,
"s": 30227,
"text": "Code_Mech"
},
{
"code": null,
"e": 30246,
"s": 30237,
"text": "noob2000"
},
{
"code": null,
"e": 30254,
"s": 30246,
"text": "GCD-LCM"
},
{
"code": null,
"e": 30258,
"s": 30254,
"text": "HCF"
},
{
"code": null,
"e": 30271,
"s": 30258,
"text": "Mathematical"
},
{
"code": null,
"e": 30284,
"s": 30271,
"text": "Mathematical"
},
{
"code": null,
"e": 30382,
"s": 30284,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30414,
"s": 30382,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 30458,
"s": 30414,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 30491,
"s": 30458,
"text": "Program to multiply two matrices"
},
{
"code": null,
"e": 30516,
"s": 30491,
"text": "Fizz Buzz Implementation"
},
{
"code": null,
"e": 30553,
"s": 30516,
"text": "Complexity Analysis of Binary Search"
},
{
"code": null,
"e": 30585,
"s": 30553,
"text": "Check if a number is Palindrome"
},
{
"code": null,
"e": 30616,
"s": 30585,
"text": "Modular multiplicative inverse"
},
{
"code": null,
"e": 30667,
"s": 30616,
"text": "Find Union and Intersection of two unsorted arrays"
},
{
"code": null,
"e": 30702,
"s": 30667,
"text": "Count ways to reach the n'th stair"
}
] |
AWT Panel Class | The class Panel is the simplest container class. It provides space in which an application can attach any other component, including other panels. It uses FlowLayout as default layout manager.
Following is the declaration for java.awt.Panel class:
public class Panel
extends Container
implements Accessible
Panel()
Creates a new panel using the default layout manager.
Panel(LayoutManager layout)
Creates a new panel with the specified layout manager.
void addNotify()
Creates the Panel's peer.
AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this Panel.
This class inherits methods from the following classes:
java.awt.Container
java.awt.Container
java.awt.Component
java.awt.Component
java.lang.Object
java.lang.Object
Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >
package com.tutorialspoint.gui;
import java.awt.*;
import java.awt.event.*;
public class AwtContainerDemo {
private Frame mainFrame;
private Label headerLabel;
private Label statusLabel;
private Panel controlPanel;
private Label msglabel;
public AwtContainerDemo(){
prepareGUI();
}
public static void main(String[] args){
AwtContainerDemo awtContainerDemo = new AwtContainerDemo();
awtContainerDemo.showPanelDemo();
}
private void prepareGUI(){
mainFrame = new Frame("Java AWT Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new Label();
headerLabel.setAlignment(Label.CENTER);
statusLabel = new Label();
statusLabel.setAlignment(Label.CENTER);
statusLabel.setSize(350,100);
msglabel = new Label();
msglabel.setAlignment(Label.CENTER);
msglabel.setText("Welcome to TutorialsPoint AWT Tutorial.");
controlPanel = new Panel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showPanelDemo(){
headerLabel.setText("Container in action: Panel");
Panel panel = new Panel();
panel.setBackground(Color.magenta);
panel.setLayout(new FlowLayout());
panel.add(msglabel);
controlPanel.add(panel);
mainFrame.setVisible(true);
}
}
Compile the program using command prompt. Go to D:/ > AWT and type the following command.
D:\AWT>javac com\tutorialspoint\gui\AwtContainerDemo.java
If no error comes that means compilation is successful. Run the program using following command.
D:\AWT>java com.tutorialspoint.gui.AwtContainerDemo
Verify the following output
13 Lectures
2 hours
EduOLC
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 1940,
"s": 1747,
"text": "The class Panel is the simplest container class. It provides space in which an application can attach any other component, including other panels. It uses FlowLayout as default layout manager."
},
{
"code": null,
"e": 1995,
"s": 1940,
"text": "Following is the declaration for java.awt.Panel class:"
},
{
"code": null,
"e": 2063,
"s": 1995,
"text": "public class Panel\n extends Container\n implements Accessible"
},
{
"code": null,
"e": 2071,
"s": 2063,
"text": "Panel()"
},
{
"code": null,
"e": 2125,
"s": 2071,
"text": "Creates a new panel using the default layout manager."
},
{
"code": null,
"e": 2154,
"s": 2125,
"text": "Panel(LayoutManager layout) "
},
{
"code": null,
"e": 2209,
"s": 2154,
"text": "Creates a new panel with the specified layout manager."
},
{
"code": null,
"e": 2227,
"s": 2209,
"text": "void addNotify() "
},
{
"code": null,
"e": 2253,
"s": 2227,
"text": "Creates the Panel's peer."
},
{
"code": null,
"e": 2295,
"s": 2253,
"text": "AccessibleContext getAccessibleContext() "
},
{
"code": null,
"e": 2350,
"s": 2295,
"text": "Gets the AccessibleContext associated with this Panel."
},
{
"code": null,
"e": 2406,
"s": 2350,
"text": "This class inherits methods from the following classes:"
},
{
"code": null,
"e": 2425,
"s": 2406,
"text": "java.awt.Container"
},
{
"code": null,
"e": 2444,
"s": 2425,
"text": "java.awt.Container"
},
{
"code": null,
"e": 2463,
"s": 2444,
"text": "java.awt.Component"
},
{
"code": null,
"e": 2482,
"s": 2463,
"text": "java.awt.Component"
},
{
"code": null,
"e": 2499,
"s": 2482,
"text": "java.lang.Object"
},
{
"code": null,
"e": 2516,
"s": 2499,
"text": "java.lang.Object"
},
{
"code": null,
"e": 2630,
"s": 2516,
"text": "Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >"
},
{
"code": null,
"e": 4349,
"s": 2630,
"text": "package com.tutorialspoint.gui;\n\nimport java.awt.*;\nimport java.awt.event.*;\n\npublic class AwtContainerDemo {\n private Frame mainFrame;\n private Label headerLabel;\n private Label statusLabel;\n private Panel controlPanel;\n private Label msglabel;\n\n public AwtContainerDemo(){\n prepareGUI();\n }\n\n public static void main(String[] args){\n AwtContainerDemo awtContainerDemo = new AwtContainerDemo(); \n awtContainerDemo.showPanelDemo();\n }\n\n private void prepareGUI(){\n mainFrame = new Frame(\"Java AWT Examples\");\n mainFrame.setSize(400,400);\n mainFrame.setLayout(new GridLayout(3, 1));\n mainFrame.addWindowListener(new WindowAdapter() {\n public void windowClosing(WindowEvent windowEvent){\n System.exit(0);\n } \n }); \n headerLabel = new Label();\n headerLabel.setAlignment(Label.CENTER);\n statusLabel = new Label(); \n statusLabel.setAlignment(Label.CENTER);\n statusLabel.setSize(350,100);\n \n msglabel = new Label();\n msglabel.setAlignment(Label.CENTER);\n msglabel.setText(\"Welcome to TutorialsPoint AWT Tutorial.\");\n\n controlPanel = new Panel();\n controlPanel.setLayout(new FlowLayout());\n\n mainFrame.add(headerLabel);\n mainFrame.add(controlPanel);\n mainFrame.add(statusLabel);\n mainFrame.setVisible(true); \n }\n\n private void showPanelDemo(){\n headerLabel.setText(\"Container in action: Panel\"); \n\n Panel panel = new Panel();\n panel.setBackground(Color.magenta);\n panel.setLayout(new FlowLayout()); \n panel.add(msglabel);\n\n controlPanel.add(panel);\n\n mainFrame.setVisible(true); \n }\n}"
},
{
"code": null,
"e": 4440,
"s": 4349,
"text": "Compile the program using command prompt. Go to D:/ > AWT and type the following command."
},
{
"code": null,
"e": 4498,
"s": 4440,
"text": "D:\\AWT>javac com\\tutorialspoint\\gui\\AwtContainerDemo.java"
},
{
"code": null,
"e": 4595,
"s": 4498,
"text": "If no error comes that means compilation is successful. Run the program using following command."
},
{
"code": null,
"e": 4647,
"s": 4595,
"text": "D:\\AWT>java com.tutorialspoint.gui.AwtContainerDemo"
},
{
"code": null,
"e": 4675,
"s": 4647,
"text": "Verify the following output"
},
{
"code": null,
"e": 4708,
"s": 4675,
"text": "\n 13 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4716,
"s": 4708,
"text": " EduOLC"
},
{
"code": null,
"e": 4723,
"s": 4716,
"text": " Print"
},
{
"code": null,
"e": 4734,
"s": 4723,
"text": " Add Notes"
}
] |
Arduino - Keyboard Serial | This example listens for a byte coming from the serial port. When received, the board sends a keystroke back to the computer. The sent keystroke is one higher than what is received, so if you send an "a" from the serial monitor, you will receive a "b" from the board connected to the computer. A "1" will return a "2" and so on.
Warning − When you use the Keyboard.print() command, the Leonardo, Micro or Due board takes over your computer's keyboard. To ensure you do not lose control of your computer while running a sketch with this function, set up a reliable control system before you call Keyboard.print(). This sketch is designed to only send a Keyboard command after the board has received a byte over the serial port.
You will need the following components −
1 × Arduino Leonardo, Micro, or Due board
Just connect your board to the computer using USB cable.
Open the Arduino IDE software on your computer. Coding in the Arduino language will control your circuit. Open a new sketch File by clicking New.
Notes − You must include the keypad library in your Arduino library file. Copy and paste the keypad library file inside the file with the name ‘libraries’ highlighted with yellow color.
/*
Keyboard test
For the Arduino Leonardo, Micro or Due Reads
a byte from the serial port, sends a keystroke back.
The sent keystroke is one higher than what's received, e.g. if you send a, you get b, send
A you get B, and so forth.
The circuit:
* none
*/
#include "Keyboard.h"
void setup() {
// open the serial port:
Serial.begin(9600);
// initialize control over the keyboard:
Keyboard.begin();
}
void loop() {
// check for incoming serial data:
if (Serial.available() > 0) {
// read incoming serial data:
char inChar = Serial.read();
// Type the next ASCII value from what you received:
Keyboard.write(inChar + 1);
}
}
Once programed, open your serial monitor and send a byte. The board will reply with a keystroke, that is one number higher.
The board will reply with a keystroke that is one number higher on Arduino IDE serial monitor when you send a byte.
65 Lectures
6.5 hours
Amit Rana
43 Lectures
3 hours
Amit Rana
20 Lectures
2 hours
Ashraf Said
19 Lectures
1.5 hours
Ashraf Said
11 Lectures
47 mins
Ashraf Said
9 Lectures
41 mins
Ashraf Said
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 3199,
"s": 2870,
"text": "This example listens for a byte coming from the serial port. When received, the board sends a keystroke back to the computer. The sent keystroke is one higher than what is received, so if you send an \"a\" from the serial monitor, you will receive a \"b\" from the board connected to the computer. A \"1\" will return a \"2\" and so on."
},
{
"code": null,
"e": 3597,
"s": 3199,
"text": "Warning − When you use the Keyboard.print() command, the Leonardo, Micro or Due board takes over your computer's keyboard. To ensure you do not lose control of your computer while running a sketch with this function, set up a reliable control system before you call Keyboard.print(). This sketch is designed to only send a Keyboard command after the board has received a byte over the serial port."
},
{
"code": null,
"e": 3638,
"s": 3597,
"text": "You will need the following components −"
},
{
"code": null,
"e": 3680,
"s": 3638,
"text": "1 × Arduino Leonardo, Micro, or Due board"
},
{
"code": null,
"e": 3737,
"s": 3680,
"text": "Just connect your board to the computer using USB cable."
},
{
"code": null,
"e": 3883,
"s": 3737,
"text": "Open the Arduino IDE software on your computer. Coding in the Arduino language will control your circuit. Open a new sketch File by clicking New."
},
{
"code": null,
"e": 4069,
"s": 3883,
"text": "Notes − You must include the keypad library in your Arduino library file. Copy and paste the keypad library file inside the file with the name ‘libraries’ highlighted with yellow color."
},
{
"code": null,
"e": 4767,
"s": 4069,
"text": "/*\n Keyboard test\n For the Arduino Leonardo, Micro or Due Reads\n a byte from the serial port, sends a keystroke back. \n The sent keystroke is one higher than what's received, e.g. if you send a, you get b, send\n A you get B, and so forth.\n The circuit:\n * none\n*/\n\n#include \"Keyboard.h\"\n\nvoid setup() {\n // open the serial port:\n Serial.begin(9600);\n // initialize control over the keyboard:\n Keyboard.begin();\n}\n\nvoid loop() {\n // check for incoming serial data:\n if (Serial.available() > 0) {\n // read incoming serial data:\n char inChar = Serial.read();\n // Type the next ASCII value from what you received:\n Keyboard.write(inChar + 1);\n }\n}"
},
{
"code": null,
"e": 4891,
"s": 4767,
"text": "Once programed, open your serial monitor and send a byte. The board will reply with a keystroke, that is one number higher."
},
{
"code": null,
"e": 5007,
"s": 4891,
"text": "The board will reply with a keystroke that is one number higher on Arduino IDE serial monitor when you send a byte."
},
{
"code": null,
"e": 5042,
"s": 5007,
"text": "\n 65 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 5053,
"s": 5042,
"text": " Amit Rana"
},
{
"code": null,
"e": 5086,
"s": 5053,
"text": "\n 43 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 5097,
"s": 5086,
"text": " Amit Rana"
},
{
"code": null,
"e": 5130,
"s": 5097,
"text": "\n 20 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 5143,
"s": 5130,
"text": " Ashraf Said"
},
{
"code": null,
"e": 5178,
"s": 5143,
"text": "\n 19 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5191,
"s": 5178,
"text": " Ashraf Said"
},
{
"code": null,
"e": 5223,
"s": 5191,
"text": "\n 11 Lectures \n 47 mins\n"
},
{
"code": null,
"e": 5236,
"s": 5223,
"text": " Ashraf Said"
},
{
"code": null,
"e": 5267,
"s": 5236,
"text": "\n 9 Lectures \n 41 mins\n"
},
{
"code": null,
"e": 5280,
"s": 5267,
"text": " Ashraf Said"
},
{
"code": null,
"e": 5287,
"s": 5280,
"text": " Print"
},
{
"code": null,
"e": 5298,
"s": 5287,
"text": " Add Notes"
}
] |
GATE | GATE-CS-2004 | Question 7 - GeeksforGeeks | 28 Jun, 2021
Given the following input (4322, 1334, 1471, 9679, 1989, 6171, 6173, 4199) and the hash function x mod 10, which of the following statements are true?
1. 9679, 1989, 4199 hash to the same value
2. 1471, 6171 hash to the same value
3. All elements hash to the same value
4. Each element hashes to a different value
(A) 1 only(B) 2 only(C) 1 and 2 only(D) 3 or 4Answer: (C)Explanation: The hash value for 9679, 1989, 4199 is 9 and hash value for 1471, 6171 is 1.Quiz of this Question
GATE-CS-2004
GATE-GATE-CS-2004
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-CS-2014-(Set-1) | Question 30
GATE | GATE-CS-2015 (Set 1) | Question 65
GATE | GATE CS 2010 | Question 45
GATE | GATE-CS-2015 (Set 3) | Question 65
C++ Program to count Vowels in a string using Pointer
GATE | GATE-CS-2004 | Question 3
GATE | GATE-CS-2015 (Set 1) | Question 42
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 2011 | Question 65
GATE | GATE CS 2012 | Question 65 | [
{
"code": null,
"e": 24075,
"s": 24047,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 24226,
"s": 24075,
"text": "Given the following input (4322, 1334, 1471, 9679, 1989, 6171, 6173, 4199) and the hash function x mod 10, which of the following statements are true?"
},
{
"code": null,
"e": 24403,
"s": 24226,
"text": "\n1. 9679, 1989, 4199 hash to the same value\n2. 1471, 6171 hash to the same value\n3. All elements hash to the same value\n4. Each element hashes to a different value "
},
{
"code": null,
"e": 24571,
"s": 24403,
"text": "(A) 1 only(B) 2 only(C) 1 and 2 only(D) 3 or 4Answer: (C)Explanation: The hash value for 9679, 1989, 4199 is 9 and hash value for 1471, 6171 is 1.Quiz of this Question"
},
{
"code": null,
"e": 24584,
"s": 24571,
"text": "GATE-CS-2004"
},
{
"code": null,
"e": 24602,
"s": 24584,
"text": "GATE-GATE-CS-2004"
},
{
"code": null,
"e": 24607,
"s": 24602,
"text": "GATE"
},
{
"code": null,
"e": 24705,
"s": 24607,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 24714,
"s": 24705,
"text": "Comments"
},
{
"code": null,
"e": 24727,
"s": 24714,
"text": "Old Comments"
},
{
"code": null,
"e": 24769,
"s": 24727,
"text": "GATE | GATE-CS-2014-(Set-1) | Question 30"
},
{
"code": null,
"e": 24811,
"s": 24769,
"text": "GATE | GATE-CS-2015 (Set 1) | Question 65"
},
{
"code": null,
"e": 24845,
"s": 24811,
"text": "GATE | GATE CS 2010 | Question 45"
},
{
"code": null,
"e": 24887,
"s": 24845,
"text": "GATE | GATE-CS-2015 (Set 3) | Question 65"
},
{
"code": null,
"e": 24941,
"s": 24887,
"text": "C++ Program to count Vowels in a string using Pointer"
},
{
"code": null,
"e": 24974,
"s": 24941,
"text": "GATE | GATE-CS-2004 | Question 3"
},
{
"code": null,
"e": 25016,
"s": 24974,
"text": "GATE | GATE-CS-2015 (Set 1) | Question 42"
},
{
"code": null,
"e": 25058,
"s": 25016,
"text": "GATE | GATE-CS-2014-(Set-3) | Question 65"
},
{
"code": null,
"e": 25092,
"s": 25058,
"text": "GATE | GATE CS 2011 | Question 65"
}
] |
How can we implement a scrollable JPanel in Java? | A JPanel is a subclass of JComponent (a subclass of a Container class). Therefore, JPanel is also a Container.
A JPanel is an empty area that can be used either to layout other components including other panels.
In a JPanel, we can add fields, labels, buttons, checkboxes, and images also.
The Layout Managers such as FlowLayout, GridLayout, BorderLayout and other layout managers helps us to control the sizes, positions, and alignment of the components using JPanel.
The important methods of a JPanel class are getAccessibleContext(), getUI(), updateUI() and paramString().
We can also implement a JPanel with vertical and horizontal scrolls by adding the panel object to JScrollPane.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JScrollablePanelTest extends JFrame {
public JScrollablePanelTest() {
setTitle("JScrollablePanel Test");
setLayout(new BorderLayout());
JPanel panel = createPanel();
add(BorderLayout.CENTER, new JScrollPane(panel));
setSize(375, 250);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public static JPanel createPanel() {
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(10, 4, 10, 10));
for (int i=0; i < 10; i++) {
for (int j=0; j < 4; j++) {
JLabel label = new JLabel("label " + i + ", " + j);
label.setFont(new Font("Arial", Font.PLAIN, 20));
panel.add(label);
}
}
return panel;
}
public static void main(String [] args) {
new JScrollablePanelTest();
}
} | [
{
"code": null,
"e": 1173,
"s": 1062,
"text": "A JPanel is a subclass of JComponent (a subclass of a Container class). Therefore, JPanel is also a Container."
},
{
"code": null,
"e": 1274,
"s": 1173,
"text": "A JPanel is an empty area that can be used either to layout other components including other panels."
},
{
"code": null,
"e": 1352,
"s": 1274,
"text": "In a JPanel, we can add fields, labels, buttons, checkboxes, and images also."
},
{
"code": null,
"e": 1531,
"s": 1352,
"text": "The Layout Managers such as FlowLayout, GridLayout, BorderLayout and other layout managers helps us to control the sizes, positions, and alignment of the components using JPanel."
},
{
"code": null,
"e": 1638,
"s": 1531,
"text": "The important methods of a JPanel class are getAccessibleContext(), getUI(), updateUI() and paramString()."
},
{
"code": null,
"e": 1749,
"s": 1638,
"text": "We can also implement a JPanel with vertical and horizontal scrolls by adding the panel object to JScrollPane."
},
{
"code": null,
"e": 2701,
"s": 1749,
"text": "import java.awt.*;\nimport java.awt.event.*;\nimport javax.swing.*;\npublic class JScrollablePanelTest extends JFrame {\n public JScrollablePanelTest() {\n setTitle(\"JScrollablePanel Test\");\n setLayout(new BorderLayout());\n JPanel panel = createPanel();\n add(BorderLayout.CENTER, new JScrollPane(panel));\n setSize(375, 250);\n setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n setLocationRelativeTo(null);\n setVisible(true);\n }\n public static JPanel createPanel() {\n JPanel panel = new JPanel();\n panel.setLayout(new GridLayout(10, 4, 10, 10));\n for (int i=0; i < 10; i++) {\n for (int j=0; j < 4; j++) {\n JLabel label = new JLabel(\"label \" + i + \", \" + j);\n label.setFont(new Font(\"Arial\", Font.PLAIN, 20));\n panel.add(label);\n }\n }\n return panel;\n }\n public static void main(String [] args) {\n new JScrollablePanelTest();\n }\n}"
}
] |
Lag Plots | 22 Jan, 2021
A lag plot is a special type of scatter plot in which the X-axis represents the dataset with some time units behind or ahead as compared to the Y-axis. The difference between these time units is called lag or lagged and it is represented by k.
The lag plot contains the following axes:
Vertical axis: Yi for all i
Horizontal axis: Yi-k for all i, where k is lag value
The lag plot is used to answer the following questions:
Distribution of Model: Distribution of model here means deciding what is the shape of data on the basis of the lag plot. Below are some examples of lag plot and their original plot:If the lag plot is linear, then the underlying structure is of the autoregressive model.If the lag plot is of elliptical shape, then the underlying structure represents a continuous periodic function such as sine, cosine, etc.
If the lag plot is linear, then the underlying structure is of the autoregressive model.
If the lag plot is of elliptical shape, then the underlying structure represents a continuous periodic function such as sine, cosine, etc.
Outliers: Outliers are a set of data points that represent the extreme values in the distribution
Randomness in data: The lag plot is also useful for checking whether the given dataset is random or not. If there is randomness in the data then it will be reflected in the lag plot, if there is no pattern in the lag plot.
Seasonality: If there is seasonality in the plot then, it will give a periodic lag plot.
Autocorrelation: If the lag plot gives a linear plot, then it means the autocorrelation is present in the data, whether there is positive autocorrelation or negative that depends upon the slope of the line of the dataset. If more data is concentrated on the diagonal in lag plot, it means there is a strong autocorrelation.
In this implementation, we will be NumPy and SciPy libraries, these are pre-installed in Colab but it can be installed in local environment using pip install. We will be using GOOGLE stock price data and Flicker data for this implementation.
Python3
# Import Librariesimport pandas as pdimport numpy as npimport matplotlib.pyplot as pltfrom scipy import stats as sc # Sine graph and lag plottime= np.arange(0, 10, 0.1);amplitude=np.sin(time)fig, ax = plt.subplots(1, 2, figsize=(12, 7))ax[0].plot(time, amplitude)ax[0].set_xlabel('Time')ax[0].set_ylabel('Amplitude')ax[0].axhline(y=0, color='k')amplitude_series = pd.Series(amplitude)pd.plotting.lag_plot(amplitude_series, lag= 3, ax =ax[1])plt.show() # Random and Lag Plotsample_size=1000fig, ax = plt.subplots(1, 2, figsize=(12, 7))random_series= pd.Series(np.random.normal(size=sample_size))random=random_series.reset_index(inplace=True)ax[0].plot(random['index'],random[0])pd.plotting.lag_plot(random[0],lag=1)plt.show() # Google Stock and Lag Plot (Strong Autocorrelation)google_stock_data = pd.read_csv('GOOG.csv')google_stock_data.reset_index(inplace=True)fig, ax = plt.subplots(1, 2, figsize=(12, 7))ax[0].plot(google_stock_data['Adj Close'], google_stock_data['index'])pd.plotting.lag_plot(google_stock_data['Adj Close'], lag=1,ax=ax[1])plt.show() # FLicker Data (Weak Autocorrelation)df =pd.read_csv('Flicker.DAT', header=None)df.reset_index(inplace=True)fig, ax = plt.subplots(1, 2, figsize=(12, 7))ax[0].plot(df['index'],df[0])pd.plotting.lag_plot(df[0],lag=1,ax =ax[1])plt.show()
Random Plot (No Autocorrelation)
Google Stock Data (Strong Autocorrelation)
Sine Plot (elliptic curve)
Flicker data (Moderate Autocorrelation)
NIST handbook
Data Visualization
ML-EDA
ML-plots
ML-Statistics
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Recurrent Neural Network
Support Vector Machine Algorithm
ML | Monte Carlo Tree Search (MCTS)
Markov Decision Process
DBSCAN Clustering in ML | Density based clustering
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": 28,
"s": 0,
"text": "\n22 Jan, 2021"
},
{
"code": null,
"e": 273,
"s": 28,
"text": " A lag plot is a special type of scatter plot in which the X-axis represents the dataset with some time units behind or ahead as compared to the Y-axis. The difference between these time units is called lag or lagged and it is represented by k."
},
{
"code": null,
"e": 315,
"s": 273,
"text": "The lag plot contains the following axes:"
},
{
"code": null,
"e": 343,
"s": 315,
"text": "Vertical axis: Yi for all i"
},
{
"code": null,
"e": 397,
"s": 343,
"text": "Horizontal axis: Yi-k for all i, where k is lag value"
},
{
"code": null,
"e": 453,
"s": 397,
"text": "The lag plot is used to answer the following questions:"
},
{
"code": null,
"e": 861,
"s": 453,
"text": "Distribution of Model: Distribution of model here means deciding what is the shape of data on the basis of the lag plot. Below are some examples of lag plot and their original plot:If the lag plot is linear, then the underlying structure is of the autoregressive model.If the lag plot is of elliptical shape, then the underlying structure represents a continuous periodic function such as sine, cosine, etc."
},
{
"code": null,
"e": 950,
"s": 861,
"text": "If the lag plot is linear, then the underlying structure is of the autoregressive model."
},
{
"code": null,
"e": 1089,
"s": 950,
"text": "If the lag plot is of elliptical shape, then the underlying structure represents a continuous periodic function such as sine, cosine, etc."
},
{
"code": null,
"e": 1187,
"s": 1089,
"text": "Outliers: Outliers are a set of data points that represent the extreme values in the distribution"
},
{
"code": null,
"e": 1410,
"s": 1187,
"text": "Randomness in data: The lag plot is also useful for checking whether the given dataset is random or not. If there is randomness in the data then it will be reflected in the lag plot, if there is no pattern in the lag plot."
},
{
"code": null,
"e": 1499,
"s": 1410,
"text": "Seasonality: If there is seasonality in the plot then, it will give a periodic lag plot."
},
{
"code": null,
"e": 1823,
"s": 1499,
"text": "Autocorrelation: If the lag plot gives a linear plot, then it means the autocorrelation is present in the data, whether there is positive autocorrelation or negative that depends upon the slope of the line of the dataset. If more data is concentrated on the diagonal in lag plot, it means there is a strong autocorrelation."
},
{
"code": null,
"e": 2065,
"s": 1823,
"text": "In this implementation, we will be NumPy and SciPy libraries, these are pre-installed in Colab but it can be installed in local environment using pip install. We will be using GOOGLE stock price data and Flicker data for this implementation."
},
{
"code": null,
"e": 2073,
"s": 2065,
"text": "Python3"
},
{
"code": "# Import Librariesimport pandas as pdimport numpy as npimport matplotlib.pyplot as pltfrom scipy import stats as sc # Sine graph and lag plottime= np.arange(0, 10, 0.1);amplitude=np.sin(time)fig, ax = plt.subplots(1, 2, figsize=(12, 7))ax[0].plot(time, amplitude)ax[0].set_xlabel('Time')ax[0].set_ylabel('Amplitude')ax[0].axhline(y=0, color='k')amplitude_series = pd.Series(amplitude)pd.plotting.lag_plot(amplitude_series, lag= 3, ax =ax[1])plt.show() # Random and Lag Plotsample_size=1000fig, ax = plt.subplots(1, 2, figsize=(12, 7))random_series= pd.Series(np.random.normal(size=sample_size))random=random_series.reset_index(inplace=True)ax[0].plot(random['index'],random[0])pd.plotting.lag_plot(random[0],lag=1)plt.show() # Google Stock and Lag Plot (Strong Autocorrelation)google_stock_data = pd.read_csv('GOOG.csv')google_stock_data.reset_index(inplace=True)fig, ax = plt.subplots(1, 2, figsize=(12, 7))ax[0].plot(google_stock_data['Adj Close'], google_stock_data['index'])pd.plotting.lag_plot(google_stock_data['Adj Close'], lag=1,ax=ax[1])plt.show() # FLicker Data (Weak Autocorrelation)df =pd.read_csv('Flicker.DAT', header=None)df.reset_index(inplace=True)fig, ax = plt.subplots(1, 2, figsize=(12, 7))ax[0].plot(df['index'],df[0])pd.plotting.lag_plot(df[0],lag=1,ax =ax[1])plt.show()",
"e": 3372,
"s": 2073,
"text": null
},
{
"code": null,
"e": 3405,
"s": 3372,
"text": "Random Plot (No Autocorrelation)"
},
{
"code": null,
"e": 3448,
"s": 3405,
"text": "Google Stock Data (Strong Autocorrelation)"
},
{
"code": null,
"e": 3475,
"s": 3448,
"text": "Sine Plot (elliptic curve)"
},
{
"code": null,
"e": 3515,
"s": 3475,
"text": "Flicker data (Moderate Autocorrelation)"
},
{
"code": null,
"e": 3529,
"s": 3515,
"text": "NIST handbook"
},
{
"code": null,
"e": 3548,
"s": 3529,
"text": "Data Visualization"
},
{
"code": null,
"e": 3555,
"s": 3548,
"text": "ML-EDA"
},
{
"code": null,
"e": 3564,
"s": 3555,
"text": "ML-plots"
},
{
"code": null,
"e": 3578,
"s": 3564,
"text": "ML-Statistics"
},
{
"code": null,
"e": 3595,
"s": 3578,
"text": "Machine Learning"
},
{
"code": null,
"e": 3602,
"s": 3595,
"text": "Python"
},
{
"code": null,
"e": 3619,
"s": 3602,
"text": "Machine Learning"
},
{
"code": null,
"e": 3717,
"s": 3619,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3758,
"s": 3717,
"text": "Introduction to Recurrent Neural Network"
},
{
"code": null,
"e": 3791,
"s": 3758,
"text": "Support Vector Machine Algorithm"
},
{
"code": null,
"e": 3827,
"s": 3791,
"text": "ML | Monte Carlo Tree Search (MCTS)"
},
{
"code": null,
"e": 3851,
"s": 3827,
"text": "Markov Decision Process"
},
{
"code": null,
"e": 3902,
"s": 3851,
"text": "DBSCAN Clustering in ML | Density based clustering"
},
{
"code": null,
"e": 3930,
"s": 3902,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 3980,
"s": 3930,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 4002,
"s": 3980,
"text": "Python map() function"
}
] |
Name Mangling and extern “C” in C++ | 14 Mar, 2022
C++ supports function overloading, i.e., there can be more than one function with the same name but, different parameters. How does the C++ compiler distinguish between different functions when it generates object code – it changes names by adding information about arguments. This technique of adding additional information to function names is called Name Mangling. C++ standard doesn’t specify any particular technique for name mangling, so different compilers may append different information to function names.
Consider the following example of Name Mangling, having the various declarations of function f():
CPP
// Function overloading in CPP to demonstrate// Name Mangling int f(void) { return 1; } int f(int) { return 0; } void g(void) { int i = f(), j = f(0); }
Some C++ compilers may mangle the above names to the following,
CPP
// Function overloading to demonstrate// Name Mangling int __f_v(void) { return 1; } int __f_i(int) { return 0; } void __g_v(void) { int i = __f_v(), j = __f_i(0); }
Note: C does not support function overloading, So, when we link a C code in C++, we have to make sure that name of a symbol is not changed.
In C, names may not be mangled as it doesn’t support function overloading. So how to make sure that name of a symbol is not changed when we link a C code in C++. For example, see the following C++ program that uses printf() function of C.
C++
// C Program to demonstrate it// doesn't support Name Mangling int printf(const char* format, ...); // Driver Codeint main(){ printf("GeeksforGeeks"); return 0;}
The above program generates an error.
Compiler Error:
In function `main’:f84cc4ebaf5b87bb8c6b97bc54245486.cpp:(.text+0xf): undefined reference to `printf(char const*, ...)’collect2: error: ld returned 1 exit status
Explanation: The reason for compiler error is simple, the name of printf() is changed by the C++ compiler and it doesn’t find the definition of the function with a new name.
Solution: Extern “C” in C++
When some code is put in the extern “C” block, the C++ compiler ensures that the function names are un-mangled – that the compiler emits a binary file with their names unchanged, as a C compiler would do.If we change the above program to the following, the program works fine and prints “GeeksforGeeks” on the console(as shown below).
C++14
// CPP Program to demonstrate Extern "C" extern "C" {int printf(const char* format, ...);} // Driver Codeint main(){ printf("GeeksforGeeks"); return 0;}
GeeksforGeeks
Therefore, all C style header files (stdio.h, string.h, etc) have their declarations in the extern “C” block.
CPP
#ifdef __cplusplusextern "C" {#endif// Declarations of this file#ifdef __cplusplus}#endif
Following are the main points discussed above: 1. Since C++ supports function overloading, additional information has to be added to function names (called Name mangling) to avoid conflicts in binary code. 2. Function names may not be changed in C as it doesn’t support function overloading. To avoid linking problems, C++ supports the extern “C” block. C++ compiler makes sure that names inside the extern “C” block are not changed.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
23603vaibhav2021
anshikajain26
RishabhPrabhu
Extern "C"
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n14 Mar, 2022"
},
{
"code": null,
"e": 571,
"s": 54,
"text": "C++ supports function overloading, i.e., there can be more than one function with the same name but, different parameters. How does the C++ compiler distinguish between different functions when it generates object code – it changes names by adding information about arguments. This technique of adding additional information to function names is called Name Mangling. C++ standard doesn’t specify any particular technique for name mangling, so different compilers may append different information to function names. "
},
{
"code": null,
"e": 670,
"s": 571,
"text": "Consider the following example of Name Mangling, having the various declarations of function f(): "
},
{
"code": null,
"e": 674,
"s": 670,
"text": "CPP"
},
{
"code": "// Function overloading in CPP to demonstrate// Name Mangling int f(void) { return 1; } int f(int) { return 0; } void g(void) { int i = f(), j = f(0); }",
"e": 827,
"s": 674,
"text": null
},
{
"code": null,
"e": 893,
"s": 827,
"text": "Some C++ compilers may mangle the above names to the following, "
},
{
"code": null,
"e": 897,
"s": 893,
"text": "CPP"
},
{
"code": "// Function overloading to demonstrate// Name Mangling int __f_v(void) { return 1; } int __f_i(int) { return 0; } void __g_v(void) { int i = __f_v(), j = __f_i(0); }",
"e": 1063,
"s": 897,
"text": null
},
{
"code": null,
"e": 1203,
"s": 1063,
"text": "Note: C does not support function overloading, So, when we link a C code in C++, we have to make sure that name of a symbol is not changed."
},
{
"code": null,
"e": 1444,
"s": 1203,
"text": "In C, names may not be mangled as it doesn’t support function overloading. So how to make sure that name of a symbol is not changed when we link a C code in C++. For example, see the following C++ program that uses printf() function of C. "
},
{
"code": null,
"e": 1448,
"s": 1444,
"text": "C++"
},
{
"code": "// C Program to demonstrate it// doesn't support Name Mangling int printf(const char* format, ...); // Driver Codeint main(){ printf(\"GeeksforGeeks\"); return 0;}",
"e": 1616,
"s": 1448,
"text": null
},
{
"code": null,
"e": 1654,
"s": 1616,
"text": "The above program generates an error."
},
{
"code": null,
"e": 1670,
"s": 1654,
"text": "Compiler Error:"
},
{
"code": null,
"e": 1831,
"s": 1670,
"text": "In function `main’:f84cc4ebaf5b87bb8c6b97bc54245486.cpp:(.text+0xf): undefined reference to `printf(char const*, ...)’collect2: error: ld returned 1 exit status"
},
{
"code": null,
"e": 2005,
"s": 1831,
"text": "Explanation: The reason for compiler error is simple, the name of printf() is changed by the C++ compiler and it doesn’t find the definition of the function with a new name."
},
{
"code": null,
"e": 2033,
"s": 2005,
"text": "Solution: Extern “C” in C++"
},
{
"code": null,
"e": 2369,
"s": 2033,
"text": "When some code is put in the extern “C” block, the C++ compiler ensures that the function names are un-mangled – that the compiler emits a binary file with their names unchanged, as a C compiler would do.If we change the above program to the following, the program works fine and prints “GeeksforGeeks” on the console(as shown below). "
},
{
"code": null,
"e": 2375,
"s": 2369,
"text": "C++14"
},
{
"code": "// CPP Program to demonstrate Extern \"C\" extern \"C\" {int printf(const char* format, ...);} // Driver Codeint main(){ printf(\"GeeksforGeeks\"); return 0;}",
"e": 2534,
"s": 2375,
"text": null
},
{
"code": null,
"e": 2548,
"s": 2534,
"text": "GeeksforGeeks"
},
{
"code": null,
"e": 2658,
"s": 2548,
"text": "Therefore, all C style header files (stdio.h, string.h, etc) have their declarations in the extern “C” block."
},
{
"code": null,
"e": 2662,
"s": 2658,
"text": "CPP"
},
{
"code": "#ifdef __cplusplusextern \"C\" {#endif// Declarations of this file#ifdef __cplusplus}#endif",
"e": 2752,
"s": 2662,
"text": null
},
{
"code": null,
"e": 3186,
"s": 2752,
"text": "Following are the main points discussed above: 1. Since C++ supports function overloading, additional information has to be added to function names (called Name mangling) to avoid conflicts in binary code. 2. Function names may not be changed in C as it doesn’t support function overloading. To avoid linking problems, C++ supports the extern “C” block. C++ compiler makes sure that names inside the extern “C” block are not changed."
},
{
"code": null,
"e": 3312,
"s": 3186,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 3329,
"s": 3312,
"text": "23603vaibhav2021"
},
{
"code": null,
"e": 3343,
"s": 3329,
"text": "anshikajain26"
},
{
"code": null,
"e": 3357,
"s": 3343,
"text": "RishabhPrabhu"
},
{
"code": null,
"e": 3368,
"s": 3357,
"text": "Extern \"C\""
},
{
"code": null,
"e": 3379,
"s": 3368,
"text": "C Language"
},
{
"code": null,
"e": 3383,
"s": 3379,
"text": "C++"
},
{
"code": null,
"e": 3387,
"s": 3383,
"text": "CPP"
}
] |
Matplotlib.pyplot.violinplot() in Python | 21 Apr, 2020
Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack.
The matplotlib.pyplot.violinplot() is as the name explains is used for making violin plots. Through this function, you can make a violin plot for every column of the dataset or each vector in the dataset sequence. All filled areas extend to show the entire data range with lines that are optional at the mean, the median, the maximum and the minimum.
Syntax: matplotlib.pyplot.violinplot(dataset, positions=None, vert=True, widths=0.5, showmeans=False, showextrema=True, showmedians=False, points=100, bw_method=None, *, data=None)
Parameters:
dataset: It is a required parameter that is generally an array or a sequence of vectors. This is where the data is fed to the function.positions: it is an array-like object whose default value is an array from 1 to n (ie, default = [1, 2, 3...n]). It is used to set the violins position. The limits and ticks are set automatically to match the positions.vert: This parameter accepts a boolean value. The default for this parameter is False. If set to True it creates a vertical violin plot else sets a horizontal violin plot.widths: It accepts an array-like object and has a default value of 0.5. It is used to set the maximal width of each violin and can be a scalar or a vector. If default value is used it takes about half the horizontal space.showmeans: it accepts a boolean value and has the default set as False. if set to true it toggles rendering of the meanshowextreama: It accepts a boolean value and by default is set to False. if set True, it toggles rendering of the extrema.showmedians: It accepts a boolean value and has default set to False. If set True, it toggles the rendering of the medians.points:It accepts a scalar and has a default value of 100. it is used to define the total number of points to calculate every gaussian kernel density estimations.bw_method: It is an optional parameter that accepts a string, scalar or a callable. The estimator bandwidth is calculated using this method. It can be ‘silverman’, ‘scott’, a callable or a scalar constant. In case of scalar, it is used directly as kde.factor. If it is a callable then it takes GaussianKDE instance only and returns a scalar. Scott is used in case None
dataset: It is a required parameter that is generally an array or a sequence of vectors. This is where the data is fed to the function.
positions: it is an array-like object whose default value is an array from 1 to n (ie, default = [1, 2, 3...n]). It is used to set the violins position. The limits and ticks are set automatically to match the positions.
vert: This parameter accepts a boolean value. The default for this parameter is False. If set to True it creates a vertical violin plot else sets a horizontal violin plot.
widths: It accepts an array-like object and has a default value of 0.5. It is used to set the maximal width of each violin and can be a scalar or a vector. If default value is used it takes about half the horizontal space.
showmeans: it accepts a boolean value and has the default set as False. if set to true it toggles rendering of the mean
showextreama: It accepts a boolean value and by default is set to False. if set True, it toggles rendering of the extrema.
showmedians: It accepts a boolean value and has default set to False. If set True, it toggles the rendering of the medians.
points:It accepts a scalar and has a default value of 100. it is used to define the total number of points to calculate every gaussian kernel density estimations.
bw_method: It is an optional parameter that accepts a string, scalar or a callable. The estimator bandwidth is calculated using this method. It can be ‘silverman’, ‘scott’, a callable or a scalar constant. In case of scalar, it is used directly as kde.factor. If it is a callable then it takes GaussianKDE instance only and returns a scalar. Scott is used in case None
Returns: This function returns a dictionary mapping of each component of the violin-plot to a list of respective collection instances. the dictionary returned has the following keys:
bodies: AN instance list of matplotlib.collections.PolyCollection containing the filled area of every violin.
cmeans: An instance of matplotlib.collections.LineCollection is created to identify the mean of each violin distribution
cmins: An instance of matplotlib.collections.LineCollection created to identify the bottom of each violin distribution.
cmaxes: An instance of matplotlib.collections.LineCollection created to identify the top of each violin distribution.
cbars:An instance of matplotlib.collections.LineCollection created to identify the center of each violin distribution.
cmedians:An instance of matplotlib.collections.LineCollection created to identify the mean value of each violin distribution.
Example 1:
import numpy as npimport matplotlib.pyplot as plt np.random.seed(21)data = np.random.random(111)quartile1, median, quartile3 = np.percentile(data, [ 50, 75,100], axis=0)plt.violinplot(data)plt.vlines(1, quartile1, quartile3, color='r', linestyle='--') plt.hlines(quartile1,.7,1.2)plt.hlines(quartile3,.7,1.2)
Output:
Example 2:
import matplotlib.pyplot as plt # Fixing random state for# reproducibilitynp.random.seed(15437660) # creating randomly generate # collections / datacoll_1 = np.random.normal(100, 10, 200)coll_2 = np.random.normal(80, 30, 200)coll_3 = np.random.normal(90, 20, 200)coll_4 = np.random.normal(70, 25, 200) ## combining these different # collections into a listdata_plotter = [coll_1, coll_2, coll_3, coll_4] plt.violinplot(data_plotter) plt.show()
Output:
Python-matplotlib
Python
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Apr, 2020"
},
{
"code": null,
"e": 240,
"s": 28,
"text": "Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack."
},
{
"code": null,
"e": 591,
"s": 240,
"text": "The matplotlib.pyplot.violinplot() is as the name explains is used for making violin plots. Through this function, you can make a violin plot for every column of the dataset or each vector in the dataset sequence. All filled areas extend to show the entire data range with lines that are optional at the mean, the median, the maximum and the minimum."
},
{
"code": null,
"e": 772,
"s": 591,
"text": "Syntax: matplotlib.pyplot.violinplot(dataset, positions=None, vert=True, widths=0.5, showmeans=False, showextrema=True, showmedians=False, points=100, bw_method=None, *, data=None)"
},
{
"code": null,
"e": 784,
"s": 772,
"text": "Parameters:"
},
{
"code": null,
"e": 2426,
"s": 784,
"text": "dataset: It is a required parameter that is generally an array or a sequence of vectors. This is where the data is fed to the function.positions: it is an array-like object whose default value is an array from 1 to n (ie, default = [1, 2, 3...n]). It is used to set the violins position. The limits and ticks are set automatically to match the positions.vert: This parameter accepts a boolean value. The default for this parameter is False. If set to True it creates a vertical violin plot else sets a horizontal violin plot.widths: It accepts an array-like object and has a default value of 0.5. It is used to set the maximal width of each violin and can be a scalar or a vector. If default value is used it takes about half the horizontal space.showmeans: it accepts a boolean value and has the default set as False. if set to true it toggles rendering of the meanshowextreama: It accepts a boolean value and by default is set to False. if set True, it toggles rendering of the extrema.showmedians: It accepts a boolean value and has default set to False. If set True, it toggles the rendering of the medians.points:It accepts a scalar and has a default value of 100. it is used to define the total number of points to calculate every gaussian kernel density estimations.bw_method: It is an optional parameter that accepts a string, scalar or a callable. The estimator bandwidth is calculated using this method. It can be ‘silverman’, ‘scott’, a callable or a scalar constant. In case of scalar, it is used directly as kde.factor. If it is a callable then it takes GaussianKDE instance only and returns a scalar. Scott is used in case None"
},
{
"code": null,
"e": 2562,
"s": 2426,
"text": "dataset: It is a required parameter that is generally an array or a sequence of vectors. This is where the data is fed to the function."
},
{
"code": null,
"e": 2782,
"s": 2562,
"text": "positions: it is an array-like object whose default value is an array from 1 to n (ie, default = [1, 2, 3...n]). It is used to set the violins position. The limits and ticks are set automatically to match the positions."
},
{
"code": null,
"e": 2954,
"s": 2782,
"text": "vert: This parameter accepts a boolean value. The default for this parameter is False. If set to True it creates a vertical violin plot else sets a horizontal violin plot."
},
{
"code": null,
"e": 3177,
"s": 2954,
"text": "widths: It accepts an array-like object and has a default value of 0.5. It is used to set the maximal width of each violin and can be a scalar or a vector. If default value is used it takes about half the horizontal space."
},
{
"code": null,
"e": 3297,
"s": 3177,
"text": "showmeans: it accepts a boolean value and has the default set as False. if set to true it toggles rendering of the mean"
},
{
"code": null,
"e": 3420,
"s": 3297,
"text": "showextreama: It accepts a boolean value and by default is set to False. if set True, it toggles rendering of the extrema."
},
{
"code": null,
"e": 3544,
"s": 3420,
"text": "showmedians: It accepts a boolean value and has default set to False. If set True, it toggles the rendering of the medians."
},
{
"code": null,
"e": 3707,
"s": 3544,
"text": "points:It accepts a scalar and has a default value of 100. it is used to define the total number of points to calculate every gaussian kernel density estimations."
},
{
"code": null,
"e": 4076,
"s": 3707,
"text": "bw_method: It is an optional parameter that accepts a string, scalar or a callable. The estimator bandwidth is calculated using this method. It can be ‘silverman’, ‘scott’, a callable or a scalar constant. In case of scalar, it is used directly as kde.factor. If it is a callable then it takes GaussianKDE instance only and returns a scalar. Scott is used in case None"
},
{
"code": null,
"e": 4259,
"s": 4076,
"text": "Returns: This function returns a dictionary mapping of each component of the violin-plot to a list of respective collection instances. the dictionary returned has the following keys:"
},
{
"code": null,
"e": 4369,
"s": 4259,
"text": "bodies: AN instance list of matplotlib.collections.PolyCollection containing the filled area of every violin."
},
{
"code": null,
"e": 4490,
"s": 4369,
"text": "cmeans: An instance of matplotlib.collections.LineCollection is created to identify the mean of each violin distribution"
},
{
"code": null,
"e": 4610,
"s": 4490,
"text": "cmins: An instance of matplotlib.collections.LineCollection created to identify the bottom of each violin distribution."
},
{
"code": null,
"e": 4728,
"s": 4610,
"text": "cmaxes: An instance of matplotlib.collections.LineCollection created to identify the top of each violin distribution."
},
{
"code": null,
"e": 4847,
"s": 4728,
"text": "cbars:An instance of matplotlib.collections.LineCollection created to identify the center of each violin distribution."
},
{
"code": null,
"e": 4973,
"s": 4847,
"text": "cmedians:An instance of matplotlib.collections.LineCollection created to identify the mean value of each violin distribution."
},
{
"code": null,
"e": 4984,
"s": 4973,
"text": "Example 1:"
},
{
"code": "import numpy as npimport matplotlib.pyplot as plt np.random.seed(21)data = np.random.random(111)quartile1, median, quartile3 = np.percentile(data, [ 50, 75,100], axis=0)plt.violinplot(data)plt.vlines(1, quartile1, quartile3, color='r', linestyle='--') plt.hlines(quartile1,.7,1.2)plt.hlines(quartile3,.7,1.2) ",
"e": 5416,
"s": 4984,
"text": null
},
{
"code": null,
"e": 5424,
"s": 5416,
"text": "Output:"
},
{
"code": null,
"e": 5435,
"s": 5424,
"text": "Example 2:"
},
{
"code": "import matplotlib.pyplot as plt # Fixing random state for# reproducibilitynp.random.seed(15437660) # creating randomly generate # collections / datacoll_1 = np.random.normal(100, 10, 200)coll_2 = np.random.normal(80, 30, 200)coll_3 = np.random.normal(90, 20, 200)coll_4 = np.random.normal(70, 25, 200) ## combining these different # collections into a listdata_plotter = [coll_1, coll_2, coll_3, coll_4] plt.violinplot(data_plotter) plt.show()",
"e": 5900,
"s": 5435,
"text": null
},
{
"code": null,
"e": 5908,
"s": 5900,
"text": "Output:"
},
{
"code": null,
"e": 5926,
"s": 5908,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 5933,
"s": 5926,
"text": "Python"
},
{
"code": null,
"e": 5949,
"s": 5933,
"text": "Write From Home"
}
] |
Job Sequencing Problem | Set 3 (Using TreeSet in JAVA) | 11 Dec, 2018
Given an array of jobs where every job has a deadline and associated profit (if the job is finished before the deadline). It is also given that every job takes a single unit of time, so the minimum possible deadline for any job is 1. How to maximize total profit if only one job can be scheduled at a time.
Examples:
Input : Four Jobs with following deadlines and profits
JobID Deadline Profit
a 4 20
b 1 10
c 1 40
d 1 30
Output : Following is maximum profit sequence of jobs
c, a
Input : Five Jobs with following deadlines and profits
JobID Deadline Profit
a 2 100
b 1 19
c 2 27
d 1 25
e 3 15
Output : Following is maximum profit sequence of jobs
c, a, e
Below is the step by step algorithm to solve the problem using TreeSet in Java:
Sort all the jobs according to their respective profits in decreasing order.Create a TreeSet and insert all the integers from 0 to n-1.Traverse the array of jobs and for ith jobSearch for a time slot ‘x’ in the TreeSet with maximum value which is less than the deadline of the ith job.If any value exists then include that job in the answer and remove ‘x’ from the TreeSetElse check for the remaining jobs.
Sort all the jobs according to their respective profits in decreasing order.
Create a TreeSet and insert all the integers from 0 to n-1.
Traverse the array of jobs and for ith jobSearch for a time slot ‘x’ in the TreeSet with maximum value which is less than the deadline of the ith job.If any value exists then include that job in the answer and remove ‘x’ from the TreeSetElse check for the remaining jobs.
Search for a time slot ‘x’ in the TreeSet with maximum value which is less than the deadline of the ith job.
If any value exists then include that job in the answer and remove ‘x’ from the TreeSet
Else check for the remaining jobs.
Below is the implementation of the above algorithm:
import java.io.*;import java.util.*; public class Solution { // Job class public static class Job { char id; int deadline; int profit; // Constructor Job(char id, int deadline, int profit) { this.id = id; this.deadline = deadline; this.profit = profit; } } public static class Sorted implements Comparator { // Function to implement comparator public int compare(Object o1, Object o2) { Job j1 = (Job)o1; Job j2 = (Job)o2; if (j1.profit != j2.profit) return j2.profit - j1.profit; else return j2.deadline - j1.deadline; } } // Function to print job scheduling public static void printJobScheduling(Job jobs[], int n) { // Creating object of Sorted class Sorted sorter = new Sorted(); Arrays.sort(jobs, sorter); // Creating TreeSet Object TreeSet<Integer> ts = new TreeSet<>(); for (int i = 0; i < n; i++) ts.add(i); for (int i = 0; i < n; i++) { Integer x = ts.floor(jobs[i].deadline - 1); if (x != null) { System.out.print(jobs[i].id + " "); ts.remove(x); } } } // Driver Code public static void main(String[] args) { int n = 5; Job[] jobs = new Job[n]; jobs[0] = new Job('a', 2, 100); jobs[1] = new Job('b', 1, 19); jobs[2] = new Job('c', 2, 27); jobs[3] = new Job('d', 1, 25); jobs[4] = new Job('e', 3, 15); printJobScheduling(jobs, n); } // Contributed by Dipesh Jain (dipesh_jain)}
Time Complexity: O(N*log(N))Auxiliary Space: O(N)
Java-Collections
Java-Set-Programs
java-treeset
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Strings in Java
Java Programming Examples
Abstraction in Java
HashSet in Java | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n11 Dec, 2018"
},
{
"code": null,
"e": 359,
"s": 52,
"text": "Given an array of jobs where every job has a deadline and associated profit (if the job is finished before the deadline). It is also given that every job takes a single unit of time, so the minimum possible deadline for any job is 1. How to maximize total profit if only one job can be scheduled at a time."
},
{
"code": null,
"e": 369,
"s": 359,
"text": "Examples:"
},
{
"code": null,
"e": 647,
"s": 369,
"text": "Input : Four Jobs with following deadlines and profits\n JobID Deadline Profit\n a 4 20 \n b 1 10\n c 1 40 \n d 1 30\nOutput : Following is maximum profit sequence of jobs\n c, a \n"
},
{
"code": null,
"e": 958,
"s": 647,
"text": "Input : Five Jobs with following deadlines and profits\n JobID Deadline Profit\n a 2 100\n b 1 19\n c 2 27\n d 1 25\n e 3 15\nOutput : Following is maximum profit sequence of jobs\n c, a, e\n"
},
{
"code": null,
"e": 1038,
"s": 958,
"text": "Below is the step by step algorithm to solve the problem using TreeSet in Java:"
},
{
"code": null,
"e": 1445,
"s": 1038,
"text": "Sort all the jobs according to their respective profits in decreasing order.Create a TreeSet and insert all the integers from 0 to n-1.Traverse the array of jobs and for ith jobSearch for a time slot ‘x’ in the TreeSet with maximum value which is less than the deadline of the ith job.If any value exists then include that job in the answer and remove ‘x’ from the TreeSetElse check for the remaining jobs."
},
{
"code": null,
"e": 1522,
"s": 1445,
"text": "Sort all the jobs according to their respective profits in decreasing order."
},
{
"code": null,
"e": 1582,
"s": 1522,
"text": "Create a TreeSet and insert all the integers from 0 to n-1."
},
{
"code": null,
"e": 1854,
"s": 1582,
"text": "Traverse the array of jobs and for ith jobSearch for a time slot ‘x’ in the TreeSet with maximum value which is less than the deadline of the ith job.If any value exists then include that job in the answer and remove ‘x’ from the TreeSetElse check for the remaining jobs."
},
{
"code": null,
"e": 1963,
"s": 1854,
"text": "Search for a time slot ‘x’ in the TreeSet with maximum value which is less than the deadline of the ith job."
},
{
"code": null,
"e": 2051,
"s": 1963,
"text": "If any value exists then include that job in the answer and remove ‘x’ from the TreeSet"
},
{
"code": null,
"e": 2086,
"s": 2051,
"text": "Else check for the remaining jobs."
},
{
"code": null,
"e": 2138,
"s": 2086,
"text": "Below is the implementation of the above algorithm:"
},
{
"code": "import java.io.*;import java.util.*; public class Solution { // Job class public static class Job { char id; int deadline; int profit; // Constructor Job(char id, int deadline, int profit) { this.id = id; this.deadline = deadline; this.profit = profit; } } public static class Sorted implements Comparator { // Function to implement comparator public int compare(Object o1, Object o2) { Job j1 = (Job)o1; Job j2 = (Job)o2; if (j1.profit != j2.profit) return j2.profit - j1.profit; else return j2.deadline - j1.deadline; } } // Function to print job scheduling public static void printJobScheduling(Job jobs[], int n) { // Creating object of Sorted class Sorted sorter = new Sorted(); Arrays.sort(jobs, sorter); // Creating TreeSet Object TreeSet<Integer> ts = new TreeSet<>(); for (int i = 0; i < n; i++) ts.add(i); for (int i = 0; i < n; i++) { Integer x = ts.floor(jobs[i].deadline - 1); if (x != null) { System.out.print(jobs[i].id + \" \"); ts.remove(x); } } } // Driver Code public static void main(String[] args) { int n = 5; Job[] jobs = new Job[n]; jobs[0] = new Job('a', 2, 100); jobs[1] = new Job('b', 1, 19); jobs[2] = new Job('c', 2, 27); jobs[3] = new Job('d', 1, 25); jobs[4] = new Job('e', 3, 15); printJobScheduling(jobs, n); } // Contributed by Dipesh Jain (dipesh_jain)}",
"e": 3898,
"s": 2138,
"text": null
},
{
"code": null,
"e": 3948,
"s": 3898,
"text": "Time Complexity: O(N*log(N))Auxiliary Space: O(N)"
},
{
"code": null,
"e": 3965,
"s": 3948,
"text": "Java-Collections"
},
{
"code": null,
"e": 3983,
"s": 3965,
"text": "Java-Set-Programs"
},
{
"code": null,
"e": 3996,
"s": 3983,
"text": "java-treeset"
},
{
"code": null,
"e": 4001,
"s": 3996,
"text": "Java"
},
{
"code": null,
"e": 4006,
"s": 4001,
"text": "Java"
},
{
"code": null,
"e": 4023,
"s": 4006,
"text": "Java-Collections"
},
{
"code": null,
"e": 4121,
"s": 4023,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4136,
"s": 4121,
"text": "Stream In Java"
},
{
"code": null,
"e": 4157,
"s": 4136,
"text": "Introduction to Java"
},
{
"code": null,
"e": 4178,
"s": 4157,
"text": "Constructors in Java"
},
{
"code": null,
"e": 4197,
"s": 4178,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 4214,
"s": 4197,
"text": "Generics in Java"
},
{
"code": null,
"e": 4244,
"s": 4214,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 4260,
"s": 4244,
"text": "Strings in Java"
},
{
"code": null,
"e": 4286,
"s": 4260,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 4306,
"s": 4286,
"text": "Abstraction in Java"
}
] |
How to Make a Chatbot in Python using Chatterbot Module? | 14 Dec, 2020
A ChatBot is basically a computer program that conducts conversation between a user and a computer through auditory or textual methods. It works as a real-world conversational partner.
ChatterBot is a library in python which generates a response to user input. It used a number of machine learning algorithms to generates a variety of responses. It makes it easier for the user to make a chatbot using the chatterbot library for more accurate responses. The design of the chatbot is such that it allows the bot to interact in many languages which include Spanish, German, English, and a lot of regional languages. The Machine Learning Algorithms also make it easier for the bot to improve on its own with the user input.
We’ll take a step-by-step approach and eventually make our own chatbot.
Let’s begin the journey of our own chatbot in the shortest way possible:-
Step 1. Install the Chatterbot and chatterbot_corpus module :
The first and foremost step is to install the chatterbot library. You also need to install the chatterbot_corpus library. Basically, Corpus means a bunch of words. The Chatterbot corpus contains a bunch of data that is included in the chatterbot module. The corpus is used by bots to train themselves.
Run the following pip commands on the terminal for installation:
pip install chatterbot
pip install chatterbot_corpus
Step 2. Import the modules
we have to import two classes: ChatBot from chatterbot and ListTrainer from chatterbot.trainers.
ListTrainer: Allows a chatbot to be trained using a list of strings where the list represents a conversation.
Python3
from chatterbot import ChatBotfrom chatterbot.trainers import ListTrainer
Step 3. Name our Chatbot:
Now, we will give any name to the chatbot of our choice. Just create a Chatbot object. Here the chatbot is maned as “Bot” just to make it understandable.
Python3
bot = ChatBot('Bot')
Step 4. Use of Logic Adapter:
The Logical Adapter regulates the logic behind the chatterbot that is, it picks responses for any input provided to it. This parameter contains a list of all the logical operators. When more than one logical adapter is put to use, the chatbot will calculate the confidence level, and the response with the highest calculated confidence will be returned as output.
Here we have used two logical adapters:
BestMatch: The BestMatchAdapter helps it to choose the best match from the list of responses already provided.TimeLogicAdapter: The TimeLogicAdapter identifies statements in which a question about the current time is asked. If a matching question is detected, then a response containing the current time is returned.
BestMatch: The BestMatchAdapter helps it to choose the best match from the list of responses already provided.
TimeLogicAdapter: The TimeLogicAdapter identifies statements in which a question about the current time is asked. If a matching question is detected, then a response containing the current time is returned.
Python3
chatbot = ChatBot( 'JARVIS', logic_adapters=[ 'chatterbot.logic.BestMatch', 'chatterbot.logic.TimeLogicAdapter'],)
Step 5. Training, Communication, and Testing :
For the training process, you will need to pass in a list of statements where the order of each statement is based on its placement in a given conversation. We have to train the bot to improve its performance for this we need to call the train() method by passing a list of sentences. Training ensures that the bot has enough knowledge to get started with specific responses to specific inputs. After training, let’s check its communication skills. And the last step is to do testing
You have to execute the following commands now:
Python3
from chatterbot.trainers import ListTrainer trainer = ListTrainer(bot) trainer.train([ 'Hi', 'Hello', 'I need roadmap for Competitive Programming', 'Just create an account on GFG and start', 'I have a query.', 'Please elaborate, your concern', 'How long it will take to become expert in Coding ?', 'It usually depends on the amount of practice.', 'Ok Thanks', 'No Problem! Have a Good Day!'])
Now let, test the chatbot:
Python3
response = bot.get_response("Good morning!") print(response)
Output:
Hello
Below is the full implementation:
Python3
from chatterbot import ChatBotfrom chatterbot.trainers import ListTrainerfrom chatterbot.trainers import ListTrainer bot = ChatBot('Bot') trainer = ListTrainer(bot) trainer.train([ 'Hi', 'Hello', 'I need roadmap for Competitive Programming', 'Just create an account on GFG and start', 'I have a query.', 'Please elaborate, your concern', 'How long it will take to become expert in Coding ?', 'It usually depends on the amount of practice.', 'Ok Thanks', 'No Problem! Have a Good Day!']) while True: request=input('you :') if request == 'OK' or request == 'ok': print('Bot: bye') break else: response=bot.get_response(request) print('Bot:', response)
Output:
python-modules
Python-projects
python-utility
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": "\n14 Dec, 2020"
},
{
"code": null,
"e": 213,
"s": 28,
"text": "A ChatBot is basically a computer program that conducts conversation between a user and a computer through auditory or textual methods. It works as a real-world conversational partner."
},
{
"code": null,
"e": 749,
"s": 213,
"text": "ChatterBot is a library in python which generates a response to user input. It used a number of machine learning algorithms to generates a variety of responses. It makes it easier for the user to make a chatbot using the chatterbot library for more accurate responses. The design of the chatbot is such that it allows the bot to interact in many languages which include Spanish, German, English, and a lot of regional languages. The Machine Learning Algorithms also make it easier for the bot to improve on its own with the user input."
},
{
"code": null,
"e": 822,
"s": 749,
"text": "We’ll take a step-by-step approach and eventually make our own chatbot. "
},
{
"code": null,
"e": 897,
"s": 822,
"text": " Let’s begin the journey of our own chatbot in the shortest way possible:-"
},
{
"code": null,
"e": 959,
"s": 897,
"text": "Step 1. Install the Chatterbot and chatterbot_corpus module :"
},
{
"code": null,
"e": 1263,
"s": 959,
"text": "The first and foremost step is to install the chatterbot library. You also need to install the chatterbot_corpus library. Basically, Corpus means a bunch of words. The Chatterbot corpus contains a bunch of data that is included in the chatterbot module. The corpus is used by bots to train themselves. "
},
{
"code": null,
"e": 1328,
"s": 1263,
"text": "Run the following pip commands on the terminal for installation:"
},
{
"code": null,
"e": 1381,
"s": 1328,
"text": "pip install chatterbot\npip install chatterbot_corpus"
},
{
"code": null,
"e": 1408,
"s": 1381,
"text": "Step 2. Import the modules"
},
{
"code": null,
"e": 1505,
"s": 1408,
"text": "we have to import two classes: ChatBot from chatterbot and ListTrainer from chatterbot.trainers."
},
{
"code": null,
"e": 1615,
"s": 1505,
"text": "ListTrainer: Allows a chatbot to be trained using a list of strings where the list represents a conversation."
},
{
"code": null,
"e": 1623,
"s": 1615,
"text": "Python3"
},
{
"code": "from chatterbot import ChatBotfrom chatterbot.trainers import ListTrainer",
"e": 1697,
"s": 1623,
"text": null
},
{
"code": null,
"e": 1723,
"s": 1697,
"text": "Step 3. Name our Chatbot:"
},
{
"code": null,
"e": 1877,
"s": 1723,
"text": "Now, we will give any name to the chatbot of our choice. Just create a Chatbot object. Here the chatbot is maned as “Bot” just to make it understandable."
},
{
"code": null,
"e": 1885,
"s": 1877,
"text": "Python3"
},
{
"code": "bot = ChatBot('Bot')",
"e": 1906,
"s": 1885,
"text": null
},
{
"code": null,
"e": 1936,
"s": 1906,
"text": "Step 4. Use of Logic Adapter:"
},
{
"code": null,
"e": 2302,
"s": 1936,
"text": " The Logical Adapter regulates the logic behind the chatterbot that is, it picks responses for any input provided to it. This parameter contains a list of all the logical operators. When more than one logical adapter is put to use, the chatbot will calculate the confidence level, and the response with the highest calculated confidence will be returned as output. "
},
{
"code": null,
"e": 2344,
"s": 2302,
"text": "Here we have used two logical adapters: "
},
{
"code": null,
"e": 2661,
"s": 2344,
"text": "BestMatch: The BestMatchAdapter helps it to choose the best match from the list of responses already provided.TimeLogicAdapter: The TimeLogicAdapter identifies statements in which a question about the current time is asked. If a matching question is detected, then a response containing the current time is returned."
},
{
"code": null,
"e": 2772,
"s": 2661,
"text": "BestMatch: The BestMatchAdapter helps it to choose the best match from the list of responses already provided."
},
{
"code": null,
"e": 2979,
"s": 2772,
"text": "TimeLogicAdapter: The TimeLogicAdapter identifies statements in which a question about the current time is asked. If a matching question is detected, then a response containing the current time is returned."
},
{
"code": null,
"e": 2987,
"s": 2979,
"text": "Python3"
},
{
"code": "chatbot = ChatBot( 'JARVIS', logic_adapters=[ 'chatterbot.logic.BestMatch', 'chatterbot.logic.TimeLogicAdapter'],) ",
"e": 3126,
"s": 2987,
"text": null
},
{
"code": null,
"e": 3173,
"s": 3126,
"text": "Step 5. Training, Communication, and Testing :"
},
{
"code": null,
"e": 3658,
"s": 3173,
"text": "For the training process, you will need to pass in a list of statements where the order of each statement is based on its placement in a given conversation. We have to train the bot to improve its performance for this we need to call the train() method by passing a list of sentences. Training ensures that the bot has enough knowledge to get started with specific responses to specific inputs. After training, let’s check its communication skills. And the last step is to do testing "
},
{
"code": null,
"e": 3706,
"s": 3658,
"text": "You have to execute the following commands now:"
},
{
"code": null,
"e": 3714,
"s": 3706,
"text": "Python3"
},
{
"code": "from chatterbot.trainers import ListTrainer trainer = ListTrainer(bot) trainer.train([ 'Hi', 'Hello', 'I need roadmap for Competitive Programming', 'Just create an account on GFG and start', 'I have a query.', 'Please elaborate, your concern', 'How long it will take to become expert in Coding ?', 'It usually depends on the amount of practice.', 'Ok Thanks', 'No Problem! Have a Good Day!'])",
"e": 4139,
"s": 3714,
"text": null
},
{
"code": null,
"e": 4166,
"s": 4139,
"text": "Now let, test the chatbot:"
},
{
"code": null,
"e": 4174,
"s": 4166,
"text": "Python3"
},
{
"code": "response = bot.get_response(\"Good morning!\") print(response)",
"e": 4236,
"s": 4174,
"text": null
},
{
"code": null,
"e": 4244,
"s": 4236,
"text": "Output:"
},
{
"code": null,
"e": 4250,
"s": 4244,
"text": "Hello"
},
{
"code": null,
"e": 4284,
"s": 4250,
"text": "Below is the full implementation:"
},
{
"code": null,
"e": 4292,
"s": 4284,
"text": "Python3"
},
{
"code": "from chatterbot import ChatBotfrom chatterbot.trainers import ListTrainerfrom chatterbot.trainers import ListTrainer bot = ChatBot('Bot') trainer = ListTrainer(bot) trainer.train([ 'Hi', 'Hello', 'I need roadmap for Competitive Programming', 'Just create an account on GFG and start', 'I have a query.', 'Please elaborate, your concern', 'How long it will take to become expert in Coding ?', 'It usually depends on the amount of practice.', 'Ok Thanks', 'No Problem! Have a Good Day!']) while True: request=input('you :') if request == 'OK' or request == 'ok': print('Bot: bye') break else: response=bot.get_response(request) print('Bot:', response)",
"e": 5013,
"s": 4292,
"text": null
},
{
"code": null,
"e": 5021,
"s": 5013,
"text": "Output:"
},
{
"code": null,
"e": 5036,
"s": 5021,
"text": "python-modules"
},
{
"code": null,
"e": 5052,
"s": 5036,
"text": "Python-projects"
},
{
"code": null,
"e": 5067,
"s": 5052,
"text": "python-utility"
},
{
"code": null,
"e": 5074,
"s": 5067,
"text": "Python"
},
{
"code": null,
"e": 5172,
"s": 5074,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5204,
"s": 5172,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 5231,
"s": 5204,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 5252,
"s": 5231,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 5275,
"s": 5252,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 5331,
"s": 5275,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 5362,
"s": 5331,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 5404,
"s": 5362,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 5446,
"s": 5404,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 5485,
"s": 5446,
"text": "Python | Get unique values from a list"
}
] |
JavaScript String - concat() Method | This method adds two or more strings and returns a new single string.
Its syntax is as follows −
string.concat(string2, string3[, ..., stringN]);
string2...stringN − These are the strings to be concatenated.
Returns a single concatenated string.
Try the following example.
<html>
<head>
<title>JavaScript String concat() Method</title>
</head>
<body>
<script type = "text/javascript">
var str1 = new String( "This is string one" );
var str2 = new String( "This is string two" );
var str3 = str1.concat( str2 );
document.write("Concatenated String :" + str3);
</script>
</body>
</html>
Concatenated String :This is string oneThis is string two. | [
{
"code": null,
"e": 2670,
"s": 2600,
"text": "This method adds two or more strings and returns a new single string."
},
{
"code": null,
"e": 2697,
"s": 2670,
"text": "Its syntax is as follows −"
},
{
"code": null,
"e": 2747,
"s": 2697,
"text": "string.concat(string2, string3[, ..., stringN]);\n"
},
{
"code": null,
"e": 2809,
"s": 2747,
"text": "string2...stringN − These are the strings to be concatenated."
},
{
"code": null,
"e": 2847,
"s": 2809,
"text": "Returns a single concatenated string."
},
{
"code": null,
"e": 2874,
"s": 2847,
"text": "Try the following example."
},
{
"code": null,
"e": 3272,
"s": 2874,
"text": "<html>\n <head>\n <title>JavaScript String concat() Method</title>\n </head>\n \n <body> \n <script type = \"text/javascript\">\n var str1 = new String( \"This is string one\" );\n var str2 = new String( \"This is string two\" );\n var str3 = str1.concat( str2 ); \n document.write(\"Concatenated String :\" + str3); \n </script> \n </body>\n</html>"
}
] |
jQuery Jcrop Plugin | 31 Jul, 2020
In this article, we will learn how to crop an image using PHP and jQuery Jcrop plugin.
Note: Please download the jQuery Jcrop plugin and include the required files in the head section of your HTML code.
<link href=”jquery.Jcrop.min.css” rel=”stylesheet” type=”text/css”/><script src=”jquery.min.js”></script><script src=”jquery.Jcrop.min.js”></script>
Example: The following HTML code demonstrates the Jcrop plugin by taking an image file and giving a “Crop Image” button to crop the image and show the output cropped image in another HTML “div”.
<!DOCTYPE html><html> <head> <!-- All the required libraries to crop the image--> <link rel="stylesheet" href="jquery.Jcrop.min.css" type="text/css" /> <script src="jquery.min.js"></script> <script src="jquery.Jcrop.min.js"></script> <style> body { width: 500px; height: 380px; font-family: Arial, Sans-serif; } .btnSubmitClass { background-color: #696969; padding: 5px 30px; border: #696969 1px solid; border-radius: 4px; color: #FFFFFF; margin-top: 10px; } input#cropBtnID { padding: 5px 25px 5px 25px; background: #D3D3D3; border: #98b398 1px solid; color: #FFF; visibility: hidden; } #outputImage { margin-top: 40px; } </style></head> <body> <h2> How to crop image using jQuery and PHP </h2> <div> <img src="gfg2.jpg" id="cropImageID" class="img" /><br /> </div> <div id="btn"> <input type='button' id="cropBtnID" value='Crop Image'> </div> <div> <img src="#" id="outputImage" style="display:none;"> </div> <script type="text/javascript"> $(document).ready(function () { var size; $('#cropImageID').Jcrop({ /* Some settings for basic configuration*/ allowSelect: true, allowMove: true, allowResize: true, fixedSupport: true, aspectRatio: 1, onSelect: function (c) { size = { x: c.x, y: c.y, w: c.w, h: c.h }; $("#cropBtnID").css( "visibility", "visible"); }//end onSelect });//end Jcrop method $("#cropBtnID").click(function () { var img = $("#cropImageID").attr('src'); $("#outputImage").show(); $("#outputImage").attr('src', 'image-features.php?x = ' + size.x + ' & y=' + size.y + ' & w=' + size.w + '&h=' + size.h + '&img=' + img); }); });//end document ready fn </script></body> </html>
PHP code: The following PHP code implements the “image-features.php” file that is used in the above HTML code for image and color creation. The PHP function used for creating a new image is imagecreatefromjpeg() method. A new true color image is created using PHP imagecreatetruecolor() method. Other PHP functions used are imagecopyresampled() and imagejpeg().
<?php // Create a new image from a file$newImage = imagecreatefromjpeg($_GET['img']); // Create a new true color image$newTruecolorImage = imagecreatetruecolor( $_GET['w'], $_GET['h']); // Copy a portion from one image to anotherimagecopyresampled($newTruecolorImage, $newImage, 0, 0, $_GET['x'], $_GET['y'], $_GET['w'], $_GET['h'], $_GET['w'], $_GET['h']); header('Content-type: image/jpeg'); // Display image to browser as outputimagejpeg($newTruecolorImage); exit;?>
Output:
jQuery-Plugin
CSS
HTML
JQuery
PHP
Web Technologies
Web technologies Questions
HTML
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n31 Jul, 2020"
},
{
"code": null,
"e": 115,
"s": 28,
"text": "In this article, we will learn how to crop an image using PHP and jQuery Jcrop plugin."
},
{
"code": null,
"e": 231,
"s": 115,
"text": "Note: Please download the jQuery Jcrop plugin and include the required files in the head section of your HTML code."
},
{
"code": null,
"e": 380,
"s": 231,
"text": "<link href=”jquery.Jcrop.min.css” rel=”stylesheet” type=”text/css”/><script src=”jquery.min.js”></script><script src=”jquery.Jcrop.min.js”></script>"
},
{
"code": null,
"e": 575,
"s": 380,
"text": "Example: The following HTML code demonstrates the Jcrop plugin by taking an image file and giving a “Crop Image” button to crop the image and show the output cropped image in another HTML “div”."
},
{
"code": "<!DOCTYPE html><html> <head> <!-- All the required libraries to crop the image--> <link rel=\"stylesheet\" href=\"jquery.Jcrop.min.css\" type=\"text/css\" /> <script src=\"jquery.min.js\"></script> <script src=\"jquery.Jcrop.min.js\"></script> <style> body { width: 500px; height: 380px; font-family: Arial, Sans-serif; } .btnSubmitClass { background-color: #696969; padding: 5px 30px; border: #696969 1px solid; border-radius: 4px; color: #FFFFFF; margin-top: 10px; } input#cropBtnID { padding: 5px 25px 5px 25px; background: #D3D3D3; border: #98b398 1px solid; color: #FFF; visibility: hidden; } #outputImage { margin-top: 40px; } </style></head> <body> <h2> How to crop image using jQuery and PHP </h2> <div> <img src=\"gfg2.jpg\" id=\"cropImageID\" class=\"img\" /><br /> </div> <div id=\"btn\"> <input type='button' id=\"cropBtnID\" value='Crop Image'> </div> <div> <img src=\"#\" id=\"outputImage\" style=\"display:none;\"> </div> <script type=\"text/javascript\"> $(document).ready(function () { var size; $('#cropImageID').Jcrop({ /* Some settings for basic configuration*/ allowSelect: true, allowMove: true, allowResize: true, fixedSupport: true, aspectRatio: 1, onSelect: function (c) { size = { x: c.x, y: c.y, w: c.w, h: c.h }; $(\"#cropBtnID\").css( \"visibility\", \"visible\"); }//end onSelect });//end Jcrop method $(\"#cropBtnID\").click(function () { var img = $(\"#cropImageID\").attr('src'); $(\"#outputImage\").show(); $(\"#outputImage\").attr('src', 'image-features.php?x = ' + size.x + ' & y=' + size.y + ' & w=' + size.w + '&h=' + size.h + '&img=' + img); }); });//end document ready fn </script></body> </html>",
"e": 3003,
"s": 575,
"text": null
},
{
"code": null,
"e": 3365,
"s": 3003,
"text": "PHP code: The following PHP code implements the “image-features.php” file that is used in the above HTML code for image and color creation. The PHP function used for creating a new image is imagecreatefromjpeg() method. A new true color image is created using PHP imagecreatetruecolor() method. Other PHP functions used are imagecopyresampled() and imagejpeg()."
},
{
"code": "<?php // Create a new image from a file$newImage = imagecreatefromjpeg($_GET['img']); // Create a new true color image$newTruecolorImage = imagecreatetruecolor( $_GET['w'], $_GET['h']); // Copy a portion from one image to anotherimagecopyresampled($newTruecolorImage, $newImage, 0, 0, $_GET['x'], $_GET['y'], $_GET['w'], $_GET['h'], $_GET['w'], $_GET['h']); header('Content-type: image/jpeg'); // Display image to browser as outputimagejpeg($newTruecolorImage); exit;?>",
"e": 3881,
"s": 3365,
"text": null
},
{
"code": null,
"e": 3889,
"s": 3881,
"text": "Output:"
},
{
"code": null,
"e": 3903,
"s": 3889,
"text": "jQuery-Plugin"
},
{
"code": null,
"e": 3907,
"s": 3903,
"text": "CSS"
},
{
"code": null,
"e": 3912,
"s": 3907,
"text": "HTML"
},
{
"code": null,
"e": 3919,
"s": 3912,
"text": "JQuery"
},
{
"code": null,
"e": 3923,
"s": 3919,
"text": "PHP"
},
{
"code": null,
"e": 3940,
"s": 3923,
"text": "Web Technologies"
},
{
"code": null,
"e": 3967,
"s": 3940,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 3972,
"s": 3967,
"text": "HTML"
},
{
"code": null,
"e": 3976,
"s": 3972,
"text": "PHP"
}
] |
How to add a row to R dataframe ? | 21 Apr, 2021
In this article, we will see how to add rows to a DataFrame in R Programing Language. To do this we will use rbind() function. This function in R Language is used to combine specified Vector, Matrix or Data Frame by rows.
Syntax:
rbind(dataframe 1, dataframe 2)
Example 1 :
R
# creating a data frame with some datadf9 = data.frame(id=c(1,2,3), name=c("karthik","bhagiradh","kethan")) print("Original data frame") # printing the data frame print(df9) # declaring a row of values in # data.frame() functiondf8 = data.frame(4,"shyam") # adding names to the row valuesnames(df8)=c("id","name") # passing the original data frame and new # data frame into the rbind() functiondf7=rbind(df9,df8) print("data frame after adding a new row")print(df7)
Output :
Example 2 :
Python3
# creating a data frame with some datadf = data.frame(id=c(1,2,3), name=c("maruti suzuki","tata","ford")) print("Original data frame")print(df) # declaring a row of values in# data.frame() functiondf1 = data.frame(4,"volkswagen") # adding names to the row valuesnames(df1)=c("id","name") # passing the original data frame and # new data frame into the rbind() function df2=rbind(df,df1) print("data frame after adding a new row")print(df2)
Output :
Example 3:
R
# creating a data frame with some datadf3 = data.frame(id=c(1,2,3), name=c("Asus","HP","Acer")) print("Original data frame")print(df3) # declaring a row of values in # data.frame() functiondf4 = data.frame(4,"Dell") # adding names to the row valuesnames(df4)=c("id","name") # passing the original data frame and # new data frame into the rbind() functiondf5=rbind(df3,df4) print("data frame after adding a new row")print(df5)
Output :
Picked
R DataFrame-Programs
R-DataFrame
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Apr, 2021"
},
{
"code": null,
"e": 250,
"s": 28,
"text": "In this article, we will see how to add rows to a DataFrame in R Programing Language. To do this we will use rbind() function. This function in R Language is used to combine specified Vector, Matrix or Data Frame by rows."
},
{
"code": null,
"e": 258,
"s": 250,
"text": "Syntax:"
},
{
"code": null,
"e": 290,
"s": 258,
"text": "rbind(dataframe 1, dataframe 2)"
},
{
"code": null,
"e": 302,
"s": 290,
"text": "Example 1 :"
},
{
"code": null,
"e": 304,
"s": 302,
"text": "R"
},
{
"code": "# creating a data frame with some datadf9 = data.frame(id=c(1,2,3), name=c(\"karthik\",\"bhagiradh\",\"kethan\")) print(\"Original data frame\") # printing the data frame print(df9) # declaring a row of values in # data.frame() functiondf8 = data.frame(4,\"shyam\") # adding names to the row valuesnames(df8)=c(\"id\",\"name\") # passing the original data frame and new # data frame into the rbind() functiondf7=rbind(df9,df8) print(\"data frame after adding a new row\")print(df7)",
"e": 797,
"s": 304,
"text": null
},
{
"code": null,
"e": 806,
"s": 797,
"text": "Output :"
},
{
"code": null,
"e": 818,
"s": 806,
"text": "Example 2 :"
},
{
"code": null,
"e": 826,
"s": 818,
"text": "Python3"
},
{
"code": "# creating a data frame with some datadf = data.frame(id=c(1,2,3), name=c(\"maruti suzuki\",\"tata\",\"ford\")) print(\"Original data frame\")print(df) # declaring a row of values in# data.frame() functiondf1 = data.frame(4,\"volkswagen\") # adding names to the row valuesnames(df1)=c(\"id\",\"name\") # passing the original data frame and # new data frame into the rbind() function df2=rbind(df,df1) print(\"data frame after adding a new row\")print(df2)",
"e": 1290,
"s": 826,
"text": null
},
{
"code": null,
"e": 1299,
"s": 1290,
"text": "Output :"
},
{
"code": null,
"e": 1310,
"s": 1299,
"text": "Example 3:"
},
{
"code": null,
"e": 1312,
"s": 1310,
"text": "R"
},
{
"code": "# creating a data frame with some datadf3 = data.frame(id=c(1,2,3), name=c(\"Asus\",\"HP\",\"Acer\")) print(\"Original data frame\")print(df3) # declaring a row of values in # data.frame() functiondf4 = data.frame(4,\"Dell\") # adding names to the row valuesnames(df4)=c(\"id\",\"name\") # passing the original data frame and # new data frame into the rbind() functiondf5=rbind(df3,df4) print(\"data frame after adding a new row\")print(df5) ",
"e": 1764,
"s": 1312,
"text": null
},
{
"code": null,
"e": 1773,
"s": 1764,
"text": "Output :"
},
{
"code": null,
"e": 1780,
"s": 1773,
"text": "Picked"
},
{
"code": null,
"e": 1801,
"s": 1780,
"text": "R DataFrame-Programs"
},
{
"code": null,
"e": 1813,
"s": 1801,
"text": "R-DataFrame"
},
{
"code": null,
"e": 1824,
"s": 1813,
"text": "R Language"
},
{
"code": null,
"e": 1835,
"s": 1824,
"text": "R Programs"
}
] |
script command in Linux with Examples | 17 Apr, 2019
script command in Linux is used to make typescript or record all the terminal activities. After executing the script command it starts recording everything printed on the screen including the inputs and outputs until exit. By default, all the terminal information is saved in the file typescript , if no argument is given. script is mostly used when we want to capture the output of a command or a set of command while installing a program or the logs generated on the terminal while compiling an opensource codes, etc. script command uses two files i.e. one for the terminal output and other for the timing information.
Syntax:
script [options] [file]
Example 1: To start a typescript without any argument. If no filename is given as argument, script will automatically create a file namely typescript in the home directory to save the recorded information.
Input:
In order to stop the typescript, we just need to execute exit command and script will stop the capturing process. Since there’s no filename given as argument, the script will automatically create a file namely typescript in the home directory to save the recorded information.
Output:
Example 2: To start the typrscript, run any random command and save it in a text file, let’s say geeksforgeeks.txt.
Input:
Output:
The output produced above is the content of the file geeksforgeeks.txt, created by script command.
Options:
-a, –append: This option is used when we want to append the output, retaining the prior content of the file. The multiple contents get separated by adding a line that states the date and time of the script started.Example:Input:Output:
Example:
Input:
Output:
-c, –command: This option is used when we want to run a particular command rather than interactive shell and get terminal information in the file given as argument or typescript by default. The script will automatically exit after successful execution.Example: To get the typescript of cal command.Input:Output:
Example: To get the typescript of cal command.
Input:
Output:
-e, –return: This option simply return exit code of the child process.
-f, –flush: This option is used to run flush output after each write. It’s useful for telecooperation
–force: This option allows default output file i.e. typescript to be hard or symbolic link.Example: To capture terminal activity in a file let’s say gfg2 that is stored in /home/sc.Input:Output:
Example: To capture terminal activity in a file let’s say gfg2 that is stored in /home/sc.
Input:
Output:
-q, –quiet: This option does not display the notification stating that the script has started and quietly execute and exit the script command.
-t, –timing[=]: This option allows user to capture the terminal activity step by step and appears like a video when the recorded file is executed with the help of scriptreplay command.Example: To capture terminal activity in a manual file, geeksforgeeks1.Input:This option contains two data fields. The first field indicates how much time elapsed since the previous output. The second field indicates how many characters were output this time. Now let’s check the output created using another command i.e. scriptreplay as follow:scriptreplay --timing=time_log geeksforgeeks1Output:
Example: To capture terminal activity in a manual file, geeksforgeeks1.
Input:
This option contains two data fields. The first field indicates how much time elapsed since the previous output. The second field indicates how many characters were output this time. Now let’s check the output created using another command i.e. scriptreplay as follow:
scriptreplay --timing=time_log geeksforgeeks1
Output:
-V, –version: Output version information and exit.
-h, –help: Display this help and exit
linux-command
Linux-misc-commands
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
tar command in Linux with examples
'crontab' in Linux with Examples
Tail command in Linux with examples
UDP Server-Client implementation in C
Docker - COPY Instruction
scp command in Linux with Examples
diff command in Linux with examples
Cat command in Linux with examples
echo command in Linux with Examples
touch command in Linux with Examples | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n17 Apr, 2019"
},
{
"code": null,
"e": 675,
"s": 54,
"text": "script command in Linux is used to make typescript or record all the terminal activities. After executing the script command it starts recording everything printed on the screen including the inputs and outputs until exit. By default, all the terminal information is saved in the file typescript , if no argument is given. script is mostly used when we want to capture the output of a command or a set of command while installing a program or the logs generated on the terminal while compiling an opensource codes, etc. script command uses two files i.e. one for the terminal output and other for the timing information."
},
{
"code": null,
"e": 683,
"s": 675,
"text": "Syntax:"
},
{
"code": null,
"e": 707,
"s": 683,
"text": "script [options] [file]"
},
{
"code": null,
"e": 913,
"s": 707,
"text": "Example 1: To start a typescript without any argument. If no filename is given as argument, script will automatically create a file namely typescript in the home directory to save the recorded information."
},
{
"code": null,
"e": 920,
"s": 913,
"text": "Input:"
},
{
"code": null,
"e": 1197,
"s": 920,
"text": "In order to stop the typescript, we just need to execute exit command and script will stop the capturing process. Since there’s no filename given as argument, the script will automatically create a file namely typescript in the home directory to save the recorded information."
},
{
"code": null,
"e": 1205,
"s": 1197,
"text": "Output:"
},
{
"code": null,
"e": 1321,
"s": 1205,
"text": "Example 2: To start the typrscript, run any random command and save it in a text file, let’s say geeksforgeeks.txt."
},
{
"code": null,
"e": 1328,
"s": 1321,
"text": "Input:"
},
{
"code": null,
"e": 1336,
"s": 1328,
"text": "Output:"
},
{
"code": null,
"e": 1435,
"s": 1336,
"text": "The output produced above is the content of the file geeksforgeeks.txt, created by script command."
},
{
"code": null,
"e": 1444,
"s": 1435,
"text": "Options:"
},
{
"code": null,
"e": 1680,
"s": 1444,
"text": "-a, –append: This option is used when we want to append the output, retaining the prior content of the file. The multiple contents get separated by adding a line that states the date and time of the script started.Example:Input:Output:"
},
{
"code": null,
"e": 1689,
"s": 1680,
"text": "Example:"
},
{
"code": null,
"e": 1696,
"s": 1689,
"text": "Input:"
},
{
"code": null,
"e": 1704,
"s": 1696,
"text": "Output:"
},
{
"code": null,
"e": 2016,
"s": 1704,
"text": "-c, –command: This option is used when we want to run a particular command rather than interactive shell and get terminal information in the file given as argument or typescript by default. The script will automatically exit after successful execution.Example: To get the typescript of cal command.Input:Output:"
},
{
"code": null,
"e": 2063,
"s": 2016,
"text": "Example: To get the typescript of cal command."
},
{
"code": null,
"e": 2070,
"s": 2063,
"text": "Input:"
},
{
"code": null,
"e": 2078,
"s": 2070,
"text": "Output:"
},
{
"code": null,
"e": 2149,
"s": 2078,
"text": "-e, –return: This option simply return exit code of the child process."
},
{
"code": null,
"e": 2251,
"s": 2149,
"text": "-f, –flush: This option is used to run flush output after each write. It’s useful for telecooperation"
},
{
"code": null,
"e": 2446,
"s": 2251,
"text": "–force: This option allows default output file i.e. typescript to be hard or symbolic link.Example: To capture terminal activity in a file let’s say gfg2 that is stored in /home/sc.Input:Output:"
},
{
"code": null,
"e": 2537,
"s": 2446,
"text": "Example: To capture terminal activity in a file let’s say gfg2 that is stored in /home/sc."
},
{
"code": null,
"e": 2544,
"s": 2537,
"text": "Input:"
},
{
"code": null,
"e": 2552,
"s": 2544,
"text": "Output:"
},
{
"code": null,
"e": 2695,
"s": 2552,
"text": "-q, –quiet: This option does not display the notification stating that the script has started and quietly execute and exit the script command."
},
{
"code": null,
"e": 3277,
"s": 2695,
"text": "-t, –timing[=]: This option allows user to capture the terminal activity step by step and appears like a video when the recorded file is executed with the help of scriptreplay command.Example: To capture terminal activity in a manual file, geeksforgeeks1.Input:This option contains two data fields. The first field indicates how much time elapsed since the previous output. The second field indicates how many characters were output this time. Now let’s check the output created using another command i.e. scriptreplay as follow:scriptreplay --timing=time_log geeksforgeeks1Output:"
},
{
"code": null,
"e": 3349,
"s": 3277,
"text": "Example: To capture terminal activity in a manual file, geeksforgeeks1."
},
{
"code": null,
"e": 3356,
"s": 3349,
"text": "Input:"
},
{
"code": null,
"e": 3625,
"s": 3356,
"text": "This option contains two data fields. The first field indicates how much time elapsed since the previous output. The second field indicates how many characters were output this time. Now let’s check the output created using another command i.e. scriptreplay as follow:"
},
{
"code": null,
"e": 3671,
"s": 3625,
"text": "scriptreplay --timing=time_log geeksforgeeks1"
},
{
"code": null,
"e": 3679,
"s": 3671,
"text": "Output:"
},
{
"code": null,
"e": 3730,
"s": 3679,
"text": "-V, –version: Output version information and exit."
},
{
"code": null,
"e": 3768,
"s": 3730,
"text": "-h, –help: Display this help and exit"
},
{
"code": null,
"e": 3782,
"s": 3768,
"text": "linux-command"
},
{
"code": null,
"e": 3802,
"s": 3782,
"text": "Linux-misc-commands"
},
{
"code": null,
"e": 3813,
"s": 3802,
"text": "Linux-Unix"
},
{
"code": null,
"e": 3911,
"s": 3813,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3946,
"s": 3911,
"text": "tar command in Linux with examples"
},
{
"code": null,
"e": 3979,
"s": 3946,
"text": "'crontab' in Linux with Examples"
},
{
"code": null,
"e": 4015,
"s": 3979,
"text": "Tail command in Linux with examples"
},
{
"code": null,
"e": 4053,
"s": 4015,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 4079,
"s": 4053,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 4114,
"s": 4079,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 4150,
"s": 4114,
"text": "diff command in Linux with examples"
},
{
"code": null,
"e": 4185,
"s": 4150,
"text": "Cat command in Linux with examples"
},
{
"code": null,
"e": 4221,
"s": 4185,
"text": "echo command in Linux with Examples"
}
] |
How to traverse a STL map in reverse direction? | 01 Dec, 2018
Map stores the elements in sorted order of keys. Now if we want to traverse it in reverse order we will use reverse_iterator of map.
Syntax:
map::reverse_iterator iterator_name;
Reverse Iterator of map moves in backward direction on increment. So, we will point the reverse_iterator to the last element of map and then keep on incrementing it until it reaches the first element. To do this we will use 2 member functions of std::map i.e.1. rbegin() : It returns the reverse_iterator pointing to last element of map.2. rend() : It returns the reverse_iterator pointing to first element of map.
Now for traversing in reverse order we will iterate over the range b/w rbegin() & rend() using reverse_iterator.Reverse Iteration in map:Example:
Input: (10, "geeks"), (20, "practice"), (5, " contribute")
Output : (20, "practice"), (10, "geeks"), (5, " contribute")
// C++ program makes a map to iterate// elements in reverse order.#include <bits/stdc++.h>using namespace std; int main(){ // Creating & Initializing a map of String & Ints map<int, string> mymap; // Inserting the elements one by one mymap.insert(make_pair(10, "geeks")); mymap.insert(make_pair(20, "practice")); mymap.insert(make_pair(5, "contribute")); // Create a map reverse iterator map<int, string>::reverse_iterator it; // rbegin() returns to the last value of map for (it = mymap.rbegin(); it != mymap.rend(); it++) { cout << "(" << it->first << ", " << it->second << ")" << endl; } return 0;}
(20, practice)
(10, geeks)
(5, contribute)
We can also use auto to avoid remembering complex syntax.
// C++ program makes a map to iterate// elements in reverse order with simpler// syntax#include <bits/stdc++.h>using namespace std; int main(){ // Creating & Initializing a map of String & Ints map<int, string> mymap; // Inserting the elements one by one mymap.insert(make_pair(10, "geeks")); mymap.insert(make_pair(20, "practice")); mymap.insert(make_pair(5, "contribute")); // rbegin() returns to the last value of map for (auto it = mymap.rbegin(); it != mymap.rend(); it++) { cout << "(" << it->first << ", " << it->second << ")" << endl; } return 0;}
(20, practice)
(10, geeks)
(5, contribute)
Reverse Iteration in multimap:Multimap is similar to map with an addition that multiple elements can have same keys. Rather than each element being unique, the key value and mapped value pair has to be unique in this case.
Example:
Input : (10, "geeks"), (20, "practice"), (5, "contribute"),
(20, "van"), (20, "watch"), (5, "joker")
Output: (20, "watch"), (20, "van"), (20, "practice"),
(10, "geeks"), (5, "joker"), (5, "contribute")
// C++ program makes a multimap to store// elements in descending order.#include <bits/stdc++.h>using namespace std; int main(){ // Creating & Initializing a multimap // of Ints & String multimap<int, std::string> mymap; // Inserting the elements one by one mymap.insert(make_pair(10, "geeks")); mymap.insert(make_pair(20, "practice")); mymap.insert(make_pair(5, "contribute")); // Duplicates allowed mymap.insert(make_pair(20, "van")); mymap.insert(make_pair(20, "watch")); mymap.insert(make_pair(5, "joker")); for (auto it = mymap.rbegin(); it != mymap.rend(); it++) { cout << "(" << it->first << ", " << it->second << ")" << endl; } return 0;}
(20, watch)
(20, van)
(20, practice)
(10, geeks)
(5, joker)
(5, contribute)
cpp-map
cpp-multimap
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting a vector in C++
Polymorphism in C++
Friend class and function in C++
Pair in C++ Standard Template Library (STL)
std::string class in C++
Queue in C++ Standard Template Library (STL)
Unordered Sets in C++ Standard Template Library
std::find in C++
List in C++ Standard Template Library (STL)
Inline Functions in C++ | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n01 Dec, 2018"
},
{
"code": null,
"e": 187,
"s": 54,
"text": "Map stores the elements in sorted order of keys. Now if we want to traverse it in reverse order we will use reverse_iterator of map."
},
{
"code": null,
"e": 195,
"s": 187,
"text": "Syntax:"
},
{
"code": null,
"e": 233,
"s": 195,
"text": "map::reverse_iterator iterator_name;\n"
},
{
"code": null,
"e": 648,
"s": 233,
"text": "Reverse Iterator of map moves in backward direction on increment. So, we will point the reverse_iterator to the last element of map and then keep on incrementing it until it reaches the first element. To do this we will use 2 member functions of std::map i.e.1. rbegin() : It returns the reverse_iterator pointing to last element of map.2. rend() : It returns the reverse_iterator pointing to first element of map."
},
{
"code": null,
"e": 794,
"s": 648,
"text": "Now for traversing in reverse order we will iterate over the range b/w rbegin() & rend() using reverse_iterator.Reverse Iteration in map:Example:"
},
{
"code": null,
"e": 918,
"s": 794,
"text": "Input: (10, \"geeks\"), (20, \"practice\"), (5, \" contribute\")\nOutput : (20, \"practice\"), (10, \"geeks\"), (5, \" contribute\")\n"
},
{
"code": "// C++ program makes a map to iterate// elements in reverse order.#include <bits/stdc++.h>using namespace std; int main(){ // Creating & Initializing a map of String & Ints map<int, string> mymap; // Inserting the elements one by one mymap.insert(make_pair(10, \"geeks\")); mymap.insert(make_pair(20, \"practice\")); mymap.insert(make_pair(5, \"contribute\")); // Create a map reverse iterator map<int, string>::reverse_iterator it; // rbegin() returns to the last value of map for (it = mymap.rbegin(); it != mymap.rend(); it++) { cout << \"(\" << it->first << \", \" << it->second << \")\" << endl; } return 0;}",
"e": 1587,
"s": 918,
"text": null
},
{
"code": null,
"e": 1631,
"s": 1587,
"text": "(20, practice)\n(10, geeks)\n(5, contribute)\n"
},
{
"code": null,
"e": 1689,
"s": 1631,
"text": "We can also use auto to avoid remembering complex syntax."
},
{
"code": "// C++ program makes a map to iterate// elements in reverse order with simpler// syntax#include <bits/stdc++.h>using namespace std; int main(){ // Creating & Initializing a map of String & Ints map<int, string> mymap; // Inserting the elements one by one mymap.insert(make_pair(10, \"geeks\")); mymap.insert(make_pair(20, \"practice\")); mymap.insert(make_pair(5, \"contribute\")); // rbegin() returns to the last value of map for (auto it = mymap.rbegin(); it != mymap.rend(); it++) { cout << \"(\" << it->first << \", \" << it->second << \")\" << endl; } return 0;}",
"e": 2302,
"s": 1689,
"text": null
},
{
"code": null,
"e": 2346,
"s": 2302,
"text": "(20, practice)\n(10, geeks)\n(5, contribute)\n"
},
{
"code": null,
"e": 2569,
"s": 2346,
"text": "Reverse Iteration in multimap:Multimap is similar to map with an addition that multiple elements can have same keys. Rather than each element being unique, the key value and mapped value pair has to be unique in this case."
},
{
"code": null,
"e": 2578,
"s": 2569,
"text": "Example:"
},
{
"code": null,
"e": 2804,
"s": 2578,
"text": "Input : (10, \"geeks\"), (20, \"practice\"), (5, \"contribute\"), \n (20, \"van\"), (20, \"watch\"), (5, \"joker\")\nOutput: (20, \"watch\"), (20, \"van\"), (20, \"practice\"), \n (10, \"geeks\"), (5, \"joker\"), (5, \"contribute\")\n"
},
{
"code": "// C++ program makes a multimap to store// elements in descending order.#include <bits/stdc++.h>using namespace std; int main(){ // Creating & Initializing a multimap // of Ints & String multimap<int, std::string> mymap; // Inserting the elements one by one mymap.insert(make_pair(10, \"geeks\")); mymap.insert(make_pair(20, \"practice\")); mymap.insert(make_pair(5, \"contribute\")); // Duplicates allowed mymap.insert(make_pair(20, \"van\")); mymap.insert(make_pair(20, \"watch\")); mymap.insert(make_pair(5, \"joker\")); for (auto it = mymap.rbegin(); it != mymap.rend(); it++) { cout << \"(\" << it->first << \", \" << it->second << \")\" << endl; } return 0;}",
"e": 3527,
"s": 2804,
"text": null
},
{
"code": null,
"e": 3604,
"s": 3527,
"text": "(20, watch)\n(20, van)\n(20, practice)\n(10, geeks)\n(5, joker)\n(5, contribute)\n"
},
{
"code": null,
"e": 3612,
"s": 3604,
"text": "cpp-map"
},
{
"code": null,
"e": 3625,
"s": 3612,
"text": "cpp-multimap"
},
{
"code": null,
"e": 3629,
"s": 3625,
"text": "STL"
},
{
"code": null,
"e": 3633,
"s": 3629,
"text": "C++"
},
{
"code": null,
"e": 3637,
"s": 3633,
"text": "STL"
},
{
"code": null,
"e": 3641,
"s": 3637,
"text": "CPP"
},
{
"code": null,
"e": 3739,
"s": 3641,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3763,
"s": 3739,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 3783,
"s": 3763,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 3816,
"s": 3783,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 3860,
"s": 3816,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 3885,
"s": 3860,
"text": "std::string class in C++"
},
{
"code": null,
"e": 3930,
"s": 3885,
"text": "Queue in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 3978,
"s": 3930,
"text": "Unordered Sets in C++ Standard Template Library"
},
{
"code": null,
"e": 3995,
"s": 3978,
"text": "std::find in C++"
},
{
"code": null,
"e": 4039,
"s": 3995,
"text": "List in C++ Standard Template Library (STL)"
}
] |
TreeSet ceiling() method in Java with Examples | 04 Apr, 2019
The ceiling() method of java.util.TreeSet<E> class is used to return the least element in this set greater than or equal to the given element, or null if there is no such element.
Syntax:
public E ceiling(E e)
Parameters: This method takes the value e as a parameter which is to be matched.
Return Value: This method returns the least element greater than or equal to e, or null if there is no such element.
Exception: This method throws NullPointerException if the specified element is null and this set uses natural ordering, or its comparator does not permit null elements.
Below are the examples to illustrate the ceiling() method
Example 1:
// Java program to demonstrate// ceiling() method import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // create tree set object TreeSet<Integer> treeadd = new TreeSet<Integer>(); // populate the TreeSet treeadd.add(10); treeadd.add(20); treeadd.add(30); treeadd.add(40); // Print the TreeSet System.out.println("TreeSet: " + treeadd); // getting ceiling value for 25 // using ceiling() method int value = treeadd.ceiling(25); // printing the ceiling value System.out.println("Ceiling value for 25: " + value); } catch (NullPointerException e) { System.out.println("Exception thrown : " + e); } }}
TreeSet: [10, 20, 30, 40]
Ceiling value for 25: 30
Example 2: To demonstrate NullPointerException.
// Java program to demonstrate// ceiling() method for NullPointerException import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // create tree set object TreeSet<Integer> treeadd = new TreeSet<Integer>(); // populate the TreeSet treeadd.add(10); treeadd.add(20); treeadd.add(30); treeadd.add(40); // Print the TreeSet System.out.println("TreeSet: " + treeadd); // getting ceiling value for null // using ceiling() method System.out.println("Trying to compare" + " with null value "); int value = treeadd.ceiling(null); // printing the ceiling value System.out.println("Ceiling value for null: " + value); } catch (NullPointerException e) { System.out.println("Exception: " + e); } }}
TreeSet: [10, 20, 30, 40]
Trying to compare with null value
Exception: java.lang.NullPointerException
kumarsgoyal
Java - util package
Java-Collections
Java-Functions
java-treeset
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
ArrayList in Java
Stream In Java
Collections in Java
Singleton Class in Java
Multidimensional Arrays in Java
Stack Class in Java
Introduction to Java
Initialize an ArrayList in Java
Constructors in Java | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n04 Apr, 2019"
},
{
"code": null,
"e": 233,
"s": 53,
"text": "The ceiling() method of java.util.TreeSet<E> class is used to return the least element in this set greater than or equal to the given element, or null if there is no such element."
},
{
"code": null,
"e": 241,
"s": 233,
"text": "Syntax:"
},
{
"code": null,
"e": 263,
"s": 241,
"text": "public E ceiling(E e)"
},
{
"code": null,
"e": 344,
"s": 263,
"text": "Parameters: This method takes the value e as a parameter which is to be matched."
},
{
"code": null,
"e": 461,
"s": 344,
"text": "Return Value: This method returns the least element greater than or equal to e, or null if there is no such element."
},
{
"code": null,
"e": 630,
"s": 461,
"text": "Exception: This method throws NullPointerException if the specified element is null and this set uses natural ordering, or its comparator does not permit null elements."
},
{
"code": null,
"e": 688,
"s": 630,
"text": "Below are the examples to illustrate the ceiling() method"
},
{
"code": null,
"e": 699,
"s": 688,
"text": "Example 1:"
},
{
"code": "// Java program to demonstrate// ceiling() method import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // create tree set object TreeSet<Integer> treeadd = new TreeSet<Integer>(); // populate the TreeSet treeadd.add(10); treeadd.add(20); treeadd.add(30); treeadd.add(40); // Print the TreeSet System.out.println(\"TreeSet: \" + treeadd); // getting ceiling value for 25 // using ceiling() method int value = treeadd.ceiling(25); // printing the ceiling value System.out.println(\"Ceiling value for 25: \" + value); } catch (NullPointerException e) { System.out.println(\"Exception thrown : \" + e); } }}",
"e": 1604,
"s": 699,
"text": null
},
{
"code": null,
"e": 1656,
"s": 1604,
"text": "TreeSet: [10, 20, 30, 40]\nCeiling value for 25: 30\n"
},
{
"code": null,
"e": 1704,
"s": 1656,
"text": "Example 2: To demonstrate NullPointerException."
},
{
"code": "// Java program to demonstrate// ceiling() method for NullPointerException import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // create tree set object TreeSet<Integer> treeadd = new TreeSet<Integer>(); // populate the TreeSet treeadd.add(10); treeadd.add(20); treeadd.add(30); treeadd.add(40); // Print the TreeSet System.out.println(\"TreeSet: \" + treeadd); // getting ceiling value for null // using ceiling() method System.out.println(\"Trying to compare\" + \" with null value \"); int value = treeadd.ceiling(null); // printing the ceiling value System.out.println(\"Ceiling value for null: \" + value); } catch (NullPointerException e) { System.out.println(\"Exception: \" + e); } }}",
"e": 2708,
"s": 1704,
"text": null
},
{
"code": null,
"e": 2812,
"s": 2708,
"text": "TreeSet: [10, 20, 30, 40]\nTrying to compare with null value \nException: java.lang.NullPointerException\n"
},
{
"code": null,
"e": 2824,
"s": 2812,
"text": "kumarsgoyal"
},
{
"code": null,
"e": 2844,
"s": 2824,
"text": "Java - util package"
},
{
"code": null,
"e": 2861,
"s": 2844,
"text": "Java-Collections"
},
{
"code": null,
"e": 2876,
"s": 2861,
"text": "Java-Functions"
},
{
"code": null,
"e": 2889,
"s": 2876,
"text": "java-treeset"
},
{
"code": null,
"e": 2894,
"s": 2889,
"text": "Java"
},
{
"code": null,
"e": 2899,
"s": 2894,
"text": "Java"
},
{
"code": null,
"e": 2916,
"s": 2899,
"text": "Java-Collections"
},
{
"code": null,
"e": 3014,
"s": 2916,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3033,
"s": 3014,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 3051,
"s": 3033,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 3066,
"s": 3051,
"text": "Stream In Java"
},
{
"code": null,
"e": 3086,
"s": 3066,
"text": "Collections in Java"
},
{
"code": null,
"e": 3110,
"s": 3086,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 3142,
"s": 3110,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 3162,
"s": 3142,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 3183,
"s": 3162,
"text": "Introduction to Java"
},
{
"code": null,
"e": 3215,
"s": 3183,
"text": "Initialize an ArrayList in Java"
}
] |
Python – Import CSV into PostgreSQL | 23 Sep, 2021
In this article, we will see how to import CSV files into PostgreSQL using the Python package psycopg2.
First, we import the psycopg2 package and establish a connection to a PostgreSQL database using the pyscopg2.connect() method. before importing a CSV file we need to create a table. In the example below, we created a table by executing the “create table” SQL command using the cursor.execute() method.
'''CREATE TABLE DETAILS(employee_id int NOT NULL,
employee_name char(20),
employee_email varchar(30),
employee_salary float);'''
View of the empty table:
Table Description
After creating the table we need to execute the “copy” command in the SQL form. in the copy command, we need to specify the path of the CSV file.
CSV File Used:
CSV File Used
'''COPY table_name
FROM 'C:\folder\file.csv'
DELIMITER ','
CSV HEADER;'''
Below is the implementation:
Python3
import psycopg2 conn = psycopg2.connect(database="EMPLOYEE_DATABASE", user='postgres', password='pass', host='127.0.0.1', port='5432') conn.autocommit = Truecursor = conn.cursor() sql = '''CREATE TABLE DETAILS(employee_id int NOT NULL,\employee_name char(20),\employee_email varchar(30), employee_salary float);''' cursor.execute(sql) sql2 = '''COPY details(employee_id,employee_name,\employee_email,employee_salary)FROM '/private/tmp/details.csv'DELIMITER ','CSV HEADER;''' cursor.execute(sql2) sql3 = '''select * from details;'''cursor.execute(sql3)for i in cursor.fetchall(): print(i) conn.commit()conn.close()
Output:
(1, 'rajesh ', '[email protected]', 60000.0)
(2, 'pratyusha ', '[email protected]', 75000.0)
(3, 'pratibha ', '[email protected]', 65000.0)
Picked
Python PostgreSQL
Python Pyscopg2
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
Check if element exists in list in Python
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Defaultdict in Python | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Sep, 2021"
},
{
"code": null,
"e": 132,
"s": 28,
"text": "In this article, we will see how to import CSV files into PostgreSQL using the Python package psycopg2."
},
{
"code": null,
"e": 434,
"s": 132,
"text": "First, we import the psycopg2 package and establish a connection to a PostgreSQL database using the pyscopg2.connect() method. before importing a CSV file we need to create a table. In the example below, we created a table by executing the “create table” SQL command using the cursor.execute() method."
},
{
"code": null,
"e": 636,
"s": 434,
"text": "'''CREATE TABLE DETAILS(employee_id int NOT NULL,\n employee_name char(20), \n employee_email varchar(30),\n employee_salary float);'''"
},
{
"code": null,
"e": 661,
"s": 636,
"text": "View of the empty table:"
},
{
"code": null,
"e": 679,
"s": 661,
"text": "Table Description"
},
{
"code": null,
"e": 826,
"s": 679,
"text": "After creating the table we need to execute the “copy” command in the SQL form. in the copy command, we need to specify the path of the CSV file. "
},
{
"code": null,
"e": 841,
"s": 826,
"text": "CSV File Used:"
},
{
"code": null,
"e": 855,
"s": 841,
"text": "CSV File Used"
},
{
"code": null,
"e": 931,
"s": 855,
"text": "'''COPY table_name\nFROM 'C:\\folder\\file.csv' \nDELIMITER ',' \nCSV HEADER;'''"
},
{
"code": null,
"e": 960,
"s": 931,
"text": "Below is the implementation:"
},
{
"code": null,
"e": 968,
"s": 960,
"text": "Python3"
},
{
"code": "import psycopg2 conn = psycopg2.connect(database=\"EMPLOYEE_DATABASE\", user='postgres', password='pass', host='127.0.0.1', port='5432') conn.autocommit = Truecursor = conn.cursor() sql = '''CREATE TABLE DETAILS(employee_id int NOT NULL,\\employee_name char(20),\\employee_email varchar(30), employee_salary float);''' cursor.execute(sql) sql2 = '''COPY details(employee_id,employee_name,\\employee_email,employee_salary)FROM '/private/tmp/details.csv'DELIMITER ','CSV HEADER;''' cursor.execute(sql2) sql3 = '''select * from details;'''cursor.execute(sql3)for i in cursor.fetchall(): print(i) conn.commit()conn.close()",
"e": 1644,
"s": 968,
"text": null
},
{
"code": null,
"e": 1652,
"s": 1644,
"text": "Output:"
},
{
"code": null,
"e": 1827,
"s": 1652,
"text": "(1, 'rajesh ', '[email protected]', 60000.0)\n(2, 'pratyusha ', '[email protected]', 75000.0)\n(3, 'pratibha ', '[email protected]', 65000.0)"
},
{
"code": null,
"e": 1834,
"s": 1827,
"text": "Picked"
},
{
"code": null,
"e": 1852,
"s": 1834,
"text": "Python PostgreSQL"
},
{
"code": null,
"e": 1868,
"s": 1852,
"text": "Python Pyscopg2"
},
{
"code": null,
"e": 1875,
"s": 1868,
"text": "Python"
},
{
"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": 2005,
"s": 1973,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2032,
"s": 2005,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2053,
"s": 2032,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2076,
"s": 2053,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2132,
"s": 2076,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2174,
"s": 2132,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2205,
"s": 2174,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2247,
"s": 2205,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2286,
"s": 2247,
"text": "Python | Get unique values from a list"
}
] |
Jump statements in C++ | 13 Jan, 2021
Jump statements are used to manipulate the flow of the program if some conditions are met. It is used to terminating or continues the loop inside a program or to stop the execution of a function. In C++ there is four jump statement: continue, break, return, and goto.
Continue: It is used to execute other parts of the loop while skipping some parts declared inside the condition, rather than terminating the loop, it continues to execute the next iteration of the same loop. It is used with a decision-making statement which must be present inside the loop. This statement can be used inside for loop or while or do-while loop.
Syntax:
continue;
Program 1:
Consider a scenario where all the numbers between 1 and 10 except number 5. So in this case, the idea is to use the continue statement after the value of i is 5. Below is the program for the same:
C++
// C++ program to demonstrate the// continue statement#include <iostream>using namespace std; // Driver codeint main(){ for (int i = 1; i < 10; i++) { if (i == 5) continue; cout << i << " "; } return 0;}
1 2 3 4 6 7 8 9
Break: It is used to terminate the whole loop if the condition is met. Unlike the continue statement after the condition is met, it breaks the loop and the remaining part of the loop is not executed. Break statement is used with decision-making statements such as if, if-else, or switch statement which is inside the for loop which can be for loop, while loop, or do-while loop. It forces the loop to stop the execution of the further iteration.
Syntax:
break;
Program 2:
Consider a scenario where the series of a number is to be printed but not after a certain value K. So in this case, the idea is to use the break statement after the value of i is K. Below is the program for the same:
C++
// C++ program to demonstrate the// break statement#include <iostream>using namespace std; // Driver Codeint main(){ for (int i = 1; i < 10; i++) { // Breaking Condition if (i == 5) break; cout << i << " "; } return 0;}
1 2 3 4
Return: It takes control out of the function itself. It is stronger than a break. It is used to terminate the entire function after the execution of the function or after some condition. Every function has a return statement with some returning value except the void() function. Although void() function can also have the return statement to end the execution of the function.
Syntax:
return expression;
Program 3:
Below is the program to demonstrate the return statement:
C++
// C++ program to demonstrate the// return statement#include <iostream>using namespace std; // Driver codeint main(){ cout << "Begin "; for (int i = 0; i < 10; i++) { // Termination condition if (i == 5) return 0; cout << i << " "; } cout << "end"; return 0;}
Begin 0 1 2 3 4
Explanation:
The above program starts execution by printing “Begin” then the for loop starts to print the value of, it will print the value of i from 0 to 4 but as soon as i becomes equal to 5 it will terminate the whole function i.e., it will never go to print the “end” statement of the program.
The return in void() functions can be used without any return type.
Syntax:
return;
Program 5:
Below is the program to demonstrate the return statement in void return type in function:
C++
// C++ program to demonstrate the return// statement in void return type function#include <iostream>using namespace std; // Function to find the greater element// among x and yvoid findGreater(int x, int y){ if (x > y) { cout << x << " " << "is greater" << "\n"; return; } else { cout << y << " " << "is greater" << "\n"; return; }} // Driver Codeint main(){ // Function Call findGreater(10, 20); return 0;}
20 is greater
Goto: This statement is used to jump directly to that part of the program to which it is being called. Every goto statement is associated with the label which takes them to part of the program for which they are called. The label statements can be written anywhere in the program it is not necessary to use before or after goto statement. This statement makes it difficult to understand the flow of the program therefore it is avoided to use it in a program.
Syntax:
goto label_name;
.
.
.
label_name:
Program 6:
Below is the program to demonstrate the goto statement:
C++
// C++ program to demonstrate the// goto statement#include <iostream>using namespace std; // Driver Codeint main(){ int n = 4; if (n % 2 == 0) goto label1; else goto label2; label1: cout << "Even" << endl; return 0; label2: cout << "Odd" << endl;}
Even
Explanation: The above program is used to check whether the number is even or odd if the number pressed by the user says it is 4 so the condition is met by the if statement and control go to label1 and label1 prints that the number is even. Here it is not necessary to write a label statement after the goto statement we can write it before goto statement also it will work fine.
Technical Scripter 2020
C++
C++ Programs
Technical Scripter
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting a vector in C++
Polymorphism in C++
Pair in C++ Standard Template Library (STL)
Friend class and function in C++
std::string class in C++
Header files in C/C++ and its uses
Sorting a Map by value in C++ STL
Program to print ASCII Value of a character
How to return multiple values from a function in C or C++?
Shallow Copy and Deep Copy in C++ | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n13 Jan, 2021"
},
{
"code": null,
"e": 322,
"s": 52,
"text": "Jump statements are used to manipulate the flow of the program if some conditions are met. It is used to terminating or continues the loop inside a program or to stop the execution of a function. In C++ there is four jump statement: continue, break, return, and goto. "
},
{
"code": null,
"e": 683,
"s": 322,
"text": "Continue: It is used to execute other parts of the loop while skipping some parts declared inside the condition, rather than terminating the loop, it continues to execute the next iteration of the same loop. It is used with a decision-making statement which must be present inside the loop. This statement can be used inside for loop or while or do-while loop."
},
{
"code": null,
"e": 691,
"s": 683,
"text": "Syntax:"
},
{
"code": null,
"e": 701,
"s": 691,
"text": "continue;"
},
{
"code": null,
"e": 712,
"s": 701,
"text": "Program 1:"
},
{
"code": null,
"e": 909,
"s": 712,
"text": "Consider a scenario where all the numbers between 1 and 10 except number 5. So in this case, the idea is to use the continue statement after the value of i is 5. Below is the program for the same:"
},
{
"code": null,
"e": 913,
"s": 909,
"text": "C++"
},
{
"code": "// C++ program to demonstrate the// continue statement#include <iostream>using namespace std; // Driver codeint main(){ for (int i = 1; i < 10; i++) { if (i == 5) continue; cout << i << \" \"; } return 0;}",
"e": 1154,
"s": 913,
"text": null
},
{
"code": null,
"e": 1171,
"s": 1154,
"text": "1 2 3 4 6 7 8 9\n"
},
{
"code": null,
"e": 1618,
"s": 1171,
"text": "Break: It is used to terminate the whole loop if the condition is met. Unlike the continue statement after the condition is met, it breaks the loop and the remaining part of the loop is not executed. Break statement is used with decision-making statements such as if, if-else, or switch statement which is inside the for loop which can be for loop, while loop, or do-while loop. It forces the loop to stop the execution of the further iteration. "
},
{
"code": null,
"e": 1626,
"s": 1618,
"text": "Syntax:"
},
{
"code": null,
"e": 1633,
"s": 1626,
"text": "break;"
},
{
"code": null,
"e": 1644,
"s": 1633,
"text": "Program 2:"
},
{
"code": null,
"e": 1861,
"s": 1644,
"text": "Consider a scenario where the series of a number is to be printed but not after a certain value K. So in this case, the idea is to use the break statement after the value of i is K. Below is the program for the same:"
},
{
"code": null,
"e": 1865,
"s": 1861,
"text": "C++"
},
{
"code": "// C++ program to demonstrate the// break statement#include <iostream>using namespace std; // Driver Codeint main(){ for (int i = 1; i < 10; i++) { // Breaking Condition if (i == 5) break; cout << i << \" \"; } return 0;}",
"e": 2129,
"s": 1865,
"text": null
},
{
"code": null,
"e": 2138,
"s": 2129,
"text": "1 2 3 4\n"
},
{
"code": null,
"e": 2515,
"s": 2138,
"text": "Return: It takes control out of the function itself. It is stronger than a break. It is used to terminate the entire function after the execution of the function or after some condition. Every function has a return statement with some returning value except the void() function. Although void() function can also have the return statement to end the execution of the function."
},
{
"code": null,
"e": 2523,
"s": 2515,
"text": "Syntax:"
},
{
"code": null,
"e": 2542,
"s": 2523,
"text": "return expression;"
},
{
"code": null,
"e": 2553,
"s": 2542,
"text": "Program 3:"
},
{
"code": null,
"e": 2611,
"s": 2553,
"text": "Below is the program to demonstrate the return statement:"
},
{
"code": null,
"e": 2615,
"s": 2611,
"text": "C++"
},
{
"code": "// C++ program to demonstrate the// return statement#include <iostream>using namespace std; // Driver codeint main(){ cout << \"Begin \"; for (int i = 0; i < 10; i++) { // Termination condition if (i == 5) return 0; cout << i << \" \"; } cout << \"end\"; return 0;}",
"e": 2929,
"s": 2615,
"text": null
},
{
"code": null,
"e": 2946,
"s": 2929,
"text": "Begin 0 1 2 3 4\n"
},
{
"code": null,
"e": 2959,
"s": 2946,
"text": "Explanation:"
},
{
"code": null,
"e": 3244,
"s": 2959,
"text": "The above program starts execution by printing “Begin” then the for loop starts to print the value of, it will print the value of i from 0 to 4 but as soon as i becomes equal to 5 it will terminate the whole function i.e., it will never go to print the “end” statement of the program."
},
{
"code": null,
"e": 3312,
"s": 3244,
"text": "The return in void() functions can be used without any return type."
},
{
"code": null,
"e": 3320,
"s": 3312,
"text": "Syntax:"
},
{
"code": null,
"e": 3328,
"s": 3320,
"text": "return;"
},
{
"code": null,
"e": 3339,
"s": 3328,
"text": "Program 5:"
},
{
"code": null,
"e": 3430,
"s": 3339,
"text": " Below is the program to demonstrate the return statement in void return type in function:"
},
{
"code": null,
"e": 3434,
"s": 3430,
"text": "C++"
},
{
"code": "// C++ program to demonstrate the return// statement in void return type function#include <iostream>using namespace std; // Function to find the greater element// among x and yvoid findGreater(int x, int y){ if (x > y) { cout << x << \" \" << \"is greater\" << \"\\n\"; return; } else { cout << y << \" \" << \"is greater\" << \"\\n\"; return; }} // Driver Codeint main(){ // Function Call findGreater(10, 20); return 0;}",
"e": 3943,
"s": 3434,
"text": null
},
{
"code": null,
"e": 3958,
"s": 3943,
"text": "20 is greater\n"
},
{
"code": null,
"e": 4418,
"s": 3958,
"text": "Goto: This statement is used to jump directly to that part of the program to which it is being called. Every goto statement is associated with the label which takes them to part of the program for which they are called. The label statements can be written anywhere in the program it is not necessary to use before or after goto statement. This statement makes it difficult to understand the flow of the program therefore it is avoided to use it in a program."
},
{
"code": null,
"e": 4426,
"s": 4418,
"text": "Syntax:"
},
{
"code": null,
"e": 4462,
"s": 4426,
"text": "goto label_name;\n.\n.\n.\nlabel_name:\n"
},
{
"code": null,
"e": 4473,
"s": 4462,
"text": "Program 6:"
},
{
"code": null,
"e": 4529,
"s": 4473,
"text": "Below is the program to demonstrate the goto statement:"
},
{
"code": null,
"e": 4533,
"s": 4529,
"text": "C++"
},
{
"code": "// C++ program to demonstrate the// goto statement#include <iostream>using namespace std; // Driver Codeint main(){ int n = 4; if (n % 2 == 0) goto label1; else goto label2; label1: cout << \"Even\" << endl; return 0; label2: cout << \"Odd\" << endl;}",
"e": 4818,
"s": 4533,
"text": null
},
{
"code": null,
"e": 4824,
"s": 4818,
"text": "Even\n"
},
{
"code": null,
"e": 5204,
"s": 4824,
"text": "Explanation: The above program is used to check whether the number is even or odd if the number pressed by the user says it is 4 so the condition is met by the if statement and control go to label1 and label1 prints that the number is even. Here it is not necessary to write a label statement after the goto statement we can write it before goto statement also it will work fine."
},
{
"code": null,
"e": 5228,
"s": 5204,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 5232,
"s": 5228,
"text": "C++"
},
{
"code": null,
"e": 5245,
"s": 5232,
"text": "C++ Programs"
},
{
"code": null,
"e": 5264,
"s": 5245,
"text": "Technical Scripter"
},
{
"code": null,
"e": 5268,
"s": 5264,
"text": "CPP"
},
{
"code": null,
"e": 5366,
"s": 5268,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5390,
"s": 5366,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 5410,
"s": 5390,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 5454,
"s": 5410,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 5487,
"s": 5454,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 5512,
"s": 5487,
"text": "std::string class in C++"
},
{
"code": null,
"e": 5547,
"s": 5512,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 5581,
"s": 5547,
"text": "Sorting a Map by value in C++ STL"
},
{
"code": null,
"e": 5625,
"s": 5581,
"text": "Program to print ASCII Value of a character"
},
{
"code": null,
"e": 5684,
"s": 5625,
"text": "How to return multiple values from a function in C or C++?"
}
] |
Node.js Buffer.toString() Method | 13 Oct, 2021
The Buffer.toString() method is used to decode a buffer data to string according to the specified encoding type. The start and end offset is used to decode only particular subset of a buffer. If the byte sequence in the buffer data is not valid according to the provided encoding, then it is replaced by the default replacement character i.e. U+FFFD.
Syntax:
Buffer.toString( encoding, start, end )
Parameters: This method accept two parameters as mentioned above and described below:
encoding: The format in which the buffer data characters has to be encoded. Its default value is ‘utf8’.
start: The beginning index of the buffer data from which encoding has to be start. Its default value is 0.
end: The last index of the buffer data up to which encoding has to be done. Its default value is Buffer.length.
Return Value: It returns decoded string from buffer to string according to specified character encoding.
Example 1:
// Node.js program to demonstrate the // Buffer.toString() Method // Creating a buffer var buffer = new Buffer.alloc(5); // Loop to add value to the bufferfor (var i = 0; i < 5; i++) { buffer[i] = i + 97;} // Display the value of buffer// in string formatconsole.log(buffer.toString());console.log(buffer.toString('utf-8', 1, 4));console.log(buffer.toString('hex'));
Output:
abcde
bcd
6162636465
Explanation: In the above example, we have declared a variable buffer with size of 5 and have filled with ASCII value from ‘a’ to ‘e’. Next, we have used toString() method without any parameters, that returns the string with default encoding style i.e. ‘UTF-8’ of complete buffer. On the next line, it returns the string with encoding style of ‘UTF-8’ from index 1 to 3 (here, 4 is excluded). At last, it returns the string representation with encoding style of ‘HEX’.
Example 2:
// Node.js program to demonstrate the // Buffer.toString() Method // Creating a buffer var buffer = new Buffer.alloc(5); // Loop to add value to the bufferfor (var i = 0; i < 5; i++) { buffer[i] = i + 97;} // Display the value of buffer// in string formatconsole.log(buffer.toString(undefined));
Output:
abcde
Note: The above program will compile and run by using the node index.js command.
Reference: https://nodejs.org/api/buffer.html#buffer_buf_tostring_encoding_start_end
Node.js-Buffer-module
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js fs.writeFile() Method
How to install the previous version of node.js and npm ?
Difference between promise and async await in Node.js
Mongoose | findByIdAndUpdate() Function
Installation of Node.js on Windows
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 ?
Differences between Functional Components and Class Components in React | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 Oct, 2021"
},
{
"code": null,
"e": 379,
"s": 28,
"text": "The Buffer.toString() method is used to decode a buffer data to string according to the specified encoding type. The start and end offset is used to decode only particular subset of a buffer. If the byte sequence in the buffer data is not valid according to the provided encoding, then it is replaced by the default replacement character i.e. U+FFFD."
},
{
"code": null,
"e": 387,
"s": 379,
"text": "Syntax:"
},
{
"code": null,
"e": 427,
"s": 387,
"text": "Buffer.toString( encoding, start, end )"
},
{
"code": null,
"e": 513,
"s": 427,
"text": "Parameters: This method accept two parameters as mentioned above and described below:"
},
{
"code": null,
"e": 618,
"s": 513,
"text": "encoding: The format in which the buffer data characters has to be encoded. Its default value is ‘utf8’."
},
{
"code": null,
"e": 725,
"s": 618,
"text": "start: The beginning index of the buffer data from which encoding has to be start. Its default value is 0."
},
{
"code": null,
"e": 837,
"s": 725,
"text": "end: The last index of the buffer data up to which encoding has to be done. Its default value is Buffer.length."
},
{
"code": null,
"e": 942,
"s": 837,
"text": "Return Value: It returns decoded string from buffer to string according to specified character encoding."
},
{
"code": null,
"e": 953,
"s": 942,
"text": "Example 1:"
},
{
"code": "// Node.js program to demonstrate the // Buffer.toString() Method // Creating a buffer var buffer = new Buffer.alloc(5); // Loop to add value to the bufferfor (var i = 0; i < 5; i++) { buffer[i] = i + 97;} // Display the value of buffer// in string formatconsole.log(buffer.toString());console.log(buffer.toString('utf-8', 1, 4));console.log(buffer.toString('hex'));",
"e": 1338,
"s": 953,
"text": null
},
{
"code": null,
"e": 1346,
"s": 1338,
"text": "Output:"
},
{
"code": null,
"e": 1368,
"s": 1346,
"text": "abcde\nbcd\n6162636465\n"
},
{
"code": null,
"e": 1837,
"s": 1368,
"text": "Explanation: In the above example, we have declared a variable buffer with size of 5 and have filled with ASCII value from ‘a’ to ‘e’. Next, we have used toString() method without any parameters, that returns the string with default encoding style i.e. ‘UTF-8’ of complete buffer. On the next line, it returns the string with encoding style of ‘UTF-8’ from index 1 to 3 (here, 4 is excluded). At last, it returns the string representation with encoding style of ‘HEX’."
},
{
"code": null,
"e": 1848,
"s": 1837,
"text": "Example 2:"
},
{
"code": "// Node.js program to demonstrate the // Buffer.toString() Method // Creating a buffer var buffer = new Buffer.alloc(5); // Loop to add value to the bufferfor (var i = 0; i < 5; i++) { buffer[i] = i + 97;} // Display the value of buffer// in string formatconsole.log(buffer.toString(undefined));",
"e": 2162,
"s": 1848,
"text": null
},
{
"code": null,
"e": 2170,
"s": 2162,
"text": "Output:"
},
{
"code": null,
"e": 2177,
"s": 2170,
"text": "abcde\n"
},
{
"code": null,
"e": 2258,
"s": 2177,
"text": "Note: The above program will compile and run by using the node index.js command."
},
{
"code": null,
"e": 2343,
"s": 2258,
"text": "Reference: https://nodejs.org/api/buffer.html#buffer_buf_tostring_encoding_start_end"
},
{
"code": null,
"e": 2365,
"s": 2343,
"text": "Node.js-Buffer-module"
},
{
"code": null,
"e": 2372,
"s": 2365,
"text": "Picked"
},
{
"code": null,
"e": 2380,
"s": 2372,
"text": "Node.js"
},
{
"code": null,
"e": 2397,
"s": 2380,
"text": "Web Technologies"
},
{
"code": null,
"e": 2495,
"s": 2397,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2525,
"s": 2495,
"text": "Node.js fs.writeFile() Method"
},
{
"code": null,
"e": 2582,
"s": 2525,
"text": "How to install the previous version of node.js and npm ?"
},
{
"code": null,
"e": 2636,
"s": 2582,
"text": "Difference between promise and async await in Node.js"
},
{
"code": null,
"e": 2676,
"s": 2636,
"text": "Mongoose | findByIdAndUpdate() Function"
},
{
"code": null,
"e": 2711,
"s": 2676,
"text": "Installation of Node.js on Windows"
},
{
"code": null,
"e": 2773,
"s": 2711,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2834,
"s": 2773,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2884,
"s": 2834,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 2927,
"s": 2884,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Python – Find Words with both alphabets and numbers | 22 Apr, 2020
Sometimes, while working with Python strings, we can have problem in which we need to extract certain words with contain both numbers and alphabets. This kind of problem can occur in many domains like school programming and web-development. Lets discuss certain ways in which this task can be performed.
Method #1 : Using any() + isdigit() + isalpha()The combination of above functionalities can be used to perform this task. In this, we iterate for all the words and check for required combination using isdigit() and isalpha().
# Python3 code to demonstrate working of # Words with both alphabets and numbers# Using isdigit() + isalpha() + any() # initializing stringtest_str = 'geeksfor23geeks is best45 for gee34ks and cs' # printing original stringprint("The original string is : " + test_str) # Words with both alphabets and numbers# Using isdigit() + isalpha() + any()res = []temp = test_str.split()for idx in temp: if any(chr.isalpha() for chr in idx) and any(chr.isdigit() for chr in idx): res.append(idx) # printing result print("Words with alphabets and numbers : " + str(res))
The original string is : geeksfor23geeks is best45 for gee34ks and csWords with alphabets and numbers : [‘geeksfor23geeks’, ‘best45’, ‘gee34ks’]
Method #2 : Using regexThis is yet another way by which we can perform this task. In this, we feed the string to findall(), and extract the required result. Returns strings till the numbers only.
# Python3 code to demonstrate working of # Words with both alphabets and numbers# Using regeximport re # initializing stringtest_str = 'geeksfor23geeks is best45 for gee34ks and cs' # printing original stringprint("The original string is : " + test_str) # Words with both alphabets and numbers# Using regexres = re.findall(r'(?:\d+[a-zA-Z]+|[a-zA-Z]+\d+)', test_str) # printing result print("Words with alphabets and numbers : " + str(res))
The original string is : geeksfor23geeks is best45 for gee34ks and csWords with alphabets and numbers : [‘geeksfor23’, ‘best45’, ‘gee34’]
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Apr, 2020"
},
{
"code": null,
"e": 332,
"s": 28,
"text": "Sometimes, while working with Python strings, we can have problem in which we need to extract certain words with contain both numbers and alphabets. This kind of problem can occur in many domains like school programming and web-development. Lets discuss certain ways in which this task can be performed."
},
{
"code": null,
"e": 558,
"s": 332,
"text": "Method #1 : Using any() + isdigit() + isalpha()The combination of above functionalities can be used to perform this task. In this, we iterate for all the words and check for required combination using isdigit() and isalpha()."
},
{
"code": "# Python3 code to demonstrate working of # Words with both alphabets and numbers# Using isdigit() + isalpha() + any() # initializing stringtest_str = 'geeksfor23geeks is best45 for gee34ks and cs' # printing original stringprint(\"The original string is : \" + test_str) # Words with both alphabets and numbers# Using isdigit() + isalpha() + any()res = []temp = test_str.split()for idx in temp: if any(chr.isalpha() for chr in idx) and any(chr.isdigit() for chr in idx): res.append(idx) # printing result print(\"Words with alphabets and numbers : \" + str(res)) ",
"e": 1140,
"s": 558,
"text": null
},
{
"code": null,
"e": 1285,
"s": 1140,
"text": "The original string is : geeksfor23geeks is best45 for gee34ks and csWords with alphabets and numbers : [‘geeksfor23geeks’, ‘best45’, ‘gee34ks’]"
},
{
"code": null,
"e": 1483,
"s": 1287,
"text": "Method #2 : Using regexThis is yet another way by which we can perform this task. In this, we feed the string to findall(), and extract the required result. Returns strings till the numbers only."
},
{
"code": "# Python3 code to demonstrate working of # Words with both alphabets and numbers# Using regeximport re # initializing stringtest_str = 'geeksfor23geeks is best45 for gee34ks and cs' # printing original stringprint(\"The original string is : \" + test_str) # Words with both alphabets and numbers# Using regexres = re.findall(r'(?:\\d+[a-zA-Z]+|[a-zA-Z]+\\d+)', test_str) # printing result print(\"Words with alphabets and numbers : \" + str(res)) ",
"e": 1937,
"s": 1483,
"text": null
},
{
"code": null,
"e": 2075,
"s": 1937,
"text": "The original string is : geeksfor23geeks is best45 for gee34ks and csWords with alphabets and numbers : [‘geeksfor23’, ‘best45’, ‘gee34’]"
},
{
"code": null,
"e": 2098,
"s": 2075,
"text": "Python string-programs"
},
{
"code": null,
"e": 2105,
"s": 2098,
"text": "Python"
},
{
"code": null,
"e": 2121,
"s": 2105,
"text": "Python Programs"
}
] |
Find the Product of first N Prime Numbers in C++ | Suppose we have a number n. We have to find the product of prime numbers between 1 to n. So if n = 7, then output will be 210, as 2 * 3 * 5 * 7 = 210.
We will use the Sieve of Eratosthenes method to find all primes. Then calculate the product of them.
Live Demo
#include<iostream>
using namespace std;
long PrimeProds(int n) {
bool prime[n + 1];
for(int i = 0; i<=n; i++){
prime[i] = true;
}
for (int i = 2; i * i <= n; i++) {
if (prime[i] == true) {
for (int j = i * 2; j <= n; j += i)
prime[j] = false;
}
}
long product = 1;
for (int i = 2; i <= n; i++)
if (prime[i])
product *= i;
return product;
}
int main() {
int n = 8;
cout << "Product of primes up to " << n << " is: " << PrimeProds(n);
}
Product of primes up to 8 is: 210 | [
{
"code": null,
"e": 1213,
"s": 1062,
"text": "Suppose we have a number n. We have to find the product of prime numbers between 1 to n. So if n = 7, then output will be 210, as 2 * 3 * 5 * 7 = 210."
},
{
"code": null,
"e": 1314,
"s": 1213,
"text": "We will use the Sieve of Eratosthenes method to find all primes. Then calculate the product of them."
},
{
"code": null,
"e": 1325,
"s": 1314,
"text": " Live Demo"
},
{
"code": null,
"e": 1841,
"s": 1325,
"text": "#include<iostream>\nusing namespace std;\nlong PrimeProds(int n) {\n bool prime[n + 1];\n for(int i = 0; i<=n; i++){\n prime[i] = true;\n }\n for (int i = 2; i * i <= n; i++) {\n if (prime[i] == true) {\n for (int j = i * 2; j <= n; j += i)\n prime[j] = false;\n }\n }\n long product = 1;\n for (int i = 2; i <= n; i++)\n if (prime[i])\n product *= i;\n return product;\n}\nint main() {\n int n = 8;\n cout << \"Product of primes up to \" << n << \" is: \" << PrimeProds(n);\n}"
},
{
"code": null,
"e": 1875,
"s": 1841,
"text": "Product of primes up to 8 is: 210"
}
] |
Command Line Interface Programming in Python? | In this section we are going to develop a command line interface using python. But before we deep dive into program, lets first understand command line.
Command line are in use since the existence of computer programs and are built on commands. A command line program is a program that runs from a shell or from a command line
While command line interface provides user interface that is navigated by typing commands at terminals, shells or consoles instead of using the mouse.
A command-line interface(CLI) starts with an executable. There are parameters which we can pass to the script depending how they are developed, like:
Arguments: We need to provide this parameter that is passed to the script. In case we don’t provide it, the CLI will through an error. For example, numpy is the argument in this command: pip install
numpy.
Arguments: We need to provide this parameter that is passed to the script. In case we don’t provide it, the CLI will through an error. For example, numpy is the argument in this command: pip install
numpy.
Options: An optional parameter which comes with a name and a value pair like: pip install django –cache-dir ./my-cache-dir where –cache_dir is an option param and the value ./my-cache-dir should be uses as the cache directory.
Options: An optional parameter which comes with a name and a value pair like: pip install django –cache-dir ./my-cache-dir where –cache_dir is an option param and the value ./my-cache-dir should be uses as the cache directory.
Flags: Another optional parameter which tells the script to enable or disable a certain behaviour
for example the –help parameter.
Flags: Another optional parameter which tells the script to enable or disable a certain behaviour
for example the –help parameter.
Python provides multiple python package to write command line interfaces such as ‘click’. Click allows us to build command line interfaces with a very few lines of code.
Below is a command line interface program without using click package. Writing CLI program may be not as elegant as the one we got using ‘click’ package, as ‘click’ allows you to follow the “Don’t Repeat Yourself” (DRY) principles.
import sys
import random
def do_work():
""" Function to handle command line usage"""
args = sys.argv
args = args[1:] # First element of args is the file name
if len(args) == 0:
print('You have not passed any commands in!')
else:
for a in args:
if a == '--help':
print('Basic command line program')
print('Options:')
print(' --help -> show this basic help menu.')
print(' --monty -> show a Monty Python quote.')
print(' --veg -> show a random vegetable')
elif a == '--monty':
print('He’s not the Messiah—he’s a very naughty boy')
elif a == '--veg':
print(random.choice(['Tomato','Reddis','Carrot', 'Potato', 'Turnip']))
else:
print('Unrecognised argument.')
if __name__ == '__main__':
do_work()
c:\Python\Python361>python cli_interp1.py --monty
He’s not the Messiah—he’s a very naughty boy
c:\Python\Python361>python cli_interp1.py --help
Basic command line program
Options:
--help -> show this basic help menu.
--monty -> show a Monty Python quote.
--veg -> show a random vegetable
c:\Python\Python361>python cli_interp1.py --veg
Tomato
c:\Python\Python361>python cli_interp1.py --error
Unrecognised argument.
As you can see in above program, it is not providing much flexibility to change an argument name.
Below is the same program using python click package to implement CLI.
import click
import random
@click.command()
@click.option('--monty', default=False, help='Show a Monty Python quote.')
@click.option('--veg', default=False, help='Show a random vegetable.')
def do_work(monty, veg):
""" Basic Click example will follow your commands"""
if monty:
print('He’s not the Messiah—he’s a very naughty boy')
if veg:
print(random.choice(['Tomato','Reddis','Carrot', 'Potato', 'Turnip']))
if __name__ == '__main__':
do_work()
c:\Python\Python361>python cli_interp2.py --help
Usage: cli_interp2.py [OPTIONS]
Basic Click example will follow your commands
Options:
--monty TEXT Show a Monty Python quote.
--veg TEXT Show a random vegetable.
--help Show this message and exit.
The above program shows, it’s much easier to write CLI using ‘click’ package and save lot of programmers efforts. | [
{
"code": null,
"e": 1215,
"s": 1062,
"text": "In this section we are going to develop a command line interface using python. But before we deep dive into program, lets first understand command line."
},
{
"code": null,
"e": 1389,
"s": 1215,
"text": "Command line are in use since the existence of computer programs and are built on commands. A command line program is a program that runs from a shell or from a command line"
},
{
"code": null,
"e": 1540,
"s": 1389,
"text": "While command line interface provides user interface that is navigated by typing commands at terminals, shells or consoles instead of using the mouse."
},
{
"code": null,
"e": 1690,
"s": 1540,
"text": "A command-line interface(CLI) starts with an executable. There are parameters which we can pass to the script depending how they are developed, like:"
},
{
"code": null,
"e": 1896,
"s": 1690,
"text": "Arguments: We need to provide this parameter that is passed to the script. In case we don’t provide it, the CLI will through an error. For example, numpy is the argument in this command: pip install\nnumpy."
},
{
"code": null,
"e": 2102,
"s": 1896,
"text": "Arguments: We need to provide this parameter that is passed to the script. In case we don’t provide it, the CLI will through an error. For example, numpy is the argument in this command: pip install\nnumpy."
},
{
"code": null,
"e": 2329,
"s": 2102,
"text": "Options: An optional parameter which comes with a name and a value pair like: pip install django –cache-dir ./my-cache-dir where –cache_dir is an option param and the value ./my-cache-dir should be uses as the cache directory."
},
{
"code": null,
"e": 2556,
"s": 2329,
"text": "Options: An optional parameter which comes with a name and a value pair like: pip install django –cache-dir ./my-cache-dir where –cache_dir is an option param and the value ./my-cache-dir should be uses as the cache directory."
},
{
"code": null,
"e": 2687,
"s": 2556,
"text": "Flags: Another optional parameter which tells the script to enable or disable a certain behaviour\nfor example the –help parameter."
},
{
"code": null,
"e": 2818,
"s": 2687,
"text": "Flags: Another optional parameter which tells the script to enable or disable a certain behaviour\nfor example the –help parameter."
},
{
"code": null,
"e": 2988,
"s": 2818,
"text": "Python provides multiple python package to write command line interfaces such as ‘click’. Click allows us to build command line interfaces with a very few lines of code."
},
{
"code": null,
"e": 3220,
"s": 2988,
"text": "Below is a command line interface program without using click package. Writing CLI program may be not as elegant as the one we got using ‘click’ package, as ‘click’ allows you to follow the “Don’t Repeat Yourself” (DRY) principles."
},
{
"code": null,
"e": 4076,
"s": 3220,
"text": "import sys\nimport random\n\ndef do_work():\n \"\"\" Function to handle command line usage\"\"\"\n args = sys.argv\n args = args[1:] # First element of args is the file name\n\n if len(args) == 0:\n print('You have not passed any commands in!')\n else:\n for a in args:\n if a == '--help':\n print('Basic command line program')\n print('Options:')\n print(' --help -> show this basic help menu.')\n print(' --monty -> show a Monty Python quote.')\n print(' --veg -> show a random vegetable')\n elif a == '--monty':\n print('He’s not the Messiah—he’s a very naughty boy')\n elif a == '--veg':\n print(random.choice(['Tomato','Reddis','Carrot', 'Potato', 'Turnip']))\n else:\n print('Unrecognised argument.')\n\nif __name__ == '__main__':\ndo_work()"
},
{
"code": null,
"e": 4495,
"s": 4076,
"text": "c:\\Python\\Python361>python cli_interp1.py --monty\nHe’s not the Messiah—he’s a very naughty boy\n\nc:\\Python\\Python361>python cli_interp1.py --help\nBasic command line program\nOptions:\n--help -> show this basic help menu.\n--monty -> show a Monty Python quote.\n--veg -> show a random vegetable\n\nc:\\Python\\Python361>python cli_interp1.py --veg\nTomato\n\nc:\\Python\\Python361>python cli_interp1.py --error\nUnrecognised argument."
},
{
"code": null,
"e": 4593,
"s": 4495,
"text": "As you can see in above program, it is not providing much flexibility to change an argument name."
},
{
"code": null,
"e": 4664,
"s": 4593,
"text": "Below is the same program using python click package to implement CLI."
},
{
"code": null,
"e": 5125,
"s": 4664,
"text": "import click\nimport random\n\[email protected]()\[email protected]('--monty', default=False, help='Show a Monty Python quote.')\[email protected]('--veg', default=False, help='Show a random vegetable.')\ndef do_work(monty, veg):\n\"\"\" Basic Click example will follow your commands\"\"\"\nif monty:\n print('He’s not the Messiah—he’s a very naughty boy')\n if veg:\n print(random.choice(['Tomato','Reddis','Carrot', 'Potato', 'Turnip']))\nif __name__ == '__main__':\ndo_work()"
},
{
"code": null,
"e": 5374,
"s": 5125,
"text": "c:\\Python\\Python361>python cli_interp2.py --help\nUsage: cli_interp2.py [OPTIONS]\n\nBasic Click example will follow your commands\n\nOptions:\n--monty TEXT Show a Monty Python quote.\n--veg TEXT Show a random vegetable.\n--help Show this message and exit."
},
{
"code": null,
"e": 5488,
"s": 5374,
"text": "The above program shows, it’s much easier to write CLI using ‘click’ package and save lot of programmers efforts."
}
] |
How to display count of notifications in toolbar icon in Android? | This example demonstrate about How to display count of notifications in toolbar icon in Android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<? xml version = "1.0" encoding = "utf-8" ?>
<RelativeLayout xmlns: android = "http://schemas.android.com/apk/res/android"
xmlns: tools = "http://schemas.android.com/tools"
android :layout_width = "match_parent"
android :layout_height = "match_parent"
tools :context = ".MainActivity" >
<Toolbar
android :layout_width = "match_parent"
android :layout_height = "?actionBarSize"
android :background = "@color/colorPrimary" >
<RelativeLayout
android :layout_width = "match_parent"
android :layout_height = "match_parent"
android :layout_marginEnd = "16dp" >
<TextView
android :layout_width = "wrap_content"
android :layout_height = "wrap_content"
android :layout_centerVertical = "true"
android :text = "Notify Me"
android :textAppearance = "@style/Base.TextAppearance.AppCompat.Medium"
android :textColor = "#FFF"
android :textStyle = "bold" />
<RelativeLayout
android :id = "@+id/notificationBadge"
android :layout_width = "wrap_content"
android :layout_height = "wrap_content"
android :layout_alignParentEnd = "true"
android :layout_centerVertical = "true" >
<RelativeLayout
android :id= "@+id/badgeLayout"
android :layout_width = "wrap_content"
android :layout_height = "wrap_content"
android :paddingTop = "8dp" >
<Button
android :layout_width = "36dp"
android :layout_height = "36dp"
android :background = "@drawable/action_notification" />
</RelativeLayout>
<TextView
android :id = "@+id/tvBadgeNumber"
android :layout_width = "wrap_content"
android :layout_height = "wrap_content"
android :layout_alignTop = "@+id/badgeLayout"
android :layout_alignEnd = "@id/badgeLayout"
android :background = "@drawable/item_count"
android :text = "0"
android :textColor = "#FFF"
android :textSize = "16sp"
android :textStyle = "bold" />
</RelativeLayout>
</RelativeLayout>
</Toolbar>
<Button
android :layout_width = "match_parent"
android :layout_height = "wrap_content"
android :layout_centerInParent = "true"
android :layout_margin = "16dp"
android :onClick = "createNotification"
android :text = "create notification" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.
package app.tutorialspoint.com.notifyme ;
import android.app.NotificationChannel ;
import android.app.NotificationManager ;
import android.app.PendingIntent ;
import android.content.Intent ;
import android.os.Bundle ;
import android.support.v4.app.NotificationCompat ;
import android.support.v7.app.AppCompatActivity ;
import android.view.View ;
import android.widget.TextView ;
public class MainActivity extends AppCompatActivity {
public static final String NOTIFICATION_CHANNEL_ID = "10001" ;
private final static String default_notification_channel_id = "default" ;
static int notificationCount = 0 ;
TextView tvBadgeNumber ;
@Override
protected void onCreate (Bundle savedInstanceState) {
super .onCreate(savedInstanceState) ;
setContentView(R.layout. activity_main ) ;
tvBadgeNumber = findViewById(R.id. tvBadgeNumber ) ;
}
public void createNotification (View view) {
Intent notificationIntent = new Intent(getApplicationContext() , MainActivity. class ) ;
notificationIntent.putExtra( "fromNotification" , true ) ;
notificationIntent.setFlags(Intent. FLAG_ACTIVITY_CLEAR_TOP | Intent. FLAG_ACTIVITY_SINGLE_TOP ) ;
PendingIntent pendingIntent = PendingIntent. getActivity ( this, 0 , notificationIntent , 0 ) ;
NotificationManager mNotificationManager = (NotificationManager) getSystemService( NOTIFICATION_SERVICE ) ;
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(MainActivity. this, default_notification_channel_id ) ;
mBuilder.setContentTitle( "My Notification" ) ;
mBuilder.setContentIntent(pendingIntent) ;
mBuilder.setContentText( "Notification Listener Service Example" ) ;
mBuilder.setTicker( "Notification Listener Service Example" ) ;
mBuilder.setSmallIcon(R.drawable. ic_launcher_foreground ) ;
mBuilder.setAutoCancel( true ) ;
if (android.os.Build.VERSION. SDK_INT >= android.os.Build.VERSION_CODES. O ) {
int importance = NotificationManager. IMPORTANCE_HIGH ;
NotificationChannel notificationChannel = new NotificationChannel( NOTIFICATION_CHANNEL_ID , "NOTIFICATION_CHANNEL_NAME" , importance) ;
mBuilder.setChannelId( NOTIFICATION_CHANNEL_ID ) ;
assert mNotificationManager != null;
mNotificationManager.createNotificationChannel(notificationChannel) ;
}
assert mNotificationManager != null;
mNotificationManager.notify(( int ) System. currentTimeMillis () , mBuilder.build()) ;
notificationCount ++ ;
tvBadgeNumber .setText(String. valueOf ( notificationCount )) ;
}
}
Step 4 − Add the following code to res/drawable/item_count.xml
<? xml version = "1.0" encoding = "utf-8" ?>
<shape xmlns: android = "http://schemas.android.com/apk/res/android"
android :shape = "rectangle" >
<corners android :radius = "8dp" />
<solid android :color = "#2196F3" />
<stroke
android :width = "1dip"
android :color = "#FFF" />
<padding
android :bottom = "2dp"
android :left = "2dp"
android :right = "2dp"
android :top = "2dp" />
</shape>
Step 5 − Add the following code to AndroidManifest.xml
<? xml version = "1.0" encoding = "utf-8" ?>
<manifest xmlns: android = "http://schemas.android.com/apk/res/android"
package= "app.tutorialspoint.com.notifyme" >
<uses-permission android :name= "android.permission.VIBRATE" />
<application
android :allowBackup = "true"
android :icon = "@mipmap/ic_launcher"
android :label = "@string/app_name"
android :roundIcon = "@mipmap/ic_launcher_round"
android :supportsRtl = "true"
android :theme = "@style/AppTheme" >
<activity android :name = ".MainActivity" >
<intent-filter>
<action android :name = "android.intent.action.MAIN" />
<category android :name = "android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
Click here to download the project code | [
{
"code": null,
"e": 1159,
"s": 1062,
"text": "This example demonstrate about How to display count of notifications in toolbar icon in Android."
},
{
"code": null,
"e": 1288,
"s": 1159,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1353,
"s": 1288,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 3986,
"s": 1353,
"text": "<? xml version = \"1.0\" encoding = \"utf-8\" ?>\n<RelativeLayout xmlns: android = \"http://schemas.android.com/apk/res/android\"\n xmlns: tools = \"http://schemas.android.com/tools\"\n android :layout_width = \"match_parent\"\n android :layout_height = \"match_parent\"\n tools :context = \".MainActivity\" >\n <Toolbar\n android :layout_width = \"match_parent\"\n android :layout_height = \"?actionBarSize\"\n android :background = \"@color/colorPrimary\" >\n <RelativeLayout\n android :layout_width = \"match_parent\"\n android :layout_height = \"match_parent\"\n android :layout_marginEnd = \"16dp\" >\n <TextView\n android :layout_width = \"wrap_content\"\n android :layout_height = \"wrap_content\"\n android :layout_centerVertical = \"true\"\n android :text = \"Notify Me\"\n android :textAppearance = \"@style/Base.TextAppearance.AppCompat.Medium\"\n android :textColor = \"#FFF\"\n android :textStyle = \"bold\" />\n <RelativeLayout\n android :id = \"@+id/notificationBadge\"\n android :layout_width = \"wrap_content\"\n android :layout_height = \"wrap_content\"\n android :layout_alignParentEnd = \"true\"\n android :layout_centerVertical = \"true\" >\n <RelativeLayout\n android :id= \"@+id/badgeLayout\"\n android :layout_width = \"wrap_content\"\n android :layout_height = \"wrap_content\"\n android :paddingTop = \"8dp\" >\n <Button\n android :layout_width = \"36dp\"\n android :layout_height = \"36dp\"\n android :background = \"@drawable/action_notification\" />\n </RelativeLayout>\n <TextView\n android :id = \"@+id/tvBadgeNumber\"\n android :layout_width = \"wrap_content\"\n android :layout_height = \"wrap_content\"\n android :layout_alignTop = \"@+id/badgeLayout\"\n android :layout_alignEnd = \"@id/badgeLayout\"\n android :background = \"@drawable/item_count\"\n android :text = \"0\"\n android :textColor = \"#FFF\"\n android :textSize = \"16sp\"\n android :textStyle = \"bold\" />\n </RelativeLayout>\n </RelativeLayout>\n </Toolbar>\n <Button\n android :layout_width = \"match_parent\"\n android :layout_height = \"wrap_content\"\n android :layout_centerInParent = \"true\"\n android :layout_margin = \"16dp\"\n android :onClick = \"createNotification\"\n android :text = \"create notification\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 4039,
"s": 3986,
"text": "Step 3 − Add the following code to src/MainActivity."
},
{
"code": null,
"e": 6653,
"s": 4039,
"text": "package app.tutorialspoint.com.notifyme ;\nimport android.app.NotificationChannel ;\nimport android.app.NotificationManager ;\nimport android.app.PendingIntent ;\nimport android.content.Intent ;\nimport android.os.Bundle ;\nimport android.support.v4.app.NotificationCompat ;\nimport android.support.v7.app.AppCompatActivity ;\nimport android.view.View ;\nimport android.widget.TextView ;\npublic class MainActivity extends AppCompatActivity {\n public static final String NOTIFICATION_CHANNEL_ID = \"10001\" ;\n private final static String default_notification_channel_id = \"default\" ;\n static int notificationCount = 0 ;\n TextView tvBadgeNumber ;\n @Override\n protected void onCreate (Bundle savedInstanceState) {\n super .onCreate(savedInstanceState) ;\n setContentView(R.layout. activity_main ) ;\n tvBadgeNumber = findViewById(R.id. tvBadgeNumber ) ;\n }\n public void createNotification (View view) {\n Intent notificationIntent = new Intent(getApplicationContext() , MainActivity. class ) ;\n notificationIntent.putExtra( \"fromNotification\" , true ) ;\n notificationIntent.setFlags(Intent. FLAG_ACTIVITY_CLEAR_TOP | Intent. FLAG_ACTIVITY_SINGLE_TOP ) ;\n PendingIntent pendingIntent = PendingIntent. getActivity ( this, 0 , notificationIntent , 0 ) ;\n NotificationManager mNotificationManager = (NotificationManager) getSystemService( NOTIFICATION_SERVICE ) ;\n NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(MainActivity. this, default_notification_channel_id ) ;\n mBuilder.setContentTitle( \"My Notification\" ) ;\n mBuilder.setContentIntent(pendingIntent) ;\n mBuilder.setContentText( \"Notification Listener Service Example\" ) ;\n mBuilder.setTicker( \"Notification Listener Service Example\" ) ;\n mBuilder.setSmallIcon(R.drawable. ic_launcher_foreground ) ;\n mBuilder.setAutoCancel( true ) ;\n if (android.os.Build.VERSION. SDK_INT >= android.os.Build.VERSION_CODES. O ) {\n int importance = NotificationManager. IMPORTANCE_HIGH ;\n NotificationChannel notificationChannel = new NotificationChannel( NOTIFICATION_CHANNEL_ID , \"NOTIFICATION_CHANNEL_NAME\" , importance) ;\n mBuilder.setChannelId( NOTIFICATION_CHANNEL_ID ) ;\n assert mNotificationManager != null;\n mNotificationManager.createNotificationChannel(notificationChannel) ;\n }\n assert mNotificationManager != null;\n mNotificationManager.notify(( int ) System. currentTimeMillis () , mBuilder.build()) ;\n notificationCount ++ ;\n tvBadgeNumber .setText(String. valueOf ( notificationCount )) ;\n }\n}"
},
{
"code": null,
"e": 6716,
"s": 6653,
"text": "Step 4 − Add the following code to res/drawable/item_count.xml"
},
{
"code": null,
"e": 7176,
"s": 6716,
"text": "<? xml version = \"1.0\" encoding = \"utf-8\" ?>\n<shape xmlns: android = \"http://schemas.android.com/apk/res/android\"\n android :shape = \"rectangle\" >\n <corners android :radius = \"8dp\" />\n <solid android :color = \"#2196F3\" />\n <stroke\n android :width = \"1dip\"\n android :color = \"#FFF\" />\n <padding\n android :bottom = \"2dp\"\n android :left = \"2dp\"\n android :right = \"2dp\"\n android :top = \"2dp\" />\n </shape>"
},
{
"code": null,
"e": 7231,
"s": 7176,
"text": "Step 5 − Add the following code to AndroidManifest.xml"
},
{
"code": null,
"e": 8028,
"s": 7231,
"text": "<? xml version = \"1.0\" encoding = \"utf-8\" ?>\n<manifest xmlns: android = \"http://schemas.android.com/apk/res/android\"\n package= \"app.tutorialspoint.com.notifyme\" >\n <uses-permission android :name= \"android.permission.VIBRATE\" />\n <application\n android :allowBackup = \"true\"\n android :icon = \"@mipmap/ic_launcher\"\n android :label = \"@string/app_name\"\n android :roundIcon = \"@mipmap/ic_launcher_round\"\n android :supportsRtl = \"true\"\n android :theme = \"@style/AppTheme\" >\n <activity android :name = \".MainActivity\" >\n <intent-filter>\n <action android :name = \"android.intent.action.MAIN\" />\n <category android :name = \"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 8375,
"s": 8028,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −"
},
{
"code": null,
"e": 8417,
"s": 8375,
"text": "Click here to download the project code"
}
] |
Count of distinct substrings of a string using Suffix Array - GeeksforGeeks | 06 Jun, 2021
Given a string of length n of lowercase alphabet characters, we need to count total number of distinct substrings of this string. Examples:
Input : str = “ababa”
Output : 10
Total number of distinct substring are 10, which are,
"", "a", "b", "ab", "ba", "aba", "bab", "abab", "baba"
and "ababa"
We have discussed a Suffix Trie based solution in below post : Count of distinct substrings of a string using Suffix TrieWe can solve this problem using suffix array and longest common prefix concept. A suffix array is a sorted array of all suffixes of a given string. For string “ababa” suffixes are : “ababa”, “baba”, “aba”, “ba”, “a”. After taking these suffixes in sorted form we get our suffix array as [4, 2, 0, 3, 1] Then we calculate lcp array using kasai’s algorithm. For string “ababa”, lcp array is [1, 3, 0, 2, 0]After constructing both arrays, we calculate total number of distinct substring by keeping this fact in mind : If we look through the prefixes of each suffix of a string, we cover all substrings of that string. We will explain the procedure for above example,
String = “ababa”
Suffixes in sorted order : “a”, “aba”, “ababa”,
“ba”, “baba”
Initializing distinct substring count by length
of first suffix,
Count = length(“a”) = 1
Substrings taken in consideration : “a”
Now we consider each consecutive pair of suffix,
lcp("a", "aba") = "a".
All characters that are not part of the longest
common prefix contribute to a distinct substring.
In the above case, they are 'b' and ‘a'. So they
should be added to Count.
Count += length(“aba”) - lcp(“a”, “aba”)
Count = 3
Substrings taken in consideration : “aba”, “ab”
Similarly for next pair also,
Count += length(“ababa”) - lcp(“aba”, “ababa”)
Count = 5
Substrings taken in consideration : “ababa”, “abab”
Count += length(“ba”) - lcp(“ababa”, “ba”)
Count = 7
Substrings taken in consideration : “ba”, “b”
Count += length(“baba”) - lcp(“ba”, “baba”)
Count = 9
Substrings taken in consideration : “baba”, “bab”
We finally add 1 for empty string.
count = 10
Above idea is implemented in below code.
CPP
// C++ code to count total distinct substrings// of a string#include <bits/stdc++.h>using namespace std; // Structure to store information of a suffixstruct suffix{ int index; // To store original index int rank[2]; // To store ranks and next // rank pair}; // A comparison function used by sort() to compare// two suffixes. Compares two pairs, returns 1 if// first pair is smallerint cmp(struct suffix a, struct suffix b){ return (a.rank[0] == b.rank[0])? (a.rank[1] < b.rank[1] ?1: 0): (a.rank[0] < b.rank[0] ?1: 0);} // This is the main function that takes a string// 'txt' of size n as an argument, builds and return// the suffix array for the given stringvector<int> buildSuffixArray(string txt, int n){ // A structure to store suffixes and their indexes struct suffix suffixes[n]; // Store suffixes and their indexes in an array // of structures. The structure is needed to sort // the suffixes alphabetically and maintain their // old indexes while sorting for (int i = 0; i < n; i++) { suffixes[i].index = i; suffixes[i].rank[0] = txt[i] - 'a'; suffixes[i].rank[1] = ((i+1) < n)? (txt[i + 1] - 'a'): -1; } // Sort the suffixes using the comparison function // defined above. sort(suffixes, suffixes+n, cmp); // At his point, all suffixes are sorted according // to first 2 characters. Let us sort suffixes // according to first 4 characters, then first // 8 and so on int ind[n]; // This array is needed to get the // index in suffixes[] from original // index. This mapping is needed to get // next suffix. for (int k = 4; k < 2*n; k = k*2) { // Assigning rank and index values to first suffix int rank = 0; int prev_rank = suffixes[0].rank[0]; suffixes[0].rank[0] = rank; ind[suffixes[0].index] = 0; // Assigning rank to suffixes for (int i = 1; i < n; i++) { // If first rank and next ranks are same as // that of previous suffix in array, assign // the same new rank to this suffix if (suffixes[i].rank[0] == prev_rank && suffixes[i].rank[1] == suffixes[i-1].rank[1]) { prev_rank = suffixes[i].rank[0]; suffixes[i].rank[0] = rank; } else // Otherwise increment rank and assign { prev_rank = suffixes[i].rank[0]; suffixes[i].rank[0] = ++rank; } ind[suffixes[i].index] = i; } // Assign next rank to every suffix for (int i = 0; i < n; i++) { int nextindex = suffixes[i].index + k/2; suffixes[i].rank[1] = (nextindex < n)? suffixes[ind[nextindex]].rank[0]: -1; } // Sort the suffixes according to first k characters sort(suffixes, suffixes+n, cmp); } // Store indexes of all sorted suffixes in the suffix // array vector<int>suffixArr; for (int i = 0; i < n; i++) suffixArr.push_back(suffixes[i].index); // Return the suffix array return suffixArr;} /* To construct and return LCP */vector<int> kasai(string txt, vector<int> suffixArr){ int n = suffixArr.size(); // To store LCP array vector<int> lcp(n, 0); // An auxiliary array to store inverse of suffix array // elements. For example if suffixArr[0] is 5, the // invSuff[5] would store 0. This is used to get next // suffix string from suffix array. vector<int> invSuff(n, 0); // Fill values in invSuff[] for (int i=0; i < n; i++) invSuff[suffixArr[i]] = i; // Initialize length of previous LCP int k = 0; // Process all suffixes one by one starting from // first suffix in txt[] for (int i=0; i<n; i++) { /* If the current suffix is at n-1, then we don’t have next substring to consider. So lcp is not defined for this substring, we put zero. */ if (invSuff[i] == n-1) { k = 0; continue; } /* j contains index of the next substring to be considered to compare with the present substring, i.e., next string in suffix array */ int j = suffixArr[invSuff[i]+1]; // Directly start matching from k'th index as // at-least k-1 characters will match while (i+k<n && j+k<n && txt[i+k]==txt[j+k]) k++; lcp[invSuff[i]] = k; // lcp for the present suffix. // Deleting the starting character from the string. if (k>0) k--; } // return the constructed lcp array return lcp;} // method to return count of total distinct substringint countDistinctSubstring(string txt){ int n = txt.length(); // calculating suffix array and lcp array vector<int> suffixArr = buildSuffixArray(txt, n); vector<int> lcp = kasai(txt, suffixArr); // n - suffixArr[i] will be the length of suffix // at ith position in suffix array initializing // count with length of first suffix of sorted // suffixes int result = n - suffixArr[0]; for (int i = 1; i < lcp.size(); i++) // subtract lcp from the length of suffix result += (n - suffixArr[i]) - lcp[i - 1]; result++; // For empty string return result;} // Driver code to test above methodsint main(){ string txt = "ababa"; cout << countDistinctSubstring(txt); return 0;}
Output:
10
This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
bunnyram19
Linkedin
Suffix-Array
Trie
Advanced Data Structure
Arrays
Strings
Linkedin
Arrays
Strings
Trie
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Decision Tree Introduction with example
Red-Black Tree | Set 2 (Insert)
Disjoint Set Data Structures
Insert Operation in B-Tree
How to design a tiny URL or URL shortener?
Arrays in Java
Arrays in C/C++
Program for array rotation
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews | [
{
"code": null,
"e": 24489,
"s": 24461,
"text": "\n06 Jun, 2021"
},
{
"code": null,
"e": 24631,
"s": 24489,
"text": "Given a string of length n of lowercase alphabet characters, we need to count total number of distinct substrings of this string. Examples: "
},
{
"code": null,
"e": 24787,
"s": 24631,
"text": "Input : str = “ababa”\nOutput : 10\nTotal number of distinct substring are 10, which are,\n\"\", \"a\", \"b\", \"ab\", \"ba\", \"aba\", \"bab\", \"abab\", \"baba\"\nand \"ababa\""
},
{
"code": null,
"e": 25575,
"s": 24789,
"text": "We have discussed a Suffix Trie based solution in below post : Count of distinct substrings of a string using Suffix TrieWe can solve this problem using suffix array and longest common prefix concept. A suffix array is a sorted array of all suffixes of a given string. For string “ababa” suffixes are : “ababa”, “baba”, “aba”, “ba”, “a”. After taking these suffixes in sorted form we get our suffix array as [4, 2, 0, 3, 1] Then we calculate lcp array using kasai’s algorithm. For string “ababa”, lcp array is [1, 3, 0, 2, 0]After constructing both arrays, we calculate total number of distinct substring by keeping this fact in mind : If we look through the prefixes of each suffix of a string, we cover all substrings of that string. We will explain the procedure for above example, "
},
{
"code": null,
"e": 26567,
"s": 25575,
"text": "String = “ababa”\nSuffixes in sorted order : “a”, “aba”, “ababa”,\n “ba”, “baba”\nInitializing distinct substring count by length\nof first suffix, \nCount = length(“a”) = 1 \nSubstrings taken in consideration : “a”\n\nNow we consider each consecutive pair of suffix, \nlcp(\"a\", \"aba\") = \"a\".\nAll characters that are not part of the longest \ncommon prefix contribute to a distinct substring. \nIn the above case, they are 'b' and ‘a'. So they \nshould be added to Count.\nCount += length(“aba”) - lcp(“a”, “aba”) \nCount = 3 \nSubstrings taken in consideration : “aba”, “ab”\n\nSimilarly for next pair also,\nCount += length(“ababa”) - lcp(“aba”, “ababa”)\nCount = 5\nSubstrings taken in consideration : “ababa”, “abab”\n\nCount += length(“ba”) - lcp(“ababa”, “ba”)\nCount = 7\nSubstrings taken in consideration : “ba”, “b”\n\nCount += length(“baba”) - lcp(“ba”, “baba”)\nCount = 9\nSubstrings taken in consideration : “baba”, “bab”\n\nWe finally add 1 for empty string.\ncount = 10"
},
{
"code": null,
"e": 26610,
"s": 26567,
"text": "Above idea is implemented in below code. "
},
{
"code": null,
"e": 26614,
"s": 26610,
"text": "CPP"
},
{
"code": "// C++ code to count total distinct substrings// of a string#include <bits/stdc++.h>using namespace std; // Structure to store information of a suffixstruct suffix{ int index; // To store original index int rank[2]; // To store ranks and next // rank pair}; // A comparison function used by sort() to compare// two suffixes. Compares two pairs, returns 1 if// first pair is smallerint cmp(struct suffix a, struct suffix b){ return (a.rank[0] == b.rank[0])? (a.rank[1] < b.rank[1] ?1: 0): (a.rank[0] < b.rank[0] ?1: 0);} // This is the main function that takes a string// 'txt' of size n as an argument, builds and return// the suffix array for the given stringvector<int> buildSuffixArray(string txt, int n){ // A structure to store suffixes and their indexes struct suffix suffixes[n]; // Store suffixes and their indexes in an array // of structures. The structure is needed to sort // the suffixes alphabetically and maintain their // old indexes while sorting for (int i = 0; i < n; i++) { suffixes[i].index = i; suffixes[i].rank[0] = txt[i] - 'a'; suffixes[i].rank[1] = ((i+1) < n)? (txt[i + 1] - 'a'): -1; } // Sort the suffixes using the comparison function // defined above. sort(suffixes, suffixes+n, cmp); // At his point, all suffixes are sorted according // to first 2 characters. Let us sort suffixes // according to first 4 characters, then first // 8 and so on int ind[n]; // This array is needed to get the // index in suffixes[] from original // index. This mapping is needed to get // next suffix. for (int k = 4; k < 2*n; k = k*2) { // Assigning rank and index values to first suffix int rank = 0; int prev_rank = suffixes[0].rank[0]; suffixes[0].rank[0] = rank; ind[suffixes[0].index] = 0; // Assigning rank to suffixes for (int i = 1; i < n; i++) { // If first rank and next ranks are same as // that of previous suffix in array, assign // the same new rank to this suffix if (suffixes[i].rank[0] == prev_rank && suffixes[i].rank[1] == suffixes[i-1].rank[1]) { prev_rank = suffixes[i].rank[0]; suffixes[i].rank[0] = rank; } else // Otherwise increment rank and assign { prev_rank = suffixes[i].rank[0]; suffixes[i].rank[0] = ++rank; } ind[suffixes[i].index] = i; } // Assign next rank to every suffix for (int i = 0; i < n; i++) { int nextindex = suffixes[i].index + k/2; suffixes[i].rank[1] = (nextindex < n)? suffixes[ind[nextindex]].rank[0]: -1; } // Sort the suffixes according to first k characters sort(suffixes, suffixes+n, cmp); } // Store indexes of all sorted suffixes in the suffix // array vector<int>suffixArr; for (int i = 0; i < n; i++) suffixArr.push_back(suffixes[i].index); // Return the suffix array return suffixArr;} /* To construct and return LCP */vector<int> kasai(string txt, vector<int> suffixArr){ int n = suffixArr.size(); // To store LCP array vector<int> lcp(n, 0); // An auxiliary array to store inverse of suffix array // elements. For example if suffixArr[0] is 5, the // invSuff[5] would store 0. This is used to get next // suffix string from suffix array. vector<int> invSuff(n, 0); // Fill values in invSuff[] for (int i=0; i < n; i++) invSuff[suffixArr[i]] = i; // Initialize length of previous LCP int k = 0; // Process all suffixes one by one starting from // first suffix in txt[] for (int i=0; i<n; i++) { /* If the current suffix is at n-1, then we don’t have next substring to consider. So lcp is not defined for this substring, we put zero. */ if (invSuff[i] == n-1) { k = 0; continue; } /* j contains index of the next substring to be considered to compare with the present substring, i.e., next string in suffix array */ int j = suffixArr[invSuff[i]+1]; // Directly start matching from k'th index as // at-least k-1 characters will match while (i+k<n && j+k<n && txt[i+k]==txt[j+k]) k++; lcp[invSuff[i]] = k; // lcp for the present suffix. // Deleting the starting character from the string. if (k>0) k--; } // return the constructed lcp array return lcp;} // method to return count of total distinct substringint countDistinctSubstring(string txt){ int n = txt.length(); // calculating suffix array and lcp array vector<int> suffixArr = buildSuffixArray(txt, n); vector<int> lcp = kasai(txt, suffixArr); // n - suffixArr[i] will be the length of suffix // at ith position in suffix array initializing // count with length of first suffix of sorted // suffixes int result = n - suffixArr[0]; for (int i = 1; i < lcp.size(); i++) // subtract lcp from the length of suffix result += (n - suffixArr[i]) - lcp[i - 1]; result++; // For empty string return result;} // Driver code to test above methodsint main(){ string txt = \"ababa\"; cout << countDistinctSubstring(txt); return 0;}",
"e": 32145,
"s": 26614,
"text": null
},
{
"code": null,
"e": 32155,
"s": 32145,
"text": "Output: "
},
{
"code": null,
"e": 32158,
"s": 32155,
"text": "10"
},
{
"code": null,
"e": 32582,
"s": 32158,
"text": "This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 32593,
"s": 32582,
"text": "bunnyram19"
},
{
"code": null,
"e": 32602,
"s": 32593,
"text": "Linkedin"
},
{
"code": null,
"e": 32615,
"s": 32602,
"text": "Suffix-Array"
},
{
"code": null,
"e": 32620,
"s": 32615,
"text": "Trie"
},
{
"code": null,
"e": 32644,
"s": 32620,
"text": "Advanced Data Structure"
},
{
"code": null,
"e": 32651,
"s": 32644,
"text": "Arrays"
},
{
"code": null,
"e": 32659,
"s": 32651,
"text": "Strings"
},
{
"code": null,
"e": 32668,
"s": 32659,
"text": "Linkedin"
},
{
"code": null,
"e": 32675,
"s": 32668,
"text": "Arrays"
},
{
"code": null,
"e": 32683,
"s": 32675,
"text": "Strings"
},
{
"code": null,
"e": 32688,
"s": 32683,
"text": "Trie"
},
{
"code": null,
"e": 32786,
"s": 32688,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32795,
"s": 32786,
"text": "Comments"
},
{
"code": null,
"e": 32808,
"s": 32795,
"text": "Old Comments"
},
{
"code": null,
"e": 32848,
"s": 32808,
"text": "Decision Tree Introduction with example"
},
{
"code": null,
"e": 32880,
"s": 32848,
"text": "Red-Black Tree | Set 2 (Insert)"
},
{
"code": null,
"e": 32909,
"s": 32880,
"text": "Disjoint Set Data Structures"
},
{
"code": null,
"e": 32936,
"s": 32909,
"text": "Insert Operation in B-Tree"
},
{
"code": null,
"e": 32979,
"s": 32936,
"text": "How to design a tiny URL or URL shortener?"
},
{
"code": null,
"e": 32994,
"s": 32979,
"text": "Arrays in Java"
},
{
"code": null,
"e": 33010,
"s": 32994,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 33037,
"s": 33010,
"text": "Program for array rotation"
},
{
"code": null,
"e": 33085,
"s": 33037,
"text": "Stack Data Structure (Introduction and Program)"
}
] |
Java Examples - Detect Face in an Image | How to detect a face in an image using java.
Following is the program to detect a face in an image using java.
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfRect;
import org.opencv.core.Point;
import org.opencv.core.Rect;
import org.opencv.core.Scalar;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
import org.opencv.objdetect.CascadeClassifier;
public class DetectingFaceInAnImage {
public static void main (String[] args) {
//Loading the OpenCV core library
System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
//Reading the Image from the file and storing it in to a Matrix object
String file = "C:/opencv/facedetection_input.jpg";
Mat src = Imgcodecs.imread(file);
//Instantiating the CascadeClassifier
String xmlFile = "C:/EXAMPLES/OpenCV/facedetect/lbpcascade_frontalface.xml";
CascadeClassifier classifier = new CascadeClassifier(xmlFile);
//Detecting the face in the snap
MatOfRect faceDetections = new MatOfRect();
classifier.detectMultiScale(src, faceDetections);
System.out.println(String.format("Detected %s faces",
faceDetections.toArray().length));
//Drawing boxes
for (Rect rect : faceDetections.toArray()) {
Imgproc.rectangle(src, //where to draw the box
new Point(rect.x, rect.y), //bottom left
new Point(rect.x + rect.width, rect.y + rect.height), //top right
new Scalar(0, 0, 255),
3); //RGB color
}
//Writing the image
Imgcodecs.imwrite("C:/opencv/facedetect_output1.jpg", src);
System.out.println("Image Processed");
}
}
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2113,
"s": 2068,
"text": "How to detect a face in an image using java."
},
{
"code": null,
"e": 2179,
"s": 2113,
"text": "Following is the program to detect a face in an image using java."
},
{
"code": null,
"e": 3844,
"s": 2179,
"text": "import org.opencv.core.Core; \nimport org.opencv.core.Mat; \nimport org.opencv.core.MatOfRect; \nimport org.opencv.core.Point; \nimport org.opencv.core.Rect; \nimport org.opencv.core.Scalar; \n\nimport org.opencv.imgcodecs.Imgcodecs; \nimport org.opencv.imgproc.Imgproc; \nimport org.opencv.objdetect.CascadeClassifier; \n \npublic class DetectingFaceInAnImage { \n public static void main (String[] args) { \n \n //Loading the OpenCV core library \n System.loadLibrary( Core.NATIVE_LIBRARY_NAME ); \n\n //Reading the Image from the file and storing it in to a Matrix object \n String file = \"C:/opencv/facedetection_input.jpg\";\n Mat src = Imgcodecs.imread(file); \n \n //Instantiating the CascadeClassifier \n String xmlFile = \"C:/EXAMPLES/OpenCV/facedetect/lbpcascade_frontalface.xml\"; \n CascadeClassifier classifier = new CascadeClassifier(xmlFile); \n\n //Detecting the face in the snap \n MatOfRect faceDetections = new MatOfRect(); \n classifier.detectMultiScale(src, faceDetections); \n System.out.println(String.format(\"Detected %s faces\", \n faceDetections.toArray().length)); \n \n //Drawing boxes \n for (Rect rect : faceDetections.toArray()) { \n Imgproc.rectangle(src, //where to draw the box \n new Point(rect.x, rect.y), //bottom left \n new Point(rect.x + rect.width, rect.y + rect.height), //top right \n new Scalar(0, 0, 255), \n 3); //RGB color \n } \n //Writing the image \n Imgcodecs.imwrite(\"C:/opencv/facedetect_output1.jpg\", src); \n \n System.out.println(\"Image Processed\"); \n } \n}"
},
{
"code": null,
"e": 3851,
"s": 3844,
"text": " Print"
},
{
"code": null,
"e": 3862,
"s": 3851,
"text": " Add Notes"
}
] |
How to switch between hide and view password in Android | There are so many cases, it required to show password while entering password or after entered password. This example demonstrate about How to switch between hide and view password.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
xmlns:tools = "http://schemas.android.com/tools"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
tools:context = ".MainActivity"
android:background = "#dde4dd"
android:orientation = "vertical">
<android.support.design.widget.TextInputLayout
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:id = "@+id/layoutEmail"
android:layout_marginTop = "8dp"
android:layout_marginStart = "8dp"
android:layout_marginEnd = "8dp"
style = "@style/Widget.MaterialComponents.TextInputLayout.FilledBox">
<android.support.design.widget.TextInputEditText
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:id = "@+id/email"
android:hint = "Enter Email id"
android:inputType = "textEmailAddress"/>
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:id = "@+id/layoutPassword"
android:layout_marginTop = "8dp"
android:layout_marginStart = "8dp"
android:layout_marginEnd = "8dp"
style = "@style/Widget.MaterialComponents.TextInputLayout.FilledBox">
<android.support.design.widget.TextInputEditText
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:id = "@+id/password"
android:hint = "Password"
android:inputType = "textPassword"/>
</android.support.design.widget.TextInputLayout>
<LinearLayout
android:layout_width = "match_parent"
android:gravity = "center"
android:layout_height = "wrap_content">
<Button
android:id = "@+id/passwordVisible"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:text = "Show"></Button>
<Button
android:id = "@+id/click"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:text = "Click"></Button>
</LinearLayout>
</LinearLayout>
In the above code we have given two TextInputEditText and one button. if you click on click button it will take data from edit text and show on Toast. Or if you click on show button, it will show and hide password as per requirement.
Step 3 − Add the following code to src/MainActivity.java
package com.example.andy.myapplication;
import android.graphics.Point;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.method.PasswordTransformationMethod;
import android.view.TextureView;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
Button PasswordVisble;
EditText email,password;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
email = findViewById(R.id.email);
password = findViewById(R.id.password);
PasswordVisble = findViewById(R.id.passwordVisible);
PasswordVisble.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(password.getText().toString().isEmpty()){
password.setError("Please Enter Pass word");
} else {
if(PasswordVisble.getText().toString().equals("Show")){
PasswordVisble.setText("Hide");
password.setTransformationMethod(null);
} else {
PasswordVisble.setText("Show");
password.setTransformationMethod(new PasswordTransformationMethod());
}
}
}
});
Button click = findViewById(R.id.click);
click.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(!email.getText().toString().isEmpty()&&(!password.getText().toString().isEmpty())) {
Toast.makeText(MainActivity.this, "you have entered email id " + email.getText().toString() + "Password " + password.getText().toString(), Toast.LENGTH_LONG).show();
} else {
email.setError("Please Enter Email id");
password.setError("Please Enter Pass word");
}
}
});
}
}
To show and hide password we are using Password transformation method as shown below -
if(PasswordVisble.getText().toString().equals("Show")) {
PasswordVisble.setText("Hide");
password.setTransformationMethod(null);
} else {
PasswordVisble.setText("Show");
password.setTransformationMethod(new PasswordTransformationMethod());
}
In the above defines as
Show password: password.setTransformationMethod(null);
Hide password: password.setTransformationMethod(new PasswordTransformationMethod());
Step 4 − Open build.gradle and add design support library dependency.
apply plugin: 'com.android.application'
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.example.andy.myapplication"
minSdkVersion 15
targetSdkVersion 28
compileSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support:design:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
It is a initial screen and click on show button with enter input in password. it will show error as shown above.
Now enter some data in password edit text and clicked on show button it will show output as shown below-
Click here to download the project code | [
{
"code": null,
"e": 1244,
"s": 1062,
"text": "There are so many cases, it required to show password while entering password or after entered password. This example demonstrate about How to switch between hide and view password."
},
{
"code": null,
"e": 1373,
"s": 1244,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1438,
"s": 1373,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 3749,
"s": 1438,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n tools:context = \".MainActivity\"\n android:background = \"#dde4dd\"\n android:orientation = \"vertical\">\n <android.support.design.widget.TextInputLayout\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\"\n android:id = \"@+id/layoutEmail\"\n android:layout_marginTop = \"8dp\"\n android:layout_marginStart = \"8dp\"\n android:layout_marginEnd = \"8dp\"\n style = \"@style/Widget.MaterialComponents.TextInputLayout.FilledBox\">\n <android.support.design.widget.TextInputEditText\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\"\n android:id = \"@+id/email\"\n android:hint = \"Enter Email id\"\n android:inputType = \"textEmailAddress\"/>\n </android.support.design.widget.TextInputLayout>\n <android.support.design.widget.TextInputLayout\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\"\n android:id = \"@+id/layoutPassword\"\n android:layout_marginTop = \"8dp\"\n android:layout_marginStart = \"8dp\"\n android:layout_marginEnd = \"8dp\"\n style = \"@style/Widget.MaterialComponents.TextInputLayout.FilledBox\">\n <android.support.design.widget.TextInputEditText\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\"\n android:id = \"@+id/password\"\n android:hint = \"Password\"\n android:inputType = \"textPassword\"/>\n </android.support.design.widget.TextInputLayout>\n <LinearLayout\n android:layout_width = \"match_parent\"\n android:gravity = \"center\"\n android:layout_height = \"wrap_content\">\n <Button\n android:id = \"@+id/passwordVisible\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\"\n android:text = \"Show\"></Button>\n <Button\n android:id = \"@+id/click\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\"\n android:text = \"Click\"></Button>\n </LinearLayout>\n</LinearLayout>"
},
{
"code": null,
"e": 3983,
"s": 3749,
"text": "In the above code we have given two TextInputEditText and one button. if you click on click button it will take data from edit text and show on Toast. Or if you click on show button, it will show and hide password as per requirement."
},
{
"code": null,
"e": 4040,
"s": 3983,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 6111,
"s": 4040,
"text": "package com.example.andy.myapplication;\n\nimport android.graphics.Point;\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.text.method.PasswordTransformationMethod;\nimport android.view.TextureView;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.EditText;\nimport android.widget.TextView;\nimport android.widget.Toast;\n\npublic class MainActivity extends AppCompatActivity {\n Button PasswordVisble;\n EditText email,password;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n email = findViewById(R.id.email);\n password = findViewById(R.id.password);\n PasswordVisble = findViewById(R.id.passwordVisible);\n PasswordVisble.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n if(password.getText().toString().isEmpty()){\n password.setError(\"Please Enter Pass word\");\n } else {\n if(PasswordVisble.getText().toString().equals(\"Show\")){\n PasswordVisble.setText(\"Hide\");\n password.setTransformationMethod(null);\n } else {\n PasswordVisble.setText(\"Show\");\n password.setTransformationMethod(new PasswordTransformationMethod());\n }\n }\n }\n });\n Button click = findViewById(R.id.click);\n click.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n if(!email.getText().toString().isEmpty()&&(!password.getText().toString().isEmpty())) {\n Toast.makeText(MainActivity.this, \"you have entered email id \" + email.getText().toString() + \"Password \" + password.getText().toString(), Toast.LENGTH_LONG).show();\n } else {\n email.setError(\"Please Enter Email id\");\n password.setError(\"Please Enter Pass word\");\n }\n }\n });\n }\n}"
},
{
"code": null,
"e": 6198,
"s": 6111,
"text": "To show and hide password we are using Password transformation method as shown below -"
},
{
"code": null,
"e": 6452,
"s": 6198,
"text": "if(PasswordVisble.getText().toString().equals(\"Show\")) {\n PasswordVisble.setText(\"Hide\");\n password.setTransformationMethod(null);\n} else {\n PasswordVisble.setText(\"Show\");\n password.setTransformationMethod(new PasswordTransformationMethod());\n}"
},
{
"code": null,
"e": 6476,
"s": 6452,
"text": "In the above defines as"
},
{
"code": null,
"e": 6617,
"s": 6476,
"text": "Show password: password.setTransformationMethod(null);\n\nHide password: password.setTransformationMethod(new PasswordTransformationMethod());"
},
{
"code": null,
"e": 6687,
"s": 6617,
"text": "Step 4 − Open build.gradle and add design support library dependency."
},
{
"code": null,
"e": 7666,
"s": 6687,
"text": "apply plugin: 'com.android.application'\n\nandroid {\n compileSdkVersion 28\n defaultConfig {\n applicationId \"com.example.andy.myapplication\"\n minSdkVersion 15\n targetSdkVersion 28\n compileSdkVersion 28\n versionCode 1\n versionName \"1.0\"\n testInstrumentationRunner \"android.support.test.runner.AndroidJUnitRunner\"\n }\n buildTypes {\n release {\n minifyEnabled false\n proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'\n }\n }\n}\ndependencies {\n implementation fileTree(dir: 'libs', include: ['*.jar'])\n implementation 'com.android.support:appcompat-v7:28.0.0'\n implementation 'com.android.support:design:28.0.0'\n implementation 'com.android.support.constraint:constraint-layout:1.1.3'\n testImplementation 'junit:junit:4.12'\n androidTestImplementation 'com.android.support.test:runner:1.0.2'\n androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'\n}"
},
{
"code": null,
"e": 8013,
"s": 7666,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −"
},
{
"code": null,
"e": 8126,
"s": 8013,
"text": "It is a initial screen and click on show button with enter input in password. it will show error as shown above."
},
{
"code": null,
"e": 8231,
"s": 8126,
"text": "Now enter some data in password edit text and clicked on show button it will show output as shown below-"
},
{
"code": null,
"e": 8271,
"s": 8231,
"text": "Click here to download the project code"
}
] |
Check if a given string can be formed using characters of adjacent cells of a Matrix - GeeksforGeeks | 03 Jun, 2021
Given a matrix board of characters and a string Word, the task is to check if Word exists on the board constructed from a sequence of horizontally and vertically adjacent characters only. Each character can be used only once.
Examples:
Input: board = { {‘A’, ‘B’, ‘C’, ‘E’}, {‘S’, ‘F’, ‘C’, ‘S’}, {‘A’, ‘D’, ‘E’, ‘E’} } Word = “SEE” Output: True Explanation: “SEE” can be formed using characters at (1, 3)[S], (2, 3)[E] and (2, 2)[E].
Input: board = { {‘A’, ‘B’, ‘C’, ‘E’}, {‘S’, ‘F’, ‘C’, ‘S’}, {‘A’, ‘D’, ‘E’, ‘E’} } Word = “ABCB” Output: False Explanation: “ABCB” can not be formed by using adjacent characters without repetition.
Approach: The approach to solving this problem is to traverse all the characters in the matrix and find the occurrence of the first character of the word. Whenever found, recursively keep checking its adjacent horizontal and vertical cells for the next character. Repeat this process until all the characters are found one by one. Any instance where all the characters match signifies Word is found. If no such instance occurs, Word is not found.
Below is the implementation of the above logic:
C++
Java
Python3
C#
Javascript
// C++ Program to check if a given// word can be formed from the// adjacent characters in a matrix// of characters #include <bits/stdc++.h>using namespace std; // Function to check if the word existsbool checkWord(vector<vector<char> >& board, string& word, int index, int row, int col){ // If index exceeds board range if (row < 0 || col < 0 || row >= board.size() || col >= board[0].size()) return false; // If the current cell does not // contain the required character if (board[row][col] != word[index]) return false; // If the cell contains the required // character and is the last character // of the word required to be matched else if (index == word.size() - 1) // Return true as word is found return true; char temp = board[row][col]; // Mark cell visited board[row][col] = '*'; // Check Adjacent cells // for the next character if (checkWord(board, word, index + 1, row + 1, col) || checkWord(board, word, index + 1, row - 1, col) || checkWord(board, word, index + 1, row, col + 1) || checkWord(board, word, index + 1, row, col - 1)) { board[row][col] = temp; return true; } // Restore cell value board[row][col] = temp; return false;} // Driver Codeint main(){ vector<vector<char> > board = { { 'A', 'B', 'C', 'E' }, { 'S', 'F', 'C', 'S' }, { 'A', 'D', 'E', 'E' } }; string word = "CFDASABCESEE"; for (int i = 0; i < board.size(); i++) { for (int j = 0; j < board[0].size(); j++) { if (board[i][j] == word[0] && checkWord( board, word, 0, i, j)) { cout << "True" << '\n'; return 0; } } } cout << "False" << '\n'; return 0;}
// Java Program to check if a given// word can be formed from the// adjacent characters in a matrix// of charactersimport java.util.*;class GFG{ // Function to check if the word existsstatic boolean checkWord(char [][]board, String word, int index, int row, int col){ // If index exceeds board range if (row < 0 || col < 0 || row >= board.length || col >= board[0].length) return false; // If the current cell does not // contain the required character if (board[row][col] != word.charAt(index)) return false; // If the cell contains the required // character and is the last character // of the word required to be matched else if (index == word.length() - 1) // Return true as word is found return true; char temp = board[row][col]; // Mark cell visited board[row][col] = '*'; // Check Adjacent cells // for the next character if (checkWord(board, word, index + 1, row + 1, col) || checkWord(board, word, index + 1, row - 1, col) || checkWord(board, word, index + 1, row, col + 1) || checkWord(board, word, index + 1, row, col - 1)) { board[row][col] = temp; return true; } // Restore cell value board[row][col] = temp; return false;} // Driver Codepublic static void main(String[] args){ char[][] board = { { 'A', 'B', 'C', 'E' }, { 'S', 'F', 'C', 'S' }, { 'A', 'D', 'E', 'E' } }; String word = "CFDASABCESEE"; for (int i = 0; i < board.length; i++) { for (int j = 0; j < board[0].length; j++) { if (board[i][j] == word.charAt(0) && checkWord(board, word, 0, i, j)) { System.out.println("True"); return; } } } System.out.println("False");}} // This code is contributed by Rajput-Ji
# Python 3 Program to check if a given# word can be formed from the# adjacent characters in a matrix# of characters # Function to check if# the word existsdef checkWord(board, word, index, row, col): # If index exceeds board range if (row < 0 or col < 0 or row >= len(board) or col >= len(board[0])): return False # If the current cell does not # contain the required character if (board[row][col] != word[index]): return False # If the cell contains the required #character and is the last character # of the word required to be matched elif (index == len(word) - 1): # Return true as word is found return True temp = board[row][col] # Mark cell visited board[row][col] = '*' # Check Adjacent cells # for the next character if (checkWord(board, word, index + 1, row + 1, col) or checkWord(board, word, index + 1, row - 1, col) or checkWord(board, word, index + 1, row, col + 1) or checkWord(board, word, index + 1, row, col - 1)): board[row][col] = temp return True # Restore cell value board[row][col] = temp return False # Driver Codeif __name__ == "__main__": board = [['A', 'B', 'C', 'E'], ['S', 'F', 'C', 'S'], ['A', 'D', 'E', 'E']] word = "CFDASABCESEE" f = 0 for i in range (len(board)): for j in range (len(board[0])): if (board[i][j] == word[0] and checkWord(board, word, 0, i, j)): print ("True" ) f = 1 break if f == 1: break if f == 0: print ("False") # This code is contributed by Chitranayal
// C# program to check if a given word// can be formed from the adjacent// characters in a matrix of charactersusing System; class GFG{ // Function to check if the word existsstatic bool checkWord(char [,]board, String word, int index, int row, int col){ // If index exceeds board range if (row < 0 || col < 0 || row >= board.GetLength(0) || col >= board.GetLength(1)) return false; // If the current cell does not // contain the required character if (board[row, col] != word[index]) return false; // If the cell contains the required // character and is the last character // of the word required to be matched else if (index == word.Length - 1) // Return true as word is found return true; char temp = board[row, col]; // Mark cell visited board[row, col] = '*'; // Check adjacent cells // for the next character if (checkWord(board, word, index + 1, row + 1, col) || checkWord(board, word, index + 1, row - 1, col) || checkWord(board, word, index + 1, row, col + 1) || checkWord(board, word, index + 1, row, col - 1)) { board[row, col] = temp; return true; } // Restore cell value board[row, col] = temp; return false;} // Driver Codepublic static void Main(String[] args){ char[,] board = { { 'A', 'B', 'C', 'E' }, { 'S', 'F', 'C', 'S' }, { 'A', 'D', 'E', 'E' } }; String word = "CFDASABCESEE"; for(int i = 0; i < board.GetLength(0); i++) { for(int j = 0; j < board.GetLength(1); j++) { if (board[i, j] == word[0] && checkWord(board, word, 0, i, j)) { Console.WriteLine("True"); return; } } } Console.WriteLine("False");}} // This code is contributed by Rajput-Ji
<script> // JavaScript program to check if a given word// can be formed from the adjacent// characters in a matrix of characters // Function to check if the word existsfunction checkWord(board, word, index, row, col){ // If index exceeds board range if (row < 0 || col < 0 || row >= board.length || col >= board[0].length) return false; // If the current cell does not // contain the required character if (board[row][col] !== word[index]) return false; // If the cell contains the required // character and is the last character // of the word required to be matched else if (index === word.length - 1) // Return true as word is found return true; var temp = board[row][col]; // Mark cell visited board[row][col] = "*"; // Check adjacent cells // for the next character if (checkWord(board, word, index + 1, row + 1, col) || checkWord(board, word, index + 1, row - 1, col) || checkWord(board, word, index + 1, row, col + 1) || checkWord(board, word, index + 1, row, col - 1)) { board[row][col] = temp; return true; } // Restore cell value board[row][col] = temp; return false;} // Driver Codevar board = [ [ "A", "B", "C", "E" ], [ "S", "F", "C", "S" ], [ "A", "D", "E", "E" ],];var word = "CFDASABCESEE";var f = 0; for(var i = 0; i < board.length; i++){ for(var j = 0; j < board[0].length; j++) { if (board[i][j] === word[0] && checkWord(board, word, 0, i, j)) { document.write("True"); f = 1; } } if (f === 1) { i = board.length + 1; }}if (f === 0){ document.write("False");} // This code is contributed by rdtank </script>
True
Rajput-Ji
ukasp
rdtank
Competitive Programming
Matrix
Recursion
Strings
Strings
Recursion
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 15 Websites for Coding Challenges and Competitions
Breadth First Traversal ( BFS ) on a 2D array
Shortest path in a directed graph by Dijkstra’s algorithm
Runtime Errors
Multistage Graph (Shortest Path)
Matrix Chain Multiplication | DP-8
Program to find largest element in an array
Print a given matrix in spiral form
Rat in a Maze | Backtracking-2
Divide and Conquer | Set 5 (Strassen's Matrix Multiplication) | [
{
"code": null,
"e": 25128,
"s": 25100,
"text": "\n03 Jun, 2021"
},
{
"code": null,
"e": 25354,
"s": 25128,
"text": "Given a matrix board of characters and a string Word, the task is to check if Word exists on the board constructed from a sequence of horizontally and vertically adjacent characters only. Each character can be used only once."
},
{
"code": null,
"e": 25365,
"s": 25354,
"text": "Examples: "
},
{
"code": null,
"e": 25564,
"s": 25365,
"text": "Input: board = { {‘A’, ‘B’, ‘C’, ‘E’}, {‘S’, ‘F’, ‘C’, ‘S’}, {‘A’, ‘D’, ‘E’, ‘E’} } Word = “SEE” Output: True Explanation: “SEE” can be formed using characters at (1, 3)[S], (2, 3)[E] and (2, 2)[E]."
},
{
"code": null,
"e": 25765,
"s": 25564,
"text": "Input: board = { {‘A’, ‘B’, ‘C’, ‘E’}, {‘S’, ‘F’, ‘C’, ‘S’}, {‘A’, ‘D’, ‘E’, ‘E’} } Word = “ABCB” Output: False Explanation: “ABCB” can not be formed by using adjacent characters without repetition. "
},
{
"code": null,
"e": 26213,
"s": 25765,
"text": "Approach: The approach to solving this problem is to traverse all the characters in the matrix and find the occurrence of the first character of the word. Whenever found, recursively keep checking its adjacent horizontal and vertical cells for the next character. Repeat this process until all the characters are found one by one. Any instance where all the characters match signifies Word is found. If no such instance occurs, Word is not found. "
},
{
"code": null,
"e": 26262,
"s": 26213,
"text": "Below is the implementation of the above logic: "
},
{
"code": null,
"e": 26266,
"s": 26262,
"text": "C++"
},
{
"code": null,
"e": 26271,
"s": 26266,
"text": "Java"
},
{
"code": null,
"e": 26279,
"s": 26271,
"text": "Python3"
},
{
"code": null,
"e": 26282,
"s": 26279,
"text": "C#"
},
{
"code": null,
"e": 26293,
"s": 26282,
"text": "Javascript"
},
{
"code": "// C++ Program to check if a given// word can be formed from the// adjacent characters in a matrix// of characters #include <bits/stdc++.h>using namespace std; // Function to check if the word existsbool checkWord(vector<vector<char> >& board, string& word, int index, int row, int col){ // If index exceeds board range if (row < 0 || col < 0 || row >= board.size() || col >= board[0].size()) return false; // If the current cell does not // contain the required character if (board[row][col] != word[index]) return false; // If the cell contains the required // character and is the last character // of the word required to be matched else if (index == word.size() - 1) // Return true as word is found return true; char temp = board[row][col]; // Mark cell visited board[row][col] = '*'; // Check Adjacent cells // for the next character if (checkWord(board, word, index + 1, row + 1, col) || checkWord(board, word, index + 1, row - 1, col) || checkWord(board, word, index + 1, row, col + 1) || checkWord(board, word, index + 1, row, col - 1)) { board[row][col] = temp; return true; } // Restore cell value board[row][col] = temp; return false;} // Driver Codeint main(){ vector<vector<char> > board = { { 'A', 'B', 'C', 'E' }, { 'S', 'F', 'C', 'S' }, { 'A', 'D', 'E', 'E' } }; string word = \"CFDASABCESEE\"; for (int i = 0; i < board.size(); i++) { for (int j = 0; j < board[0].size(); j++) { if (board[i][j] == word[0] && checkWord( board, word, 0, i, j)) { cout << \"True\" << '\\n'; return 0; } } } cout << \"False\" << '\\n'; return 0;}",
"e": 28253,
"s": 26293,
"text": null
},
{
"code": "// Java Program to check if a given// word can be formed from the// adjacent characters in a matrix// of charactersimport java.util.*;class GFG{ // Function to check if the word existsstatic boolean checkWord(char [][]board, String word, int index, int row, int col){ // If index exceeds board range if (row < 0 || col < 0 || row >= board.length || col >= board[0].length) return false; // If the current cell does not // contain the required character if (board[row][col] != word.charAt(index)) return false; // If the cell contains the required // character and is the last character // of the word required to be matched else if (index == word.length() - 1) // Return true as word is found return true; char temp = board[row][col]; // Mark cell visited board[row][col] = '*'; // Check Adjacent cells // for the next character if (checkWord(board, word, index + 1, row + 1, col) || checkWord(board, word, index + 1, row - 1, col) || checkWord(board, word, index + 1, row, col + 1) || checkWord(board, word, index + 1, row, col - 1)) { board[row][col] = temp; return true; } // Restore cell value board[row][col] = temp; return false;} // Driver Codepublic static void main(String[] args){ char[][] board = { { 'A', 'B', 'C', 'E' }, { 'S', 'F', 'C', 'S' }, { 'A', 'D', 'E', 'E' } }; String word = \"CFDASABCESEE\"; for (int i = 0; i < board.length; i++) { for (int j = 0; j < board[0].length; j++) { if (board[i][j] == word.charAt(0) && checkWord(board, word, 0, i, j)) { System.out.println(\"True\"); return; } } } System.out.println(\"False\");}} // This code is contributed by Rajput-Ji",
"e": 30251,
"s": 28253,
"text": null
},
{
"code": "# Python 3 Program to check if a given# word can be formed from the# adjacent characters in a matrix# of characters # Function to check if# the word existsdef checkWord(board, word, index, row, col): # If index exceeds board range if (row < 0 or col < 0 or row >= len(board) or col >= len(board[0])): return False # If the current cell does not # contain the required character if (board[row][col] != word[index]): return False # If the cell contains the required #character and is the last character # of the word required to be matched elif (index == len(word) - 1): # Return true as word is found return True temp = board[row][col] # Mark cell visited board[row][col] = '*' # Check Adjacent cells # for the next character if (checkWord(board, word, index + 1, row + 1, col) or checkWord(board, word, index + 1, row - 1, col) or checkWord(board, word, index + 1, row, col + 1) or checkWord(board, word, index + 1, row, col - 1)): board[row][col] = temp return True # Restore cell value board[row][col] = temp return False # Driver Codeif __name__ == \"__main__\": board = [['A', 'B', 'C', 'E'], ['S', 'F', 'C', 'S'], ['A', 'D', 'E', 'E']] word = \"CFDASABCESEE\" f = 0 for i in range (len(board)): for j in range (len(board[0])): if (board[i][j] == word[0] and checkWord(board, word, 0, i, j)): print (\"True\" ) f = 1 break if f == 1: break if f == 0: print (\"False\") # This code is contributed by Chitranayal",
"e": 32128,
"s": 30251,
"text": null
},
{
"code": "// C# program to check if a given word// can be formed from the adjacent// characters in a matrix of charactersusing System; class GFG{ // Function to check if the word existsstatic bool checkWord(char [,]board, String word, int index, int row, int col){ // If index exceeds board range if (row < 0 || col < 0 || row >= board.GetLength(0) || col >= board.GetLength(1)) return false; // If the current cell does not // contain the required character if (board[row, col] != word[index]) return false; // If the cell contains the required // character and is the last character // of the word required to be matched else if (index == word.Length - 1) // Return true as word is found return true; char temp = board[row, col]; // Mark cell visited board[row, col] = '*'; // Check adjacent cells // for the next character if (checkWord(board, word, index + 1, row + 1, col) || checkWord(board, word, index + 1, row - 1, col) || checkWord(board, word, index + 1, row, col + 1) || checkWord(board, word, index + 1, row, col - 1)) { board[row, col] = temp; return true; } // Restore cell value board[row, col] = temp; return false;} // Driver Codepublic static void Main(String[] args){ char[,] board = { { 'A', 'B', 'C', 'E' }, { 'S', 'F', 'C', 'S' }, { 'A', 'D', 'E', 'E' } }; String word = \"CFDASABCESEE\"; for(int i = 0; i < board.GetLength(0); i++) { for(int j = 0; j < board.GetLength(1); j++) { if (board[i, j] == word[0] && checkWord(board, word, 0, i, j)) { Console.WriteLine(\"True\"); return; } } } Console.WriteLine(\"False\");}} // This code is contributed by Rajput-Ji",
"e": 34081,
"s": 32128,
"text": null
},
{
"code": "<script> // JavaScript program to check if a given word// can be formed from the adjacent// characters in a matrix of characters // Function to check if the word existsfunction checkWord(board, word, index, row, col){ // If index exceeds board range if (row < 0 || col < 0 || row >= board.length || col >= board[0].length) return false; // If the current cell does not // contain the required character if (board[row][col] !== word[index]) return false; // If the cell contains the required // character and is the last character // of the word required to be matched else if (index === word.length - 1) // Return true as word is found return true; var temp = board[row][col]; // Mark cell visited board[row][col] = \"*\"; // Check adjacent cells // for the next character if (checkWord(board, word, index + 1, row + 1, col) || checkWord(board, word, index + 1, row - 1, col) || checkWord(board, word, index + 1, row, col + 1) || checkWord(board, word, index + 1, row, col - 1)) { board[row][col] = temp; return true; } // Restore cell value board[row][col] = temp; return false;} // Driver Codevar board = [ [ \"A\", \"B\", \"C\", \"E\" ], [ \"S\", \"F\", \"C\", \"S\" ], [ \"A\", \"D\", \"E\", \"E\" ],];var word = \"CFDASABCESEE\";var f = 0; for(var i = 0; i < board.length; i++){ for(var j = 0; j < board[0].length; j++) { if (board[i][j] === word[0] && checkWord(board, word, 0, i, j)) { document.write(\"True\"); f = 1; } } if (f === 1) { i = board.length + 1; }}if (f === 0){ document.write(\"False\");} // This code is contributed by rdtank </script>",
"e": 35965,
"s": 34081,
"text": null
},
{
"code": null,
"e": 35970,
"s": 35965,
"text": "True"
},
{
"code": null,
"e": 35982,
"s": 35972,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 35988,
"s": 35982,
"text": "ukasp"
},
{
"code": null,
"e": 35995,
"s": 35988,
"text": "rdtank"
},
{
"code": null,
"e": 36019,
"s": 35995,
"text": "Competitive Programming"
},
{
"code": null,
"e": 36026,
"s": 36019,
"text": "Matrix"
},
{
"code": null,
"e": 36036,
"s": 36026,
"text": "Recursion"
},
{
"code": null,
"e": 36044,
"s": 36036,
"text": "Strings"
},
{
"code": null,
"e": 36052,
"s": 36044,
"text": "Strings"
},
{
"code": null,
"e": 36062,
"s": 36052,
"text": "Recursion"
},
{
"code": null,
"e": 36069,
"s": 36062,
"text": "Matrix"
},
{
"code": null,
"e": 36167,
"s": 36069,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36222,
"s": 36167,
"text": "Top 15 Websites for Coding Challenges and Competitions"
},
{
"code": null,
"e": 36268,
"s": 36222,
"text": "Breadth First Traversal ( BFS ) on a 2D array"
},
{
"code": null,
"e": 36326,
"s": 36268,
"text": "Shortest path in a directed graph by Dijkstra’s algorithm"
},
{
"code": null,
"e": 36341,
"s": 36326,
"text": "Runtime Errors"
},
{
"code": null,
"e": 36374,
"s": 36341,
"text": "Multistage Graph (Shortest Path)"
},
{
"code": null,
"e": 36409,
"s": 36374,
"text": "Matrix Chain Multiplication | DP-8"
},
{
"code": null,
"e": 36453,
"s": 36409,
"text": "Program to find largest element in an array"
},
{
"code": null,
"e": 36489,
"s": 36453,
"text": "Print a given matrix in spiral form"
},
{
"code": null,
"e": 36520,
"s": 36489,
"text": "Rat in a Maze | Backtracking-2"
}
] |
EasyGUI – Code Box - GeeksforGeeks | 14 Mar, 2022
Code Box : It is used to show and get the text to/from the user which is in form of code i.e not in word-wrap form, text can be edited using any keyboard input, it takes input in form of string. It displays the title, message to be displayed, place to alter the given text and a pair of “Ok”, “Cancel” button which is used confirm the text. It is similar to text box but used to show code text, below is how the enter box looks like
In order to do this we will use codebox methodSyntax : codebox(message, title, text)Argument : It takes 3 arguments, first string i.e message/information to be displayed, second string i.e title of the window and third is string which is the editable textReturn : It returns the altered text and None if cancel is pressed
Example : In this we will create a code box with editable text, and will show the specific text on the screen according to the altered text, below is the implementation
Python3
# importing easygui modulefrom easygui import * # message to be displayedmessage = "Below is the text to edit" # window titletitle = "Window Title GfG" # long code texttext = """<gfg> EasyGUIis a module for very simple,very easy GUI programming in Python.EasyGUIis different from otherGUI generatorsin that EasyGUI is NOT event-driven. </gfg>""" # creating a code boxoutput = codebox(message, title, text) # showing the outputprint("Altered Text ")print("================")print(output)
Output :
Altered Text
================
'gfg>
great
EasyGUI module
is a module for very simple,
very easy GUI programming in Python.
EasyGUI
is different from otherGUI generators
in that EasyGUI is NOT event-driven.
'/gfg>
Another Example : In this we will create a code box without editable text, and will show the specific text on the screen according to the altered text, below is the implementation
Python3
# importing easygui modulefrom easygui import * # message to be displayedmessage = "Below is the text to edit" # window titletitle = "Window Title GfG" # creating a code boxoutput = codebox(message, title) # showing the outputprint("Altered Text ")print("================")print(output)
Output :
Altered Text
================
gfg
a
b
v
c
c
c
/gfg
sumitgumber28
Python-EasyGUI
Python-gui
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Create a Pandas DataFrame from Lists
sum() function in Python
*args and **kwargs in Python
How to drop one or multiple columns in Pandas Dataframe
Convert integer to string in Python
Print lists in Python (4 Different Ways) | [
{
"code": null,
"e": 24834,
"s": 24806,
"text": "\n14 Mar, 2022"
},
{
"code": null,
"e": 25269,
"s": 24834,
"text": "Code Box : It is used to show and get the text to/from the user which is in form of code i.e not in word-wrap form, text can be edited using any keyboard input, it takes input in form of string. It displays the title, message to be displayed, place to alter the given text and a pair of “Ok”, “Cancel” button which is used confirm the text. It is similar to text box but used to show code text, below is how the enter box looks like "
},
{
"code": null,
"e": 25595,
"s": 25271,
"text": "In order to do this we will use codebox methodSyntax : codebox(message, title, text)Argument : It takes 3 arguments, first string i.e message/information to be displayed, second string i.e title of the window and third is string which is the editable textReturn : It returns the altered text and None if cancel is pressed "
},
{
"code": null,
"e": 25766,
"s": 25595,
"text": "Example : In this we will create a code box with editable text, and will show the specific text on the screen according to the altered text, below is the implementation "
},
{
"code": null,
"e": 25774,
"s": 25766,
"text": "Python3"
},
{
"code": "# importing easygui modulefrom easygui import * # message to be displayedmessage = \"Below is the text to edit\" # window titletitle = \"Window Title GfG\" # long code texttext = \"\"\"<gfg> EasyGUIis a module for very simple,very easy GUI programming in Python.EasyGUIis different from otherGUI generatorsin that EasyGUI is NOT event-driven. </gfg>\"\"\" # creating a code boxoutput = codebox(message, title, text) # showing the outputprint(\"Altered Text \")print(\"================\")print(output)",
"e": 26269,
"s": 25774,
"text": null
},
{
"code": null,
"e": 26280,
"s": 26269,
"text": "Output : "
},
{
"code": null,
"e": 26499,
"s": 26282,
"text": "Altered Text \n================\n'gfg>\ngreat\nEasyGUI module\nis a module for very simple,\nvery easy GUI programming in Python.\nEasyGUI \nis different from otherGUI generators \nin that EasyGUI is NOT event-driven.\n\n'/gfg>"
},
{
"code": null,
"e": 26681,
"s": 26499,
"text": "Another Example : In this we will create a code box without editable text, and will show the specific text on the screen according to the altered text, below is the implementation "
},
{
"code": null,
"e": 26689,
"s": 26681,
"text": "Python3"
},
{
"code": "# importing easygui modulefrom easygui import * # message to be displayedmessage = \"Below is the text to edit\" # window titletitle = \"Window Title GfG\" # creating a code boxoutput = codebox(message, title) # showing the outputprint(\"Altered Text \")print(\"================\")print(output)",
"e": 26976,
"s": 26689,
"text": null
},
{
"code": null,
"e": 26987,
"s": 26976,
"text": "Output : "
},
{
"code": null,
"e": 27043,
"s": 26989,
"text": "Altered Text \n================\ngfg\na\nb\nv\nc\nc\nc\n\n\n/gfg"
},
{
"code": null,
"e": 27059,
"s": 27045,
"text": "sumitgumber28"
},
{
"code": null,
"e": 27074,
"s": 27059,
"text": "Python-EasyGUI"
},
{
"code": null,
"e": 27085,
"s": 27074,
"text": "Python-gui"
},
{
"code": null,
"e": 27092,
"s": 27085,
"text": "Python"
},
{
"code": null,
"e": 27190,
"s": 27092,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27199,
"s": 27190,
"text": "Comments"
},
{
"code": null,
"e": 27212,
"s": 27199,
"text": "Old Comments"
},
{
"code": null,
"e": 27230,
"s": 27212,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27252,
"s": 27230,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27284,
"s": 27252,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27326,
"s": 27284,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27363,
"s": 27326,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 27388,
"s": 27363,
"text": "sum() function in Python"
},
{
"code": null,
"e": 27417,
"s": 27388,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 27473,
"s": 27417,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27509,
"s": 27473,
"text": "Convert integer to string in Python"
}
] |
Stratified K Fold Cross Validation - GeeksforGeeks | 27 Apr, 2022
In machine learning, When we want to train our ML model we split our entire dataset into training_set and test_set using train_test_split() class present in sklearn. Then we train our model on training_set and test our model on test_set. The problems that we are going to face in this method are:
Whenever we change the random_state parameter present in train_test_split(), We get different accuracy for different random_state and hence we can’t exactly point out the accuracy for our model. The train_test_split() splits the dataset into training_test and test_set by random sampling. But stratified sampling is performed.
What are random sampling and Stratified sampling? Suppose you want to take a survey and decided to call 1000 people from a particular state, If you pick either 1000 males completely or 1000 females completely or 900 females and 100 males (randomly) to ask their opinion on a particular product. Then based on these 1000 opinions you can’t decide the opinion of that entire state on your product. This is random sampling.But in Stratified Sampling, Let the population for that state be 51.3% male and 48.7% female, Then for choosing 1000 people from that state if you pick 513 male ( 51.3% of 1000 ) and 487 female ( 48.7% for 1000 ) i.e 513 male + 487 female (Total=1000 people) to ask their opinion. Then these groups of people represent the entire state. This is called Stratified Sampling.
Why random sampling is not preferred in machine learning? Let’s consider a binary-class classification problem. Let our dataset consists of 100 samples out of which 80 are negative class { 0 } and 20 are positive class { 1 }.
Random sampling: If we do random sampling to split the dataset into training_set and test_set in an 8:2 ratio respectively.Then we might get all negative class {0} in training_set i.e 80 samples in training_test and all 20 positive class {1} in test_set.Now if we train our model on training_set and test our model on test_set, Then obviously we will get a bad accuracy score.
Stratified Sampling: In stratified sampling, The training_set consists of 64 negative class{0} ( 80% 0f 80 ) and 16 positive class {1} ( 80% of 20 ) i.e. 64{0}+16{1}=80 samples in training_set which represents the original dataset in equal proportion and similarly test_set consists of 16 negative class {0} ( 20% of 80 ) and 4 positive class{1} ( 20% of 20 ) i.e. 16{0}+4{1}=20 samples in test_set which also represents the entire dataset in equal proportion.This type of train-test-split results in good accuracy.
What is the solution to mentioned problems? The solution for the first problem where we were able to get different accuracy scores for different random_state parameter values is to use K-Fold Cross-Validation. But K-Fold Cross Validation also suffers from the second problem i.e. random sampling.The solution for both the first and second problems is to use Stratified K-Fold Cross-Validation.
What is Stratified K-Fold Cross Validation? Stratified k-fold cross-validation is the same as just k-fold cross-validation, But Stratified k-fold cross-validation, it does stratified sampling instead of random sampling.
Code: Python code implementation of Stratified K-Fold Cross-Validation
Python3
# This code may not be run on GFG IDE # as required packages are not found. # STRATIFIES K-FOLD CROSS VALIDATION { 10-fold } # Import Required Modules.from statistics import mean, stdevfrom sklearn import preprocessingfrom sklearn.model_selection import StratifiedKFoldfrom sklearn import linear_modelfrom sklearn import datasets # FEATCHING FEATURES AND TARGET VARIABLES IN ARRAY FORMAT.cancer = datasets.load_breast_cancer()# Input_x_Features.x = cancer.data # Input_ y_Target_Variable.y = cancer.target # Feature Scaling for input features.scaler = preprocessing.MinMaxScaler()x_scaled = scaler.fit_transform(x) # Create classifier object.lr = linear_model.LogisticRegression() # Create StratifiedKFold object.skf = StratifiedKFold(n_splits=10, shuffle=True, random_state=1)lst_accu_stratified = [] for train_index, test_index in skf.split(x, y): x_train_fold, x_test_fold = x_scaled[train_index], x_scaled[test_index] y_train_fold, y_test_fold = y[train_index], y[test_index] lr.fit(x_train_fold, y_train_fold) lst_accu_stratified.append(lr.score(x_test_fold, y_test_fold)) # Print the output.print('List of possible accuracy:', lst_accu_stratified)print('\nMaximum Accuracy That can be obtained from this model is:', max(lst_accu_stratified)*100, '%')print('\nMinimum Accuracy:', min(lst_accu_stratified)*100, '%')print('\nOverall Accuracy:', mean(lst_accu_stratified)*100, '%')print('\nStandard Deviation is:', stdev(lst_accu_stratified))
Output:
List of possible accuracy: [0.9298245614035088, 0.9649122807017544, 0.9824561403508771, 1.0, 0.9649122807017544, 0.9649122807017544, 0.9824561403508771, 0.9473684210526315, 0.9473684210526315, 0.9821428571428571]
Maximum Accuracy That can be obtained from this model is: 100.0 %
Minimum Accuracy That can be obtained from this model is: 92.98245614035088 %
The overall Accuracy of this model is: 96.66353383458647 %
The Standard Deviation is: 0.02097789213195869
simmytarika5
ericgustin44
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Support Vector Machine Algorithm
k-nearest neighbor algorithm in Python
Intuition of Adam Optimizer
Singular Value Decomposition (SVD)
ML | Logistic Regression using 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": 24368,
"s": 24340,
"text": "\n27 Apr, 2022"
},
{
"code": null,
"e": 24665,
"s": 24368,
"text": "In machine learning, When we want to train our ML model we split our entire dataset into training_set and test_set using train_test_split() class present in sklearn. Then we train our model on training_set and test our model on test_set. The problems that we are going to face in this method are:"
},
{
"code": null,
"e": 24992,
"s": 24665,
"text": "Whenever we change the random_state parameter present in train_test_split(), We get different accuracy for different random_state and hence we can’t exactly point out the accuracy for our model. The train_test_split() splits the dataset into training_test and test_set by random sampling. But stratified sampling is performed."
},
{
"code": null,
"e": 25785,
"s": 24992,
"text": "What are random sampling and Stratified sampling? Suppose you want to take a survey and decided to call 1000 people from a particular state, If you pick either 1000 males completely or 1000 females completely or 900 females and 100 males (randomly) to ask their opinion on a particular product. Then based on these 1000 opinions you can’t decide the opinion of that entire state on your product. This is random sampling.But in Stratified Sampling, Let the population for that state be 51.3% male and 48.7% female, Then for choosing 1000 people from that state if you pick 513 male ( 51.3% of 1000 ) and 487 female ( 48.7% for 1000 ) i.e 513 male + 487 female (Total=1000 people) to ask their opinion. Then these groups of people represent the entire state. This is called Stratified Sampling."
},
{
"code": null,
"e": 26011,
"s": 25785,
"text": "Why random sampling is not preferred in machine learning? Let’s consider a binary-class classification problem. Let our dataset consists of 100 samples out of which 80 are negative class { 0 } and 20 are positive class { 1 }."
},
{
"code": null,
"e": 26388,
"s": 26011,
"text": "Random sampling: If we do random sampling to split the dataset into training_set and test_set in an 8:2 ratio respectively.Then we might get all negative class {0} in training_set i.e 80 samples in training_test and all 20 positive class {1} in test_set.Now if we train our model on training_set and test our model on test_set, Then obviously we will get a bad accuracy score."
},
{
"code": null,
"e": 26904,
"s": 26388,
"text": "Stratified Sampling: In stratified sampling, The training_set consists of 64 negative class{0} ( 80% 0f 80 ) and 16 positive class {1} ( 80% of 20 ) i.e. 64{0}+16{1}=80 samples in training_set which represents the original dataset in equal proportion and similarly test_set consists of 16 negative class {0} ( 20% of 80 ) and 4 positive class{1} ( 20% of 20 ) i.e. 16{0}+4{1}=20 samples in test_set which also represents the entire dataset in equal proportion.This type of train-test-split results in good accuracy."
},
{
"code": null,
"e": 27298,
"s": 26904,
"text": "What is the solution to mentioned problems? The solution for the first problem where we were able to get different accuracy scores for different random_state parameter values is to use K-Fold Cross-Validation. But K-Fold Cross Validation also suffers from the second problem i.e. random sampling.The solution for both the first and second problems is to use Stratified K-Fold Cross-Validation."
},
{
"code": null,
"e": 27518,
"s": 27298,
"text": "What is Stratified K-Fold Cross Validation? Stratified k-fold cross-validation is the same as just k-fold cross-validation, But Stratified k-fold cross-validation, it does stratified sampling instead of random sampling."
},
{
"code": null,
"e": 27591,
"s": 27518,
"text": "Code: Python code implementation of Stratified K-Fold Cross-Validation "
},
{
"code": null,
"e": 27599,
"s": 27591,
"text": "Python3"
},
{
"code": "# This code may not be run on GFG IDE # as required packages are not found. # STRATIFIES K-FOLD CROSS VALIDATION { 10-fold } # Import Required Modules.from statistics import mean, stdevfrom sklearn import preprocessingfrom sklearn.model_selection import StratifiedKFoldfrom sklearn import linear_modelfrom sklearn import datasets # FEATCHING FEATURES AND TARGET VARIABLES IN ARRAY FORMAT.cancer = datasets.load_breast_cancer()# Input_x_Features.x = cancer.data # Input_ y_Target_Variable.y = cancer.target # Feature Scaling for input features.scaler = preprocessing.MinMaxScaler()x_scaled = scaler.fit_transform(x) # Create classifier object.lr = linear_model.LogisticRegression() # Create StratifiedKFold object.skf = StratifiedKFold(n_splits=10, shuffle=True, random_state=1)lst_accu_stratified = [] for train_index, test_index in skf.split(x, y): x_train_fold, x_test_fold = x_scaled[train_index], x_scaled[test_index] y_train_fold, y_test_fold = y[train_index], y[test_index] lr.fit(x_train_fold, y_train_fold) lst_accu_stratified.append(lr.score(x_test_fold, y_test_fold)) # Print the output.print('List of possible accuracy:', lst_accu_stratified)print('\\nMaximum Accuracy That can be obtained from this model is:', max(lst_accu_stratified)*100, '%')print('\\nMinimum Accuracy:', min(lst_accu_stratified)*100, '%')print('\\nOverall Accuracy:', mean(lst_accu_stratified)*100, '%')print('\\nStandard Deviation is:', stdev(lst_accu_stratified))",
"e": 29132,
"s": 27599,
"text": null
},
{
"code": null,
"e": 29141,
"s": 29132,
"text": "Output: "
},
{
"code": null,
"e": 29608,
"s": 29141,
"text": "List of possible accuracy: [0.9298245614035088, 0.9649122807017544, 0.9824561403508771, 1.0, 0.9649122807017544, 0.9649122807017544, 0.9824561403508771, 0.9473684210526315, 0.9473684210526315, 0.9821428571428571]\n\nMaximum Accuracy That can be obtained from this model is: 100.0 %\n\nMinimum Accuracy That can be obtained from this model is: 92.98245614035088 %\n\nThe overall Accuracy of this model is: 96.66353383458647 %\n\nThe Standard Deviation is: 0.02097789213195869"
},
{
"code": null,
"e": 29623,
"s": 29610,
"text": "simmytarika5"
},
{
"code": null,
"e": 29636,
"s": 29623,
"text": "ericgustin44"
},
{
"code": null,
"e": 29653,
"s": 29636,
"text": "Machine Learning"
},
{
"code": null,
"e": 29660,
"s": 29653,
"text": "Python"
},
{
"code": null,
"e": 29677,
"s": 29660,
"text": "Machine Learning"
},
{
"code": null,
"e": 29775,
"s": 29677,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29808,
"s": 29775,
"text": "Support Vector Machine Algorithm"
},
{
"code": null,
"e": 29847,
"s": 29808,
"text": "k-nearest neighbor algorithm in Python"
},
{
"code": null,
"e": 29875,
"s": 29847,
"text": "Intuition of Adam Optimizer"
},
{
"code": null,
"e": 29910,
"s": 29875,
"text": "Singular Value Decomposition (SVD)"
},
{
"code": null,
"e": 29948,
"s": 29910,
"text": "ML | Logistic Regression using Python"
},
{
"code": null,
"e": 29976,
"s": 29948,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 30026,
"s": 29976,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 30048,
"s": 30026,
"text": "Python map() function"
}
] |
What is the difference between Trim() and TrimStart() methods in C#? | A string method that removes all the leading and trailing whitespaces in a string.
For example, the string “jack sparrow“ would be returned as the following without leading and whitespaces using trim().
jack sparrow
The following is an example −
Live Demo
using System;
namespace Demo {
class Program {
static void Main(string[] args) {
string str = " Amit ";
Console.WriteLine(str);
// trim
Console.WriteLine("After removing leading and trailing whitespace...");
string res = str.Trim();
Console.WriteLine(res);
Console.ReadKey();
}
}
}
Amit
After removing leading and trailing whitespace...
Amit
The TrimStart() method removes all leading occurrences of a set of characters specified in an array.
Let us see an example to remove all leading zeros −
Live Demo
using System;
class Program {
static void Main() {
String str ="0009678".TrimStart(new Char[] { '0' } );
Console.WriteLine(str);
}
}
9678 | [
{
"code": null,
"e": 1145,
"s": 1062,
"text": "A string method that removes all the leading and trailing whitespaces in a string."
},
{
"code": null,
"e": 1265,
"s": 1145,
"text": "For example, the string “jack sparrow“ would be returned as the following without leading and whitespaces using trim()."
},
{
"code": null,
"e": 1278,
"s": 1265,
"text": "jack sparrow"
},
{
"code": null,
"e": 1308,
"s": 1278,
"text": "The following is an example −"
},
{
"code": null,
"e": 1319,
"s": 1308,
"text": " Live Demo"
},
{
"code": null,
"e": 1685,
"s": 1319,
"text": "using System;\nnamespace Demo {\n class Program {\n static void Main(string[] args) {\n\n string str = \" Amit \";\n Console.WriteLine(str);\n\n // trim\n Console.WriteLine(\"After removing leading and trailing whitespace...\");\n string res = str.Trim();\n Console.WriteLine(res);\n\n Console.ReadKey();\n }\n }\n}"
},
{
"code": null,
"e": 1745,
"s": 1685,
"text": "Amit\nAfter removing leading and trailing whitespace...\nAmit"
},
{
"code": null,
"e": 1846,
"s": 1745,
"text": "The TrimStart() method removes all leading occurrences of a set of characters specified in an array."
},
{
"code": null,
"e": 1898,
"s": 1846,
"text": "Let us see an example to remove all leading zeros −"
},
{
"code": null,
"e": 1909,
"s": 1898,
"text": " Live Demo"
},
{
"code": null,
"e": 2060,
"s": 1909,
"text": "using System;\nclass Program {\n static void Main() {\n String str =\"0009678\".TrimStart(new Char[] { '0' } );\n Console.WriteLine(str);\n }\n}"
},
{
"code": null,
"e": 2065,
"s": 2060,
"text": "9678"
}
] |
Calculating Wind Chill Factor(WCF) or Wind Chill Index(WCI) in Python - GeeksforGeeks | 07 Feb, 2018
Wind-chill or Windchill is the perceived decrease in air temperature felt by the body on exposed skin due to the flow of air. The effect of wind chill is to increase the rate of heat loss and reduce any warmer objects to the ambient temperature more quickly.Here is the standard formula that was adopted in 2001 by Canada, UK, and the US to compute and analyze the Wind Chill Index:
Twc(WCI) = 13.12 + 0.6215Ta – 11.37v+0.16 + 0.3965Tav+0.16where
Twc = Wind Chill Index (Based on Celsius temperature scale)Ta = Air Temperature (in degree Celsius)v = Wind Speed (in miles per hour)
Examples:
Input:
Air Temperature = 28
Wind Speed = 80
Output: 30
Calculation done using the above formula:
WCI = 13.12 + 0.6215 * (28) -
11.37 * (80)**0.16 +
0.3965 * 28 * 80**0.16
Input:
Air Temperature = 42
Wind Speed = 150
Output: 51
Calculation done using the above formula:
WCI = 13.12 + 0.6215 * (42) -
11.37 * (150)**0.16 +
0.3965 * 42 * 150**0.16
# Python program to calculate WCIimport math # funtion to calculate WCIdef WC(temp, wi_sp): # Calculating Wind Chill Index (Twc) wci = 13.12+0.6215*temp- 11.37*math.pow(wi_sp, 0.16) + \ 0.3965*temp*math.pow(wi_sp, 0.16) return wci # Taking the Air Temperature (Ta) temp = 42 # Taking the Wind Speed (v) wi_sp = 150 print("The Wind Chill Index is", int(round(WC(temp, wi_sp))))
Output:
The Wind Chill Index is 51
This article is contributed by Chinmoy Lenka. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Selecting rows in pandas DataFrame based on conditions
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Defaultdict in Python
Python | Split string into list of characters
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python program to check whether a number is Prime or not | [
{
"code": null,
"e": 24317,
"s": 24289,
"text": "\n07 Feb, 2018"
},
{
"code": null,
"e": 24700,
"s": 24317,
"text": "Wind-chill or Windchill is the perceived decrease in air temperature felt by the body on exposed skin due to the flow of air. The effect of wind chill is to increase the rate of heat loss and reduce any warmer objects to the ambient temperature more quickly.Here is the standard formula that was adopted in 2001 by Canada, UK, and the US to compute and analyze the Wind Chill Index:"
},
{
"code": null,
"e": 24764,
"s": 24700,
"text": "Twc(WCI) = 13.12 + 0.6215Ta – 11.37v+0.16 + 0.3965Tav+0.16where"
},
{
"code": null,
"e": 24898,
"s": 24764,
"text": "Twc = Wind Chill Index (Based on Celsius temperature scale)Ta = Air Temperature (in degree Celsius)v = Wind Speed (in miles per hour)"
},
{
"code": null,
"e": 24908,
"s": 24898,
"text": "Examples:"
},
{
"code": null,
"e": 25095,
"s": 24908,
"text": "Input: \nAir Temperature = 28\nWind Speed = 80\nOutput: 30\nCalculation done using the above formula:\nWCI = 13.12 + 0.6215 * (28) - \n 11.37 * (80)**0.16 + \n 0.3965 * 28 * 80**0.16\n"
},
{
"code": null,
"e": 25285,
"s": 25095,
"text": "Input: \nAir Temperature = 42\nWind Speed = 150\nOutput: 51\nCalculation done using the above formula:\nWCI = 13.12 + 0.6215 * (42) - \n 11.37 * (150)**0.16 + \n 0.3965 * 42 * 150**0.16\n"
},
{
"code": "# Python program to calculate WCIimport math # funtion to calculate WCIdef WC(temp, wi_sp): # Calculating Wind Chill Index (Twc) wci = 13.12+0.6215*temp- 11.37*math.pow(wi_sp, 0.16) + \\ 0.3965*temp*math.pow(wi_sp, 0.16) return wci # Taking the Air Temperature (Ta) temp = 42 # Taking the Wind Speed (v) wi_sp = 150 print(\"The Wind Chill Index is\", int(round(WC(temp, wi_sp))))",
"e": 25694,
"s": 25285,
"text": null
},
{
"code": null,
"e": 25702,
"s": 25694,
"text": "Output:"
},
{
"code": null,
"e": 25730,
"s": 25702,
"text": "The Wind Chill Index is 51\n"
},
{
"code": null,
"e": 26031,
"s": 25730,
"text": "This article is contributed by Chinmoy Lenka. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 26156,
"s": 26031,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 26163,
"s": 26156,
"text": "Python"
},
{
"code": null,
"e": 26179,
"s": 26163,
"text": "Python Programs"
},
{
"code": null,
"e": 26277,
"s": 26179,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26286,
"s": 26277,
"text": "Comments"
},
{
"code": null,
"e": 26299,
"s": 26286,
"text": "Old Comments"
},
{
"code": null,
"e": 26331,
"s": 26299,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26387,
"s": 26331,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26442,
"s": 26387,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 26484,
"s": 26442,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26526,
"s": 26484,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26548,
"s": 26526,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26594,
"s": 26548,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 26633,
"s": 26594,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 26671,
"s": 26633,
"text": "Python | Convert a list to dictionary"
}
] |
Difference Between getPath() and getAbsolutePath() in Java - GeeksforGeeks | 04 Jan, 2021
getPath(): The getPath() method is a part of File class. This function returns the path of the given file object. The function returns a string object which contains the path of the given file object.
Return Type:
The string form of an abstract pathname
getAbsolutePath(): The getAbsolutePath() returns a path object representing the absolute path of given path. If the given pathname is already absolute, then the pathname string is simply returned as if by the getPath() method. If the current abstract pathname is the empty abstract pathname then the pathname string of the current user directory(named by the system property) is returned. Else, this pathname is resolved in a system-dependent way.
On Unix’s System:
A relative pathname is made absolute by resolving it against the current user directory.
On Microsoft System:
A relative pathname is made absolute by resolving it against the current directory of the drive named by the pathname, it is resolved against the current user directory.
Returns:
The absolute pathname string denoting the same file or directory as this abstract pathname
This method returns a string which denotes the (absolute or relative) pathname of the file represented by the file object.
This method returns the absolute pathname string of abstract file pathname.
If the file object is created using an absolute path then the path returned is an absolute path.
If the abstract pathname is already absolute, then the same pathname string is returned.
If the file object is created using a relative path then the path returned is a relative path.
If the abstract pathname is relative, then it is resolved in a system-dependent way.
Example(On Window’s System):
If the absolute path is provided:
File path1 = new File(“C:\\Users\\ASPIRE\\Desktop\\Java folder\\demo.txt”);
Output:
C:\Users\ASPIRE\Desktop\Java folder\demo.txt
If relative path is provided:
File path2 = new File(“..\\demo.txt”);
Output:
..\demo.txt
Example(On Window’s System):
If absolute path is provided:
File path1 = new File(“C:\\Users\\ASPIRE\\Desktop\\Java folder\\demo.txt”);
Output:
C:\Users\ASPIRE\Desktop\Java folder\demo.txt
If relative path is provided:
File path2 = new File(“..\\demo.txt”);
Output:
C:\Users\ASPIRE\Desktop\Java folder\..\demo.txt
Example(On Unix’s System):
If absolute path is provided:
File path1 = new File(“home/Pooja/Desktop/Java folder/demo.txt”);
Output:
home/Pooja/Desktop/Java folder/demo.txt
If relative path is provided:
File path2 = new File(“../demo.txt”);
Output:
../demo.txt
Example(On Unix’s System):
If absolute path is provided:
File path1 = new File(“home/Pooja/Desktop/Java folder/demo.txt”);
Output:
home/Pooja/Desktop/Java folder/demo.txt
If relative path is provided:
a)File path2 = new File(“../demo.txt”);
Output:
../demo.txt
b)File path2 = new File(“../Document/abc.txt”);
Output:
/home/pooja/Document/abc.txt
Java-File Class
Picked
Difference Between
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Difference between Prim's and Kruskal's algorithm for MST
Difference Between Spark DataFrame and Pandas DataFrame
Difference between Internal and External fragmentation
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Arrays.sort() in Java with examples
Reverse a string in Java | [
{
"code": null,
"e": 24858,
"s": 24830,
"text": "\n04 Jan, 2021"
},
{
"code": null,
"e": 25059,
"s": 24858,
"text": "getPath(): The getPath() method is a part of File class. This function returns the path of the given file object. The function returns a string object which contains the path of the given file object."
},
{
"code": null,
"e": 25072,
"s": 25059,
"text": "Return Type:"
},
{
"code": null,
"e": 25112,
"s": 25072,
"text": "The string form of an abstract pathname"
},
{
"code": null,
"e": 25560,
"s": 25112,
"text": "getAbsolutePath(): The getAbsolutePath() returns a path object representing the absolute path of given path. If the given pathname is already absolute, then the pathname string is simply returned as if by the getPath() method. If the current abstract pathname is the empty abstract pathname then the pathname string of the current user directory(named by the system property) is returned. Else, this pathname is resolved in a system-dependent way."
},
{
"code": null,
"e": 25579,
"s": 25560,
"text": "On Unix’s System: "
},
{
"code": null,
"e": 25668,
"s": 25579,
"text": "A relative pathname is made absolute by resolving it against the current user directory."
},
{
"code": null,
"e": 25690,
"s": 25668,
"text": "On Microsoft System: "
},
{
"code": null,
"e": 25860,
"s": 25690,
"text": "A relative pathname is made absolute by resolving it against the current directory of the drive named by the pathname, it is resolved against the current user directory."
},
{
"code": null,
"e": 25869,
"s": 25860,
"text": "Returns:"
},
{
"code": null,
"e": 25960,
"s": 25869,
"text": "The absolute pathname string denoting the same file or directory as this abstract pathname"
},
{
"code": null,
"e": 26098,
"s": 25960,
"text": "This method returns a string which denotes the (absolute or relative) pathname of the file represented by the file object. "
},
{
"code": null,
"e": 26174,
"s": 26098,
"text": "This method returns the absolute pathname string of abstract file pathname."
},
{
"code": null,
"e": 26271,
"s": 26174,
"text": "If the file object is created using an absolute path then the path returned is an absolute path."
},
{
"code": null,
"e": 26458,
"s": 26271,
"text": "If the abstract pathname is already absolute, then the same pathname string is returned. "
},
{
"code": null,
"e": 26553,
"s": 26458,
"text": "If the file object is created using a relative path then the path returned is a relative path."
},
{
"code": null,
"e": 26638,
"s": 26553,
"text": "If the abstract pathname is relative, then it is resolved in a system-dependent way."
},
{
"code": null,
"e": 26667,
"s": 26638,
"text": "Example(On Window’s System):"
},
{
"code": null,
"e": 26701,
"s": 26667,
"text": "If the absolute path is provided:"
},
{
"code": null,
"e": 26777,
"s": 26701,
"text": "File path1 = new File(“C:\\\\Users\\\\ASPIRE\\\\Desktop\\\\Java folder\\\\demo.txt”);"
},
{
"code": null,
"e": 26785,
"s": 26777,
"text": "Output:"
},
{
"code": null,
"e": 26830,
"s": 26785,
"text": "C:\\Users\\ASPIRE\\Desktop\\Java folder\\demo.txt"
},
{
"code": null,
"e": 26860,
"s": 26830,
"text": "If relative path is provided:"
},
{
"code": null,
"e": 26899,
"s": 26860,
"text": "File path2 = new File(“..\\\\demo.txt”);"
},
{
"code": null,
"e": 26907,
"s": 26899,
"text": "Output:"
},
{
"code": null,
"e": 26919,
"s": 26907,
"text": "..\\demo.txt"
},
{
"code": null,
"e": 26948,
"s": 26919,
"text": "Example(On Window’s System):"
},
{
"code": null,
"e": 26978,
"s": 26948,
"text": "If absolute path is provided:"
},
{
"code": null,
"e": 27054,
"s": 26978,
"text": "File path1 = new File(“C:\\\\Users\\\\ASPIRE\\\\Desktop\\\\Java folder\\\\demo.txt”);"
},
{
"code": null,
"e": 27062,
"s": 27054,
"text": "Output:"
},
{
"code": null,
"e": 27107,
"s": 27062,
"text": "C:\\Users\\ASPIRE\\Desktop\\Java folder\\demo.txt"
},
{
"code": null,
"e": 27137,
"s": 27107,
"text": "If relative path is provided:"
},
{
"code": null,
"e": 27176,
"s": 27137,
"text": "File path2 = new File(“..\\\\demo.txt”);"
},
{
"code": null,
"e": 27184,
"s": 27176,
"text": "Output:"
},
{
"code": null,
"e": 27232,
"s": 27184,
"text": "C:\\Users\\ASPIRE\\Desktop\\Java folder\\..\\demo.txt"
},
{
"code": null,
"e": 27259,
"s": 27232,
"text": "Example(On Unix’s System):"
},
{
"code": null,
"e": 27289,
"s": 27259,
"text": "If absolute path is provided:"
},
{
"code": null,
"e": 27355,
"s": 27289,
"text": "File path1 = new File(“home/Pooja/Desktop/Java folder/demo.txt”);"
},
{
"code": null,
"e": 27363,
"s": 27355,
"text": "Output:"
},
{
"code": null,
"e": 27403,
"s": 27363,
"text": "home/Pooja/Desktop/Java folder/demo.txt"
},
{
"code": null,
"e": 27433,
"s": 27403,
"text": "If relative path is provided:"
},
{
"code": null,
"e": 27471,
"s": 27433,
"text": "File path2 = new File(“../demo.txt”);"
},
{
"code": null,
"e": 27479,
"s": 27471,
"text": "Output:"
},
{
"code": null,
"e": 27491,
"s": 27479,
"text": "../demo.txt"
},
{
"code": null,
"e": 27518,
"s": 27491,
"text": "Example(On Unix’s System):"
},
{
"code": null,
"e": 27548,
"s": 27518,
"text": "If absolute path is provided:"
},
{
"code": null,
"e": 27614,
"s": 27548,
"text": "File path1 = new File(“home/Pooja/Desktop/Java folder/demo.txt”);"
},
{
"code": null,
"e": 27622,
"s": 27614,
"text": "Output:"
},
{
"code": null,
"e": 27662,
"s": 27622,
"text": "home/Pooja/Desktop/Java folder/demo.txt"
},
{
"code": null,
"e": 27692,
"s": 27662,
"text": "If relative path is provided:"
},
{
"code": null,
"e": 27732,
"s": 27692,
"text": "a)File path2 = new File(“../demo.txt”);"
},
{
"code": null,
"e": 27740,
"s": 27732,
"text": "Output:"
},
{
"code": null,
"e": 27752,
"s": 27740,
"text": "../demo.txt"
},
{
"code": null,
"e": 27800,
"s": 27752,
"text": "b)File path2 = new File(“../Document/abc.txt”);"
},
{
"code": null,
"e": 27808,
"s": 27800,
"text": "Output:"
},
{
"code": null,
"e": 27837,
"s": 27808,
"text": "/home/pooja/Document/abc.txt"
},
{
"code": null,
"e": 27853,
"s": 27837,
"text": "Java-File Class"
},
{
"code": null,
"e": 27860,
"s": 27853,
"text": "Picked"
},
{
"code": null,
"e": 27879,
"s": 27860,
"text": "Difference Between"
},
{
"code": null,
"e": 27884,
"s": 27879,
"text": "Java"
},
{
"code": null,
"e": 27898,
"s": 27884,
"text": "Java Programs"
},
{
"code": null,
"e": 27903,
"s": 27898,
"text": "Java"
},
{
"code": null,
"e": 28001,
"s": 27903,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28010,
"s": 28001,
"text": "Comments"
},
{
"code": null,
"e": 28023,
"s": 28010,
"text": "Old Comments"
},
{
"code": null,
"e": 28084,
"s": 28023,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28152,
"s": 28084,
"text": "Difference Between Method Overloading and Method Overriding in Java"
},
{
"code": null,
"e": 28210,
"s": 28152,
"text": "Difference between Prim's and Kruskal's algorithm for MST"
},
{
"code": null,
"e": 28266,
"s": 28210,
"text": "Difference Between Spark DataFrame and Pandas DataFrame"
},
{
"code": null,
"e": 28321,
"s": 28266,
"text": "Difference between Internal and External fragmentation"
},
{
"code": null,
"e": 28336,
"s": 28321,
"text": "Arrays in Java"
},
{
"code": null,
"e": 28380,
"s": 28336,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 28402,
"s": 28380,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 28438,
"s": 28402,
"text": "Arrays.sort() in Java with examples"
}
] |
Are Stock Returns Normally Distributed? | by Tony Yiu | Towards Data Science | While painful, the chaos in financial markets recently provides a good opportunity for us to question our assumptions. It’s very common in the investments industry to model the potential range of an investment’s future returns with a normal distribution. Any time we can model something with normal distributions, it makes life a lot easier. For example, the return of a portfolio consisting of many investments (each with normally distributed returns) is also normally distributed. And to describe an investment, we only need 2 values: the mean (a.k.a. the investment’s expected return) and the standard deviation (a.k.a. the investment’s risk). If we want to be thorough, we should also record the investment’s correlation with our overall portfolio.
I wrote previously about how the finance industry models the risk of an investment. The X-axis location of the peak of the bell curve is the expected return and the width of the bell curve proxies its risk:
But do risk estimates made with these assumptions actually make sense? Are stock returns actually normal? And does the assumption of normality understate, properly state, or overstate the frequency of market disasters (like what we experienced over the past few weeks)?
Since 1950, the average annual return of the S&P 500 has been approximately 8% and the standard deviation of that return has been 12%. I want to look at monthly returns so let’s translate these to monthly:
Monthly Expected Return = 8%/12 = 0.66%Monthly Standard Deviation = 12%/(12^0.5) = 3.50%
Let’s overlay the actual returns on top of a theoretical normal distribution with a mean of 0.66% and a standard deviation of 3.5%:
It looks approximately normal but if we look to the left of the distribution, we can see the famous fat tails. The fat tails mean that extreme events occur more frequently in reality than what a normal distribution would predict. More evidence of that is how the actual distribution of monthly S&P 500 returns is skinnier in its center than the normal distribution. The skinny middle and the fat tails imply that the normal distribution might not be the best describer of stock returns. Rather, there seem to be 2 regimes — a calm regime where we spend most of the time that is normally distributed (but with a lower volatility than 12%) and a regime with high volatility and terrible returns.
Another way to check for normality is with a QQ plot (I also wrote a blog detailing how QQ plots work). Let’s check out the QQ plot for monthly S&P 500 returns:
Deviations from the red 45 degree line represent differences from the normal distribution. While most of the observations do fall more or less on the red line, we can see significant deviations on the left tail and smaller ones on the right tail. The value on the X-axis (Theoretical Quantiles) tells us how frequently we expect to see an observation of that magnitude on a normal distribution (they are Z-scores, a.k.a. standard deviations away from the mean, which implies a probability). And the value on the Y-axis (Sample Quantiles, also in Z-scores) tells us how frequently we actually see it.
For example, take the 2 dots on the left that are obvious outliers. Both of those represent S&P 500 returns of worse than -20%. In the dataset, there are 843 monthly observations in total. So the 2 outlier dots represent a mere 0.237% of our observations. We can use the following line of code to find the point on a normal distribution where 0.237% of the observations lie to the left:
In:from scipy.stats import norm# Multiply by 2 to account for probabilities in right tail alsotheoretical_z_score = norm.interval(1-(0.00237*2))[0]print('Theoretical Z = ' + str(round(theoretical_z_score, 2)))Out:Theoretical Z = -2.82
This means that on a normal distribution (with mean=0 and standard deviation=1), we would expect 0.237% of the observations to lie to the left of -2.82 (this value is an example of a Z-score). The Z-score we just calculated is the X-axis position of the second-worst return on the QQ plot.
We can confirm this via the cumulative density function (CDF method), which tells us, for a given distribution, the sum of the probabilities that lie to the left of the Z-score:
In:prob_left = norm.cdf(theoretical_z_score)print('Probability to left = ' + str(round(prob_left, 5)))Out:Probability to left = 0.00237
The Z-score is a metric that connects magnitudes with probabilities. It’s formula is:
Z-score = (observed - mean)/standard_deviation
A Z-score of -2.82 means the observed value was -2.82 standard deviations below the mean (the further it is from the mean in either direction, the less probable the observation). The -2.82 is a theoretical Z-score, a.k.a. the value below which we expect 0.237% of our observations to lie on a normal distribution.
Now let’s calculate the Z-score of our actual data. The 2 outlier dots represent disastrous monthly returns of -20.4% (2008 Financial Crisis) and -22.5% (this past month). So we can use -20.4% to calculate our Z-score (since 2 out of the 842 observations are -20.4% or worse) along with the mean and standard deviation of the S&P 500’s monthly returns:
In:actual_z_score = (-0.204 - 0.0066)/0.035print('Actual Z = ' + str(round(actual_z_score, 2)))Out:Actual Z = -6.02
Wow, a -20% monthly return is a 6 sigma event (6 standard deviations below the mean)! Let’s frame this in terms of probabilities that we can more easily comprehend:
A -2.82 sigma (or worse) event occurs with 0.237% frequency. That means we would expect it to happen once every 1/0.00237 months. So we expect it to happen once every 422 months, or once every 35 years.
A -6.02 sigma (or worse) event occurs with 8.87*10^-8% frequency. Yeah, that number doesn’t make sense to me either so let’s rephrase it. In terms of years, if stock returns were truly normal, then we would expect a 6 sigma event like this one to occur once every 93,884,861 years!
That’s why the QQ plot highlights those 2 points especially (the -6.02 sigma is the Y-axis value of the second worst return on the QQ plot). It’s saying that we are observing 6 sigma events (massively improbably events) in our data at a much higher than expected frequency (approximately 3 sigma frequency). It’s trying to tell us:
It’s saying that we are observing 6 sigma events (massively improbably events) in our data at a much higher than expected frequency (approximately 3 sigma frequency). It’s trying to tell us:
“Hey based on the mean and standard deviation of our data and most critically the assumption that our data is normally distributed, what we are observing here is super duper abnormal!”
And we observed 2 returns worse than -20%! That’s 2 six sigma events (once in 90 million year type events) in a dataset that is only 70 years long. So we can pretty confidently state (no hypothesis test needed!) that NO stock returns are not normal. Moreover, assuming that they are causing us to understate the likelihood of disastrous market returns.
Do we scrap all our models and try to start again from scratch? I don’t think we need to go all the way there. Stock returns are roughly normal after all and a lot of the benefits of investment theory such as diversification hold true even in a world of less than normal stock returns and fat tails (perhaps even more so).
But when we stress test our portfolios (as well as our own mental expectations of what the future might hold), we should definitely be cognizant of the supposed 4, 5, and 6 sigma events that actually seem to occur once every business cycle.
We can also rethink specifically the way we estimate the frequency of disastrous market returns. One issue is that financial markets have just not been around long enough. Therefore we don’t have enough observations to be confident that our estimates of mean, standard deviation, etc. are truly representative of the true distribution. So we should acknowledge the possibility that the inferences we make (using the market data that we do have) will sometimes be woefully incorrect. It reminds me a little of earthquake forecasting where scientists are trying to predict the magnitude and frequency of huge earthquakes (the likes of which might never have been recorded before) using a dataset dominated by quakes of small and medium magnitude. Perhaps the finance industry can borrow a page or 2 from them.
Previous Posts Referenced In This Article:
Understanding Investment Risk
Understanding The Normal Distribution
What In The World Are QQ Plots? | [
{
"code": null,
"e": 925,
"s": 172,
"text": "While painful, the chaos in financial markets recently provides a good opportunity for us to question our assumptions. It’s very common in the investments industry to model the potential range of an investment’s future returns with a normal distribution. Any time we can model something with normal distributions, it makes life a lot easier. For example, the return of a portfolio consisting of many investments (each with normally distributed returns) is also normally distributed. And to describe an investment, we only need 2 values: the mean (a.k.a. the investment’s expected return) and the standard deviation (a.k.a. the investment’s risk). If we want to be thorough, we should also record the investment’s correlation with our overall portfolio."
},
{
"code": null,
"e": 1132,
"s": 925,
"text": "I wrote previously about how the finance industry models the risk of an investment. The X-axis location of the peak of the bell curve is the expected return and the width of the bell curve proxies its risk:"
},
{
"code": null,
"e": 1402,
"s": 1132,
"text": "But do risk estimates made with these assumptions actually make sense? Are stock returns actually normal? And does the assumption of normality understate, properly state, or overstate the frequency of market disasters (like what we experienced over the past few weeks)?"
},
{
"code": null,
"e": 1608,
"s": 1402,
"text": "Since 1950, the average annual return of the S&P 500 has been approximately 8% and the standard deviation of that return has been 12%. I want to look at monthly returns so let’s translate these to monthly:"
},
{
"code": null,
"e": 1697,
"s": 1608,
"text": "Monthly Expected Return = 8%/12 = 0.66%Monthly Standard Deviation = 12%/(12^0.5) = 3.50%"
},
{
"code": null,
"e": 1829,
"s": 1697,
"text": "Let’s overlay the actual returns on top of a theoretical normal distribution with a mean of 0.66% and a standard deviation of 3.5%:"
},
{
"code": null,
"e": 2523,
"s": 1829,
"text": "It looks approximately normal but if we look to the left of the distribution, we can see the famous fat tails. The fat tails mean that extreme events occur more frequently in reality than what a normal distribution would predict. More evidence of that is how the actual distribution of monthly S&P 500 returns is skinnier in its center than the normal distribution. The skinny middle and the fat tails imply that the normal distribution might not be the best describer of stock returns. Rather, there seem to be 2 regimes — a calm regime where we spend most of the time that is normally distributed (but with a lower volatility than 12%) and a regime with high volatility and terrible returns."
},
{
"code": null,
"e": 2684,
"s": 2523,
"text": "Another way to check for normality is with a QQ plot (I also wrote a blog detailing how QQ plots work). Let’s check out the QQ plot for monthly S&P 500 returns:"
},
{
"code": null,
"e": 3284,
"s": 2684,
"text": "Deviations from the red 45 degree line represent differences from the normal distribution. While most of the observations do fall more or less on the red line, we can see significant deviations on the left tail and smaller ones on the right tail. The value on the X-axis (Theoretical Quantiles) tells us how frequently we expect to see an observation of that magnitude on a normal distribution (they are Z-scores, a.k.a. standard deviations away from the mean, which implies a probability). And the value on the Y-axis (Sample Quantiles, also in Z-scores) tells us how frequently we actually see it."
},
{
"code": null,
"e": 3671,
"s": 3284,
"text": "For example, take the 2 dots on the left that are obvious outliers. Both of those represent S&P 500 returns of worse than -20%. In the dataset, there are 843 monthly observations in total. So the 2 outlier dots represent a mere 0.237% of our observations. We can use the following line of code to find the point on a normal distribution where 0.237% of the observations lie to the left:"
},
{
"code": null,
"e": 3906,
"s": 3671,
"text": "In:from scipy.stats import norm# Multiply by 2 to account for probabilities in right tail alsotheoretical_z_score = norm.interval(1-(0.00237*2))[0]print('Theoretical Z = ' + str(round(theoretical_z_score, 2)))Out:Theoretical Z = -2.82"
},
{
"code": null,
"e": 4196,
"s": 3906,
"text": "This means that on a normal distribution (with mean=0 and standard deviation=1), we would expect 0.237% of the observations to lie to the left of -2.82 (this value is an example of a Z-score). The Z-score we just calculated is the X-axis position of the second-worst return on the QQ plot."
},
{
"code": null,
"e": 4374,
"s": 4196,
"text": "We can confirm this via the cumulative density function (CDF method), which tells us, for a given distribution, the sum of the probabilities that lie to the left of the Z-score:"
},
{
"code": null,
"e": 4510,
"s": 4374,
"text": "In:prob_left = norm.cdf(theoretical_z_score)print('Probability to left = ' + str(round(prob_left, 5)))Out:Probability to left = 0.00237"
},
{
"code": null,
"e": 4596,
"s": 4510,
"text": "The Z-score is a metric that connects magnitudes with probabilities. It’s formula is:"
},
{
"code": null,
"e": 4643,
"s": 4596,
"text": "Z-score = (observed - mean)/standard_deviation"
},
{
"code": null,
"e": 4957,
"s": 4643,
"text": "A Z-score of -2.82 means the observed value was -2.82 standard deviations below the mean (the further it is from the mean in either direction, the less probable the observation). The -2.82 is a theoretical Z-score, a.k.a. the value below which we expect 0.237% of our observations to lie on a normal distribution."
},
{
"code": null,
"e": 5310,
"s": 4957,
"text": "Now let’s calculate the Z-score of our actual data. The 2 outlier dots represent disastrous monthly returns of -20.4% (2008 Financial Crisis) and -22.5% (this past month). So we can use -20.4% to calculate our Z-score (since 2 out of the 842 observations are -20.4% or worse) along with the mean and standard deviation of the S&P 500’s monthly returns:"
},
{
"code": null,
"e": 5426,
"s": 5310,
"text": "In:actual_z_score = (-0.204 - 0.0066)/0.035print('Actual Z = ' + str(round(actual_z_score, 2)))Out:Actual Z = -6.02"
},
{
"code": null,
"e": 5591,
"s": 5426,
"text": "Wow, a -20% monthly return is a 6 sigma event (6 standard deviations below the mean)! Let’s frame this in terms of probabilities that we can more easily comprehend:"
},
{
"code": null,
"e": 5794,
"s": 5591,
"text": "A -2.82 sigma (or worse) event occurs with 0.237% frequency. That means we would expect it to happen once every 1/0.00237 months. So we expect it to happen once every 422 months, or once every 35 years."
},
{
"code": null,
"e": 6076,
"s": 5794,
"text": "A -6.02 sigma (or worse) event occurs with 8.87*10^-8% frequency. Yeah, that number doesn’t make sense to me either so let’s rephrase it. In terms of years, if stock returns were truly normal, then we would expect a 6 sigma event like this one to occur once every 93,884,861 years!"
},
{
"code": null,
"e": 6408,
"s": 6076,
"text": "That’s why the QQ plot highlights those 2 points especially (the -6.02 sigma is the Y-axis value of the second worst return on the QQ plot). It’s saying that we are observing 6 sigma events (massively improbably events) in our data at a much higher than expected frequency (approximately 3 sigma frequency). It’s trying to tell us:"
},
{
"code": null,
"e": 6599,
"s": 6408,
"text": "It’s saying that we are observing 6 sigma events (massively improbably events) in our data at a much higher than expected frequency (approximately 3 sigma frequency). It’s trying to tell us:"
},
{
"code": null,
"e": 6784,
"s": 6599,
"text": "“Hey based on the mean and standard deviation of our data and most critically the assumption that our data is normally distributed, what we are observing here is super duper abnormal!”"
},
{
"code": null,
"e": 7137,
"s": 6784,
"text": "And we observed 2 returns worse than -20%! That’s 2 six sigma events (once in 90 million year type events) in a dataset that is only 70 years long. So we can pretty confidently state (no hypothesis test needed!) that NO stock returns are not normal. Moreover, assuming that they are causing us to understate the likelihood of disastrous market returns."
},
{
"code": null,
"e": 7460,
"s": 7137,
"text": "Do we scrap all our models and try to start again from scratch? I don’t think we need to go all the way there. Stock returns are roughly normal after all and a lot of the benefits of investment theory such as diversification hold true even in a world of less than normal stock returns and fat tails (perhaps even more so)."
},
{
"code": null,
"e": 7701,
"s": 7460,
"text": "But when we stress test our portfolios (as well as our own mental expectations of what the future might hold), we should definitely be cognizant of the supposed 4, 5, and 6 sigma events that actually seem to occur once every business cycle."
},
{
"code": null,
"e": 8509,
"s": 7701,
"text": "We can also rethink specifically the way we estimate the frequency of disastrous market returns. One issue is that financial markets have just not been around long enough. Therefore we don’t have enough observations to be confident that our estimates of mean, standard deviation, etc. are truly representative of the true distribution. So we should acknowledge the possibility that the inferences we make (using the market data that we do have) will sometimes be woefully incorrect. It reminds me a little of earthquake forecasting where scientists are trying to predict the magnitude and frequency of huge earthquakes (the likes of which might never have been recorded before) using a dataset dominated by quakes of small and medium magnitude. Perhaps the finance industry can borrow a page or 2 from them."
},
{
"code": null,
"e": 8552,
"s": 8509,
"text": "Previous Posts Referenced In This Article:"
},
{
"code": null,
"e": 8582,
"s": 8552,
"text": "Understanding Investment Risk"
},
{
"code": null,
"e": 8620,
"s": 8582,
"text": "Understanding The Normal Distribution"
}
] |
5 Tips to Customize the Display of Your Pandas Data Frame | by Satyam Kumar | Towards Data Science | Pandas is one of the most popular Python libraries in the data science community, as it offers flexible data structures and a vast API for data explorations and visualization. A data scientist spends most of the time exploring the data and performing exploratory data analysis. Jupyter Notebook provides an interactive platform to perform exploratory data analysis and is most preferred by Data Scientists and Data Analysts.
dataframe.head() is a function from the Pandas package to display the top 5 rows of the data frame. Pandas use predefined HTML+CSS commands to display the data frame in a formatted way on the notebook. By default, we are limited by the number of rows and columns that the Pandas data frame shows in the notebook. Sometimes, it's necessary to change the display format to make the EDA more intuitive and formatted. The formatting of the data frame can be changed using pandas.options.display option.
30+ display options can be altered to customize the display format; in this article we will discuss 5 of the popular tricks to customize the display format of the data frame to make it more intuitive.
Checklist:1. Display of Columns2. Display of Rows3. Width of the cell4. Decimal value formatting5. Data frame info
Before getting started, I am using pd as alias name of pandas library, import pandas as pd , and df is the variable that points to the dataset.
After we load the dataset using Pandas, we are limited by the number of columns in the output display cell. df.head() function from Pandas library is essential to get a first cut overview of the top 5 rows of the data frame. The number of the columns is limited, which makes it difficult to visualize the entire set of columns.
By default, the output display is restricted to 20 columns, the first 10 and the last 10 columns are displayed separated by three dots.
You have the option to alter the number of columns to be displayed on the output cell. Using pd.set_option(“display.max_columns”, x), the number of displayed columns will be changed to x. If None is passed in place of x, then all the columns will be displayed in the output cell.
By changing the display options of the number of columns, it makes very intuitive to get the first cut visualization of the data frame.
Pandas also provide to alter the display options of the rows of the data frame. By default, Pandas will truncate the rows with more than 60 rows, and display only the top and bottom 5 rows in the output cell.
One can alter the number of rows to be displayed in the output cell using pd.set_option(“display.max_rows”, x) , when None replaced with x displays all the rows in the data frame. One can scroll down and visualize the values of the data frame.
Pandas display options can not only alter the number of rows and columns to be displayed in the output cell, but also provides capabilities to alter the width of the cell of the data frame. By default, the maximum width of the cell can be 50. The cell having more than 50 characters, the rest of the characters are truncated.
In the above sample dataset, the text values in the review column in truncated after 50 characters.pandas.display.options provides capabilities to alter the number of characters to be displayed in the output cell, using pd.set_option(“display.max_colwidth”, x) where x is the number of characters.
By default, Pandas formats the floating values in the data frame to 6 decimal places, for the values having more than 6 digits after the decimal.
If you print the first row values of V1 column, we get the real feature values that have 13 digits after the decimal-1.3598071336738 .
pandas.display.options provides capabilities to alter the precision of the floating-point numbers, using pd.set_option(“display.precision”, x) where x is the precision.
Changing the precision of the feature values does not actually affect the dataset, but it's restricted to the display in the output cell of the notebook.
dataframe.info() is a popular function in Pandas, to get an overview profile of the data frame. This displays the column name, Non-null values count, the datatype of the column for the data frame.
The info() function has its constraints limited to a data frame with 100 features or columns. The below-mentioned image displays what info() function returns for a dataset with just 2 features.
For a dataset with more than 100 features, info() functions do not return with the column name, Non-null values count, the datatype for each of the columns.
One can alter the default constraints of max_info_columns, to get the entire profile overview of the data frame.
In this article, we have discussed how to alter the display options in the Pandas data frame. The 6 hacks mentioned in the article are very useful while performing data understanding and data explorations tasks. By altering the display options discussed above one can get a better visualization of the data frame in the notebook.
[1] Pandas Documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/options.html
Thank You for Reading | [
{
"code": null,
"e": 596,
"s": 171,
"text": "Pandas is one of the most popular Python libraries in the data science community, as it offers flexible data structures and a vast API for data explorations and visualization. A data scientist spends most of the time exploring the data and performing exploratory data analysis. Jupyter Notebook provides an interactive platform to perform exploratory data analysis and is most preferred by Data Scientists and Data Analysts."
},
{
"code": null,
"e": 1095,
"s": 596,
"text": "dataframe.head() is a function from the Pandas package to display the top 5 rows of the data frame. Pandas use predefined HTML+CSS commands to display the data frame in a formatted way on the notebook. By default, we are limited by the number of rows and columns that the Pandas data frame shows in the notebook. Sometimes, it's necessary to change the display format to make the EDA more intuitive and formatted. The formatting of the data frame can be changed using pandas.options.display option."
},
{
"code": null,
"e": 1296,
"s": 1095,
"text": "30+ display options can be altered to customize the display format; in this article we will discuss 5 of the popular tricks to customize the display format of the data frame to make it more intuitive."
},
{
"code": null,
"e": 1411,
"s": 1296,
"text": "Checklist:1. Display of Columns2. Display of Rows3. Width of the cell4. Decimal value formatting5. Data frame info"
},
{
"code": null,
"e": 1555,
"s": 1411,
"text": "Before getting started, I am using pd as alias name of pandas library, import pandas as pd , and df is the variable that points to the dataset."
},
{
"code": null,
"e": 1883,
"s": 1555,
"text": "After we load the dataset using Pandas, we are limited by the number of columns in the output display cell. df.head() function from Pandas library is essential to get a first cut overview of the top 5 rows of the data frame. The number of the columns is limited, which makes it difficult to visualize the entire set of columns."
},
{
"code": null,
"e": 2019,
"s": 1883,
"text": "By default, the output display is restricted to 20 columns, the first 10 and the last 10 columns are displayed separated by three dots."
},
{
"code": null,
"e": 2299,
"s": 2019,
"text": "You have the option to alter the number of columns to be displayed on the output cell. Using pd.set_option(“display.max_columns”, x), the number of displayed columns will be changed to x. If None is passed in place of x, then all the columns will be displayed in the output cell."
},
{
"code": null,
"e": 2435,
"s": 2299,
"text": "By changing the display options of the number of columns, it makes very intuitive to get the first cut visualization of the data frame."
},
{
"code": null,
"e": 2644,
"s": 2435,
"text": "Pandas also provide to alter the display options of the rows of the data frame. By default, Pandas will truncate the rows with more than 60 rows, and display only the top and bottom 5 rows in the output cell."
},
{
"code": null,
"e": 2888,
"s": 2644,
"text": "One can alter the number of rows to be displayed in the output cell using pd.set_option(“display.max_rows”, x) , when None replaced with x displays all the rows in the data frame. One can scroll down and visualize the values of the data frame."
},
{
"code": null,
"e": 3214,
"s": 2888,
"text": "Pandas display options can not only alter the number of rows and columns to be displayed in the output cell, but also provides capabilities to alter the width of the cell of the data frame. By default, the maximum width of the cell can be 50. The cell having more than 50 characters, the rest of the characters are truncated."
},
{
"code": null,
"e": 3512,
"s": 3214,
"text": "In the above sample dataset, the text values in the review column in truncated after 50 characters.pandas.display.options provides capabilities to alter the number of characters to be displayed in the output cell, using pd.set_option(“display.max_colwidth”, x) where x is the number of characters."
},
{
"code": null,
"e": 3658,
"s": 3512,
"text": "By default, Pandas formats the floating values in the data frame to 6 decimal places, for the values having more than 6 digits after the decimal."
},
{
"code": null,
"e": 3793,
"s": 3658,
"text": "If you print the first row values of V1 column, we get the real feature values that have 13 digits after the decimal-1.3598071336738 ."
},
{
"code": null,
"e": 3962,
"s": 3793,
"text": "pandas.display.options provides capabilities to alter the precision of the floating-point numbers, using pd.set_option(“display.precision”, x) where x is the precision."
},
{
"code": null,
"e": 4116,
"s": 3962,
"text": "Changing the precision of the feature values does not actually affect the dataset, but it's restricted to the display in the output cell of the notebook."
},
{
"code": null,
"e": 4313,
"s": 4116,
"text": "dataframe.info() is a popular function in Pandas, to get an overview profile of the data frame. This displays the column name, Non-null values count, the datatype of the column for the data frame."
},
{
"code": null,
"e": 4507,
"s": 4313,
"text": "The info() function has its constraints limited to a data frame with 100 features or columns. The below-mentioned image displays what info() function returns for a dataset with just 2 features."
},
{
"code": null,
"e": 4664,
"s": 4507,
"text": "For a dataset with more than 100 features, info() functions do not return with the column name, Non-null values count, the datatype for each of the columns."
},
{
"code": null,
"e": 4777,
"s": 4664,
"text": "One can alter the default constraints of max_info_columns, to get the entire profile overview of the data frame."
},
{
"code": null,
"e": 5107,
"s": 4777,
"text": "In this article, we have discussed how to alter the display options in the Pandas data frame. The 6 hacks mentioned in the article are very useful while performing data understanding and data explorations tasks. By altering the display options discussed above one can get a better visualization of the data frame in the notebook."
},
{
"code": null,
"e": 5202,
"s": 5107,
"text": "[1] Pandas Documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/options.html"
}
] |
Tensorflow multi-worker training on Google Cloud AI Platform | by Szilárd Kálosi | Towards Data Science | In nearly every deep learning project, there is a decisive moment when immense volumes of training data or lack of processing power become the limiting factor of completing training in proper time. Therefore, applying appropriate scaling is inevitable. Although scaling up, i.e. upgrading to more powerful hardware, might deliver momentary remedies, seldom does it offer the right scalability because scaling up can rapidly hit its physical limits. Hence, we have no other option than to scale model training out, namely to use additional machines. Blissfully, scaling out in the era of cloud is not a hurdle anymore.
When it comes to scaling out neural network training, there are two main approaches. There is a strategy called model parallelism, in which the neural network itself gets split across multiple devices. This type of distribution gets mainly used in cases where the models consist of a multitude of parameters and would not otherwise fit on particular devices, or the sizes of input samples would impede even calculating activations. For those who are interested in model parallelism for Tensorflow, there is an official solution called Mesh.
Another distribution strategy is called data parallelism, in which the model gets replicated on each node. The data then gets distributed in such a way that each replica sees a different part of it. This distribution strategy becomes particularly useful for cases with vast volumes of training data.
Since each replica receives a distinct slice of the training data at each step, the workers must orderly communicate the gradient updates. There are two ways of communication. There is asynchronous training, in which the workers train their replicas independently. Asynchronous training typically uses discrete parameter servers for reporting into the gradient updates.
The other is synchronous training, in which the workers share the parameter updates after each training step. Synchronous training frequently implements all-reduce algorithms meaning all replicas store the reduced (updated) parameters rather than passing them to a central location.
The main benefit of asynchronous training manifests in avoiding idling for the slowest worker and slightly better machine fault tolerance. The major disadvantage is the parameter server needs a lot of network bandwidth for efficient communication with the workers. Operating more than one parameter servers might solve the issue, but it can also increase training costs.
The tradeoffs of synchronous training are the exact opposite. There is no need for using additional machines for storing the updated model parameters. On the other hand, waiting for the slowest worker can surely stall the process. Choosing workers of similar performance can potentially reduce idling times. Employing an efficient network topology for sharing gradient updates is likewise essential. Redundant communications between workers can eliminate the benefits of synchronous training.
Tensorflow implements data parallelism strategies in their standard library through the tf.distribute.Strategy API. They support both synchronous and asynchronous multi-worker training, although the latter has only limited support. As of writing this post, the asynchronous ParameterServerStrategy only supports the original tf.estimator.Estimator API. However, starting with version 2.4, there are efforts to make asynchronous training more available.
Since the release of Tensorflow 2.0, tf.keras.Model API has become the primary way of building neural networks, in particular, those not requiring custom training loops. Newly developed distributed training strategies have likewise mostly focused on Keras models. Although there have been several distributed training strategies implemented for Keras models, as of writing this article, the currently available multi-worker training is solely the synchronous MultiWorkerMirroredStrategy.
This strategy does a lot of weight lifting for us. It optimally chooses suitable all-reduce implementation based on the used hardware and network topology. Currently, the available options are the ring all-reduce and NVidia’s NCLL. The strategy also automatically distributes the training dataset among the workers in case of training Keras models. The distribution happens either by sharding the dataset by files or by data. Sharding by files is preferred because each replica loads the assigned files only. It is, for example, available for TFRecord datasets. Storing training examples in them is the most efficient way of processing large dataset efficiently. If, on the other hand, there is no way to shard by files, all workers read all the available data, yet they only process their assigned shards. Sharding by date can happen, for instance, in the case of reading directly from BigQuery, or if there are fewer files than workers. The same sharding holds for validation and test datasets too.
The strategy can also provide fault-tolerance through a Keras callback named BackupAndRestore. This callback backs up the model at the end of each epoch. If a worker interruption occurs, all other workers will also restart, and the training continues from the last finished training epoch. Upon successful model training, the stored checkpoints get deleted.
The simplest way of configuring multi-worker training in Tensorflow is through an environment variable namedTF_CONFIG. It is a JSON string that contains two keys, cluster and task. The former describes the topology and includes the addresses of the nodes. Its value is identical across all the nodes. The latter is unique for each node and defines their respective roles in the cluster. Once Tensorflow parses the environment variable, it starts gRPC servers based on the configuration.
The following example describes a cluster with two nodes, a chief and a worker.
There is a designated node in this cluster with extra responsibilities, called the chief. It caters to tasks such as saving training checkpoints, writing summaries for TensorBoard and serialising the trained model. If there is no chief explicitly specified in the configuration, the worker with index 0 assumes the role. Of course, the chief node executes the same code as well.
Integrating theMultiWorkerMirroredStrategy with Keras models is simple. There are only a few requirements. First, building and compiling the model must take place within the distribution strategy’s scope. Second, the batch size must reflect the number of nodes. Commonly, the batch size gets adjusted by multiplying it with the number of nodes. Keeping the original batch size also works. However, the workers receive smaller batches in that case. These approaches are referred to as weak and strong scaling, respectively.
Another difference opposed to regular Keras training is the requirement of specifying the steps_per_epoch argument, which is otherwise optional. The number of steps per epoch is easily calculated and is the ratio of the number of training instances divided by the adjusted global batch size. The function create_model involves the usual way of defining a model incorporating model compilation as well.
Saving a multi-worker model is a bit more elaborate. All the nodes must save the model, albeit to different locations. Finally, all the nodes except the chief must delete their saved versions. The reason for these steps is all-reduce communications can still occur.
Google Cloud and Tensorflow work together harmoniously. Tensorflow has always enjoyed a prominent role in AI platform. Furthermore, Google Cloud has also been putting efforts in new products with Tensorflow. For instance, they have recently introduced Tensorflow Enterprise with complementary support and managed services.
As we have seen, havingTF_CONFIG set correctly is an essential ingredient of Tensorflow multi-worker training. For Tensorflow to pick it up, the environment variable must exist before running model training. Fortunately, AI Platform takes care of setting it up based on the given training job configuration.
Ther are two ways of providing the job configuration. It is functional to set the respective options of the submission command. However, for infrequently changed properties, storing them in a YAML config file is more convenient. For successful multi-worker training, the required options are runtimVersion, pythonVersion, scaleTier, masterType, worketType, workerCount.
The above config file would create a cluster of there nodes consisting of a chief and two workers. The type of machines can be different, although it is more desirable for having them identical across the training cluster. There are predefined machine tiers as well, but they all come with parameter servers. Thus, having scale-tier set to custom is currently imperative.
The configuration also specifies the Tensorflow version, which is equal to the runtimeVersion property. The runtimes are periodically updated, but it takes some time for having later Tensorflow versions supported. It is important to note that runtimes before version 2.1 don’t set the chief node correctly. Hence, multi-worker training on AI Platform is only available for runtimes 2.1 and later.
There are situations, on the other hand, when being able to use not yet supported Tensorflow versions is crucial. For instance, there are relevant new features, or they need proper testing before moving them to production. For such cases, Google AI platform provides an option to use custom containers for training. Submitting custom containers for training is almost similar to using the provided runtimes. There are minor details to consider, though. For having correct TF_CONFIG, containerised Tensorflow models require the option useChiefInTfConfig set totrue. Furthermore, the training configuration must specify the image URIs for both chief and worker. The containers are, of course, identical for both cases.
In both official runtime and custom container, AI Platform Training automatically uses the Cloud ML Service Agent credentials.
Before submitting a job to AI Platform, it is practical to test the correctness of the training configuration locally as failed jobs get billed too. Fortunately, it is remarkably straightforward for official runtimes to run locally, execute
gcloud ai-platform local train --distributed --worker-count $N ...
The command sets up a correct TF_CONFIG for us. Alas, it also adds a parameter server to the configuration. Tensorflow will warn, but having the parameter servers will not thwart the training.
For containers, setting a correct TF_CONFIG and running the containers is a bit more complicated, but not impracticable. The simplest way to achieve local testing is to use docker-compose for running the chief and worker containers as well as setting the environment variables.
The COMMAND variable is a string containing all the arguments to the training task. Once the docker-compose configuration is complete, just hit
docker-compose up
In both cases, if the training requires access to other Google Cloud services, such as Cloud Storage, defining GOOGLE_APPLICATION_CREDENTIALS pointing to the right service account key JSON file must take place before running local training.
Building neural networks in itself is not a simple task. Dealing with distributed computing on the top of that can end up seriously curbing the process. Fortunately, modern deep learning frameworks are built with scalability in mind and thus enabling faster development. Moreover, thanks to the smooth compatibility between Tensorflow and Google Cloud, exploiting this scalability has never been closer to everyone’s reach.
Indeed, this smoothness might not appear so at first glance. For this reason, I have created a simple working example available on Github. Check it out for practical details. Remember, the best way of learning is by doing.
github.com
Distributed training with TensorFlow
Multi-worker training with Keras
TF_CONFIG and distributed training
Distributed Learning (slides) by Amir H. Payberah
Some rights reserved | [
{
"code": null,
"e": 790,
"s": 172,
"text": "In nearly every deep learning project, there is a decisive moment when immense volumes of training data or lack of processing power become the limiting factor of completing training in proper time. Therefore, applying appropriate scaling is inevitable. Although scaling up, i.e. upgrading to more powerful hardware, might deliver momentary remedies, seldom does it offer the right scalability because scaling up can rapidly hit its physical limits. Hence, we have no other option than to scale model training out, namely to use additional machines. Blissfully, scaling out in the era of cloud is not a hurdle anymore."
},
{
"code": null,
"e": 1331,
"s": 790,
"text": "When it comes to scaling out neural network training, there are two main approaches. There is a strategy called model parallelism, in which the neural network itself gets split across multiple devices. This type of distribution gets mainly used in cases where the models consist of a multitude of parameters and would not otherwise fit on particular devices, or the sizes of input samples would impede even calculating activations. For those who are interested in model parallelism for Tensorflow, there is an official solution called Mesh."
},
{
"code": null,
"e": 1631,
"s": 1331,
"text": "Another distribution strategy is called data parallelism, in which the model gets replicated on each node. The data then gets distributed in such a way that each replica sees a different part of it. This distribution strategy becomes particularly useful for cases with vast volumes of training data."
},
{
"code": null,
"e": 2001,
"s": 1631,
"text": "Since each replica receives a distinct slice of the training data at each step, the workers must orderly communicate the gradient updates. There are two ways of communication. There is asynchronous training, in which the workers train their replicas independently. Asynchronous training typically uses discrete parameter servers for reporting into the gradient updates."
},
{
"code": null,
"e": 2284,
"s": 2001,
"text": "The other is synchronous training, in which the workers share the parameter updates after each training step. Synchronous training frequently implements all-reduce algorithms meaning all replicas store the reduced (updated) parameters rather than passing them to a central location."
},
{
"code": null,
"e": 2655,
"s": 2284,
"text": "The main benefit of asynchronous training manifests in avoiding idling for the slowest worker and slightly better machine fault tolerance. The major disadvantage is the parameter server needs a lot of network bandwidth for efficient communication with the workers. Operating more than one parameter servers might solve the issue, but it can also increase training costs."
},
{
"code": null,
"e": 3148,
"s": 2655,
"text": "The tradeoffs of synchronous training are the exact opposite. There is no need for using additional machines for storing the updated model parameters. On the other hand, waiting for the slowest worker can surely stall the process. Choosing workers of similar performance can potentially reduce idling times. Employing an efficient network topology for sharing gradient updates is likewise essential. Redundant communications between workers can eliminate the benefits of synchronous training."
},
{
"code": null,
"e": 3601,
"s": 3148,
"text": "Tensorflow implements data parallelism strategies in their standard library through the tf.distribute.Strategy API. They support both synchronous and asynchronous multi-worker training, although the latter has only limited support. As of writing this post, the asynchronous ParameterServerStrategy only supports the original tf.estimator.Estimator API. However, starting with version 2.4, there are efforts to make asynchronous training more available."
},
{
"code": null,
"e": 4089,
"s": 3601,
"text": "Since the release of Tensorflow 2.0, tf.keras.Model API has become the primary way of building neural networks, in particular, those not requiring custom training loops. Newly developed distributed training strategies have likewise mostly focused on Keras models. Although there have been several distributed training strategies implemented for Keras models, as of writing this article, the currently available multi-worker training is solely the synchronous MultiWorkerMirroredStrategy."
},
{
"code": null,
"e": 5090,
"s": 4089,
"text": "This strategy does a lot of weight lifting for us. It optimally chooses suitable all-reduce implementation based on the used hardware and network topology. Currently, the available options are the ring all-reduce and NVidia’s NCLL. The strategy also automatically distributes the training dataset among the workers in case of training Keras models. The distribution happens either by sharding the dataset by files or by data. Sharding by files is preferred because each replica loads the assigned files only. It is, for example, available for TFRecord datasets. Storing training examples in them is the most efficient way of processing large dataset efficiently. If, on the other hand, there is no way to shard by files, all workers read all the available data, yet they only process their assigned shards. Sharding by date can happen, for instance, in the case of reading directly from BigQuery, or if there are fewer files than workers. The same sharding holds for validation and test datasets too."
},
{
"code": null,
"e": 5448,
"s": 5090,
"text": "The strategy can also provide fault-tolerance through a Keras callback named BackupAndRestore. This callback backs up the model at the end of each epoch. If a worker interruption occurs, all other workers will also restart, and the training continues from the last finished training epoch. Upon successful model training, the stored checkpoints get deleted."
},
{
"code": null,
"e": 5935,
"s": 5448,
"text": "The simplest way of configuring multi-worker training in Tensorflow is through an environment variable namedTF_CONFIG. It is a JSON string that contains two keys, cluster and task. The former describes the topology and includes the addresses of the nodes. Its value is identical across all the nodes. The latter is unique for each node and defines their respective roles in the cluster. Once Tensorflow parses the environment variable, it starts gRPC servers based on the configuration."
},
{
"code": null,
"e": 6015,
"s": 5935,
"text": "The following example describes a cluster with two nodes, a chief and a worker."
},
{
"code": null,
"e": 6394,
"s": 6015,
"text": "There is a designated node in this cluster with extra responsibilities, called the chief. It caters to tasks such as saving training checkpoints, writing summaries for TensorBoard and serialising the trained model. If there is no chief explicitly specified in the configuration, the worker with index 0 assumes the role. Of course, the chief node executes the same code as well."
},
{
"code": null,
"e": 6917,
"s": 6394,
"text": "Integrating theMultiWorkerMirroredStrategy with Keras models is simple. There are only a few requirements. First, building and compiling the model must take place within the distribution strategy’s scope. Second, the batch size must reflect the number of nodes. Commonly, the batch size gets adjusted by multiplying it with the number of nodes. Keeping the original batch size also works. However, the workers receive smaller batches in that case. These approaches are referred to as weak and strong scaling, respectively."
},
{
"code": null,
"e": 7319,
"s": 6917,
"text": "Another difference opposed to regular Keras training is the requirement of specifying the steps_per_epoch argument, which is otherwise optional. The number of steps per epoch is easily calculated and is the ratio of the number of training instances divided by the adjusted global batch size. The function create_model involves the usual way of defining a model incorporating model compilation as well."
},
{
"code": null,
"e": 7585,
"s": 7319,
"text": "Saving a multi-worker model is a bit more elaborate. All the nodes must save the model, albeit to different locations. Finally, all the nodes except the chief must delete their saved versions. The reason for these steps is all-reduce communications can still occur."
},
{
"code": null,
"e": 7908,
"s": 7585,
"text": "Google Cloud and Tensorflow work together harmoniously. Tensorflow has always enjoyed a prominent role in AI platform. Furthermore, Google Cloud has also been putting efforts in new products with Tensorflow. For instance, they have recently introduced Tensorflow Enterprise with complementary support and managed services."
},
{
"code": null,
"e": 8216,
"s": 7908,
"text": "As we have seen, havingTF_CONFIG set correctly is an essential ingredient of Tensorflow multi-worker training. For Tensorflow to pick it up, the environment variable must exist before running model training. Fortunately, AI Platform takes care of setting it up based on the given training job configuration."
},
{
"code": null,
"e": 8586,
"s": 8216,
"text": "Ther are two ways of providing the job configuration. It is functional to set the respective options of the submission command. However, for infrequently changed properties, storing them in a YAML config file is more convenient. For successful multi-worker training, the required options are runtimVersion, pythonVersion, scaleTier, masterType, worketType, workerCount."
},
{
"code": null,
"e": 8958,
"s": 8586,
"text": "The above config file would create a cluster of there nodes consisting of a chief and two workers. The type of machines can be different, although it is more desirable for having them identical across the training cluster. There are predefined machine tiers as well, but they all come with parameter servers. Thus, having scale-tier set to custom is currently imperative."
},
{
"code": null,
"e": 9355,
"s": 8958,
"text": "The configuration also specifies the Tensorflow version, which is equal to the runtimeVersion property. The runtimes are periodically updated, but it takes some time for having later Tensorflow versions supported. It is important to note that runtimes before version 2.1 don’t set the chief node correctly. Hence, multi-worker training on AI Platform is only available for runtimes 2.1 and later."
},
{
"code": null,
"e": 10072,
"s": 9355,
"text": "There are situations, on the other hand, when being able to use not yet supported Tensorflow versions is crucial. For instance, there are relevant new features, or they need proper testing before moving them to production. For such cases, Google AI platform provides an option to use custom containers for training. Submitting custom containers for training is almost similar to using the provided runtimes. There are minor details to consider, though. For having correct TF_CONFIG, containerised Tensorflow models require the option useChiefInTfConfig set totrue. Furthermore, the training configuration must specify the image URIs for both chief and worker. The containers are, of course, identical for both cases."
},
{
"code": null,
"e": 10199,
"s": 10072,
"text": "In both official runtime and custom container, AI Platform Training automatically uses the Cloud ML Service Agent credentials."
},
{
"code": null,
"e": 10440,
"s": 10199,
"text": "Before submitting a job to AI Platform, it is practical to test the correctness of the training configuration locally as failed jobs get billed too. Fortunately, it is remarkably straightforward for official runtimes to run locally, execute"
},
{
"code": null,
"e": 10507,
"s": 10440,
"text": "gcloud ai-platform local train --distributed --worker-count $N ..."
},
{
"code": null,
"e": 10700,
"s": 10507,
"text": "The command sets up a correct TF_CONFIG for us. Alas, it also adds a parameter server to the configuration. Tensorflow will warn, but having the parameter servers will not thwart the training."
},
{
"code": null,
"e": 10978,
"s": 10700,
"text": "For containers, setting a correct TF_CONFIG and running the containers is a bit more complicated, but not impracticable. The simplest way to achieve local testing is to use docker-compose for running the chief and worker containers as well as setting the environment variables."
},
{
"code": null,
"e": 11122,
"s": 10978,
"text": "The COMMAND variable is a string containing all the arguments to the training task. Once the docker-compose configuration is complete, just hit"
},
{
"code": null,
"e": 11140,
"s": 11122,
"text": "docker-compose up"
},
{
"code": null,
"e": 11381,
"s": 11140,
"text": "In both cases, if the training requires access to other Google Cloud services, such as Cloud Storage, defining GOOGLE_APPLICATION_CREDENTIALS pointing to the right service account key JSON file must take place before running local training."
},
{
"code": null,
"e": 11805,
"s": 11381,
"text": "Building neural networks in itself is not a simple task. Dealing with distributed computing on the top of that can end up seriously curbing the process. Fortunately, modern deep learning frameworks are built with scalability in mind and thus enabling faster development. Moreover, thanks to the smooth compatibility between Tensorflow and Google Cloud, exploiting this scalability has never been closer to everyone’s reach."
},
{
"code": null,
"e": 12028,
"s": 11805,
"text": "Indeed, this smoothness might not appear so at first glance. For this reason, I have created a simple working example available on Github. Check it out for practical details. Remember, the best way of learning is by doing."
},
{
"code": null,
"e": 12039,
"s": 12028,
"text": "github.com"
},
{
"code": null,
"e": 12076,
"s": 12039,
"text": "Distributed training with TensorFlow"
},
{
"code": null,
"e": 12109,
"s": 12076,
"text": "Multi-worker training with Keras"
},
{
"code": null,
"e": 12144,
"s": 12109,
"text": "TF_CONFIG and distributed training"
},
{
"code": null,
"e": 12194,
"s": 12144,
"text": "Distributed Learning (slides) by Amir H. Payberah"
}
] |
RSpec - Basic Syntax | Let’s take a closer look at the code of our HelloWorld example. First of all, in case it isn’t clear, we are testing the functionality of the HelloWorld class. This of course, is a very simple class that contains only one method say_hello().
Here is the RSpec code again −
describe HelloWorld do
context “When testing the HelloWorld class” do
it "The say_hello method should return 'Hello World'" do
hw = HelloWorld.new
message = hw.say_hello
expect(message).to eq "Hello World!"
end
end
end
The word describe is an RSpec keyword. It is used to define an “Example Group”. You can think of an “Example Group” as a collection of tests. The describe keyword can take a class name and/or string argument. You also need to pass a block argument to describe, this will contain the individual tests, or as they are known in RSpec, the “Examples”. The block is just a Ruby block designated by the Ruby do/end keywords.
The context keyword is similar to describe. It too can accept a class name and/or string argument. You should use a block with context as well. The idea of context is that it encloses tests of a certain type.
For example, you can specify groups of Examples with different contexts like this −
context “When passing bad parameters to the foobar() method”
context “When passing valid parameters to the foobar() method”
context “When testing corner cases with the foobar() method”
The context keyword is not mandatory, but it helps to add more details about the examples that it contains.
The word it is another RSpec keyword which is used to define an “Example”. An example is basically a test or a test case. Again, like describe and context, it accepts both class name and string arguments and should be used with a block argument, designated with do/end. In the case of it, it is customary to only pass a string and block argument. The string argument often uses the word “should” and is meant to describe what specific behavior should happen inside the it block. In other words, it describes that expected outcome is for the Example.
Note the it block from our HelloWorld Example −
it "The say_hello method should return 'Hello World'" do
The string makes it clear what should happen when we call say hello on an instance of the HelloWorld class. This part of the RSpec philosophy, an Example is not just a test, it’s also a specification (a spec). In other words, an Example both documents and tests the expected behavior of your Ruby code.
The expect keyword is used to define an “Expectation” in RSpec. This is a verification step where we check, that a specific expected condition has been met.
From our HelloWorld Example, we have −
expect(message).to eql "Hello World!"
The idea with expect statements is that they read like normal English. You can say this aloud as “Expect the variable message to equal the string ‘Hello World’”. The idea is that its descriptive and also easy to read, even for non-technical stakeholders such as project managers.
The to keyword
The to keyword is used as part of expect statements. Note that you can also use the not_to keyword to express the opposite, when you want the Expectation to be false. You can see that to is used with a dot, expect(message).to, because it actually just a regular Ruby method. In fact, all of the RSpec keywords are really just Ruby methods.
The eql keyword
The eql keyword is a special RSpec keyword called a Matcher. You use Matchers to specify what type of condition you are testing to be true (or false).
In our HelloWorld expect statement, it is clear that eql means string equality. Note that, there are different types of equality operators in Ruby and consequently different corresponding Matchers in RSpec. We will explore the many different types of Matchers in a later section.
9 Lectures
37 mins
Harshit Srivastava
27 Lectures
7 hours
Atul Tiwari
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2036,
"s": 1794,
"text": "Let’s take a closer look at the code of our HelloWorld example. First of all, in case it isn’t clear, we are testing the functionality of the HelloWorld class. This of course, is a very simple class that contains only one method say_hello()."
},
{
"code": null,
"e": 2067,
"s": 2036,
"text": "Here is the RSpec code again −"
},
{
"code": null,
"e": 2352,
"s": 2067,
"text": "describe HelloWorld do \n context “When testing the HelloWorld class” do \n \n it \"The say_hello method should return 'Hello World'\" do \n hw = HelloWorld.new \n message = hw.say_hello \n expect(message).to eq \"Hello World!\" \n end\n \n end \nend"
},
{
"code": null,
"e": 2771,
"s": 2352,
"text": "The word describe is an RSpec keyword. It is used to define an “Example Group”. You can think of an “Example Group” as a collection of tests. The describe keyword can take a class name and/or string argument. You also need to pass a block argument to describe, this will contain the individual tests, or as they are known in RSpec, the “Examples”. The block is just a Ruby block designated by the Ruby do/end keywords."
},
{
"code": null,
"e": 2980,
"s": 2771,
"text": "The context keyword is similar to describe. It too can accept a class name and/or string argument. You should use a block with context as well. The idea of context is that it encloses tests of a certain type."
},
{
"code": null,
"e": 3064,
"s": 2980,
"text": "For example, you can specify groups of Examples with different contexts like this −"
},
{
"code": null,
"e": 3252,
"s": 3064,
"text": "context “When passing bad parameters to the foobar() method” \ncontext “When passing valid parameters to the foobar() method” \ncontext “When testing corner cases with the foobar() method”\n"
},
{
"code": null,
"e": 3360,
"s": 3252,
"text": "The context keyword is not mandatory, but it helps to add more details about the examples that it contains."
},
{
"code": null,
"e": 3910,
"s": 3360,
"text": "The word it is another RSpec keyword which is used to define an “Example”. An example is basically a test or a test case. Again, like describe and context, it accepts both class name and string arguments and should be used with a block argument, designated with do/end. In the case of it, it is customary to only pass a string and block argument. The string argument often uses the word “should” and is meant to describe what specific behavior should happen inside the it block. In other words, it describes that expected outcome is for the Example."
},
{
"code": null,
"e": 3958,
"s": 3910,
"text": "Note the it block from our HelloWorld Example −"
},
{
"code": null,
"e": 4016,
"s": 3958,
"text": "it \"The say_hello method should return 'Hello World'\" do\n"
},
{
"code": null,
"e": 4319,
"s": 4016,
"text": "The string makes it clear what should happen when we call say hello on an instance of the HelloWorld class. This part of the RSpec philosophy, an Example is not just a test, it’s also a specification (a spec). In other words, an Example both documents and tests the expected behavior of your Ruby code."
},
{
"code": null,
"e": 4476,
"s": 4319,
"text": "The expect keyword is used to define an “Expectation” in RSpec. This is a verification step where we check, that a specific expected condition has been met."
},
{
"code": null,
"e": 4515,
"s": 4476,
"text": "From our HelloWorld Example, we have −"
},
{
"code": null,
"e": 4554,
"s": 4515,
"text": "expect(message).to eql \"Hello World!\"\n"
},
{
"code": null,
"e": 4834,
"s": 4554,
"text": "The idea with expect statements is that they read like normal English. You can say this aloud as “Expect the variable message to equal the string ‘Hello World’”. The idea is that its descriptive and also easy to read, even for non-technical stakeholders such as project managers."
},
{
"code": null,
"e": 4850,
"s": 4834,
"text": "The to keyword\n"
},
{
"code": null,
"e": 5190,
"s": 4850,
"text": "The to keyword is used as part of expect statements. Note that you can also use the not_to keyword to express the opposite, when you want the Expectation to be false. You can see that to is used with a dot, expect(message).to, because it actually just a regular Ruby method. In fact, all of the RSpec keywords are really just Ruby methods."
},
{
"code": null,
"e": 5207,
"s": 5190,
"text": "The eql keyword\n"
},
{
"code": null,
"e": 5358,
"s": 5207,
"text": "The eql keyword is a special RSpec keyword called a Matcher. You use Matchers to specify what type of condition you are testing to be true (or false)."
},
{
"code": null,
"e": 5638,
"s": 5358,
"text": "In our HelloWorld expect statement, it is clear that eql means string equality. Note that, there are different types of equality operators in Ruby and consequently different corresponding Matchers in RSpec. We will explore the many different types of Matchers in a later section."
},
{
"code": null,
"e": 5669,
"s": 5638,
"text": "\n 9 Lectures \n 37 mins\n"
},
{
"code": null,
"e": 5689,
"s": 5669,
"text": " Harshit Srivastava"
},
{
"code": null,
"e": 5722,
"s": 5689,
"text": "\n 27 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 5735,
"s": 5722,
"text": " Atul Tiwari"
},
{
"code": null,
"e": 5742,
"s": 5735,
"text": " Print"
},
{
"code": null,
"e": 5753,
"s": 5742,
"text": " Add Notes"
}
] |
Count number of trailing zeros in Binary representation of a number using Bitset in C++ | Given an integer num as input. The goal is to find the number of trailing zeroes in the binary representation of num using bitset.
A bitset stores the bits 0s and 1s in it. It is an array of bits.
For Example
num = 10
Count of number of trailing zeros in Binary representation of a number using
Bitset are: 1
The number 10 in binary is represented as 1010 so trailing zeroes in it is
1.
num = 64
Count of number of trailing zeros in Binary representation of a number using Bitset are: 6
The number 64 in binary is represented as 10000000 so trailing zeroes in it is 6.
Approach used in the below program is as follows −
In this approach we are using bitset. We will set the bitset with num using |. Now traverse bitset using for loop, as soon as the first 1 is encountered then break the loop otherwise increment count for trailing zeroes.
Take an integer num as input.
Take an integer num as input.
Function trailing_zeroes(int num) takes num and returns the count of number of trailing zeros in Binary representation of a number using Bitset.
Function trailing_zeroes(int num) takes num and returns the count of number of trailing zeros in Binary representation of a number using Bitset.
Take the initial count as 0.
Take the initial count as 0.
Take a bitset arr.
Take a bitset arr.
Set it with num as arr |=num.
Set it with num as arr |=num.
Traverse arr using for loop from i=0 to i<64. If arr[i] is 0 then increment count else breaks the loop.
Traverse arr using for loop from i=0 to i<64. If arr[i] is 0 then increment count else breaks the loop.
Return count as result at the end of loop.
Return count as result at the end of loop.
Live Demo
#include <bits/stdc++.h>
using namespace std;
int trailing_zeroes(int num){
int count = 0;
bitset<64> arr;
arr |= num;
for (int i = 0; i < 64; i++){
if (arr[i] == 0){
count++;
} else {
break;
}
}
return count;
}
int main(){
int num = 6;
cout<<"Count of number of trailing zeros in Binary representation of a number using Bitset are: "<<trailing_zeroes(num);
return 0;
}
If we run the above code it will generate the following output −
Count of number of trailing zeros in Binary representation of a number using Bitset are: 1 | [
{
"code": null,
"e": 1193,
"s": 1062,
"text": "Given an integer num as input. The goal is to find the number of trailing zeroes in the binary representation of num using bitset."
},
{
"code": null,
"e": 1259,
"s": 1193,
"text": "A bitset stores the bits 0s and 1s in it. It is an array of bits."
},
{
"code": null,
"e": 1271,
"s": 1259,
"text": "For Example"
},
{
"code": null,
"e": 1280,
"s": 1271,
"text": "num = 10"
},
{
"code": null,
"e": 1371,
"s": 1280,
"text": "Count of number of trailing zeros in Binary representation of a number using\nBitset are: 1"
},
{
"code": null,
"e": 1449,
"s": 1371,
"text": "The number 10 in binary is represented as 1010 so trailing zeroes in it is\n1."
},
{
"code": null,
"e": 1458,
"s": 1449,
"text": "num = 64"
},
{
"code": null,
"e": 1549,
"s": 1458,
"text": "Count of number of trailing zeros in Binary representation of a number using Bitset are: 6"
},
{
"code": null,
"e": 1631,
"s": 1549,
"text": "The number 64 in binary is represented as 10000000 so trailing zeroes in it is 6."
},
{
"code": null,
"e": 1682,
"s": 1631,
"text": "Approach used in the below program is as follows −"
},
{
"code": null,
"e": 1902,
"s": 1682,
"text": "In this approach we are using bitset. We will set the bitset with num using |. Now traverse bitset using for loop, as soon as the first 1 is encountered then break the loop otherwise increment count for trailing zeroes."
},
{
"code": null,
"e": 1932,
"s": 1902,
"text": "Take an integer num as input."
},
{
"code": null,
"e": 1962,
"s": 1932,
"text": "Take an integer num as input."
},
{
"code": null,
"e": 2107,
"s": 1962,
"text": "Function trailing_zeroes(int num) takes num and returns the count of number of trailing zeros in Binary representation of a number using Bitset."
},
{
"code": null,
"e": 2252,
"s": 2107,
"text": "Function trailing_zeroes(int num) takes num and returns the count of number of trailing zeros in Binary representation of a number using Bitset."
},
{
"code": null,
"e": 2281,
"s": 2252,
"text": "Take the initial count as 0."
},
{
"code": null,
"e": 2310,
"s": 2281,
"text": "Take the initial count as 0."
},
{
"code": null,
"e": 2329,
"s": 2310,
"text": "Take a bitset arr."
},
{
"code": null,
"e": 2348,
"s": 2329,
"text": "Take a bitset arr."
},
{
"code": null,
"e": 2378,
"s": 2348,
"text": "Set it with num as arr |=num."
},
{
"code": null,
"e": 2408,
"s": 2378,
"text": "Set it with num as arr |=num."
},
{
"code": null,
"e": 2512,
"s": 2408,
"text": "Traverse arr using for loop from i=0 to i<64. If arr[i] is 0 then increment count else breaks the loop."
},
{
"code": null,
"e": 2616,
"s": 2512,
"text": "Traverse arr using for loop from i=0 to i<64. If arr[i] is 0 then increment count else breaks the loop."
},
{
"code": null,
"e": 2659,
"s": 2616,
"text": "Return count as result at the end of loop."
},
{
"code": null,
"e": 2702,
"s": 2659,
"text": "Return count as result at the end of loop."
},
{
"code": null,
"e": 2713,
"s": 2702,
"text": " Live Demo"
},
{
"code": null,
"e": 3146,
"s": 2713,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nint trailing_zeroes(int num){\n int count = 0;\n bitset<64> arr;\n arr |= num;\n for (int i = 0; i < 64; i++){\n if (arr[i] == 0){\n count++;\n } else {\n break;\n }\n }\n return count;\n}\nint main(){\n int num = 6;\n cout<<\"Count of number of trailing zeros in Binary representation of a number using Bitset are: \"<<trailing_zeroes(num);\n return 0;\n}"
},
{
"code": null,
"e": 3211,
"s": 3146,
"text": "If we run the above code it will generate the following output −"
},
{
"code": null,
"e": 3302,
"s": 3211,
"text": "Count of number of trailing zeros in Binary representation of a number using Bitset are: 1"
}
] |
Scala | Closures - GeeksforGeeks | 05 Nov, 2019
Scala Closures are functions which uses one or more free variables and the return value of this function is dependent of these variable. The free variables are defined outside of the Closure Function and is not included as a parameter of this function. So the difference between a closure function and a normal function is the free variable. A free variable is any kind of variable which is not defined within the function and not passed as the parameter of the function. A free variable is not bound to a function with a valid value. The function does not contain any values for the free variable.Example:If we define a function as shown below:
def example(a:double) = a*p / 100
Now on running the above code we’ll get an error starting not found p. So now we give a value to p outside the function.
// defined the value of p as 10val p = 10 // define this closure.def example(a:double) = a*p / 100
Now the above function is ready to run as the free variable has a value. Now if we run the functions as:
Calling the function: example(10000)
Input: p = 10
Output: double = 1000.0
Now what if the value of the free variable changes, how does the value of the closure function changes?So basically what closure function does is, that it takes the most recent state of the free variable and changes the value of the closure function accordingly.
Input: p = 10
Output: double = 1000.0
Input: p = 20
Output: double = 2000.0
A closure function can further be classified into pure and impure functions, depending on the type of the free variable. If we give the free variable a type var then the variable tends to change the value any time throughout the entire code and thus may result in changing the value of the closure function. Thus this closure is a impure function. On the other-hand if we declare the free variable of the type val then the value of the variable remains constant and thus making the closure function a pure one.
Example:
// Addition of two numbers with // Scala closure // Creating objectobject GFG{ // Main method def main(args: Array[String]) { println( "Final_Sum(1) value = " + sum(1)) println( "Final_Sum(2) value = " + sum(2)) println( "Final_Sum(3) value = " + sum(3)) } var a = 4 // define closure function val sum = (b:Int) => b + a}
Final_Sum(1) value = 5
Final_Sum(2) value = 6
Final_Sum(3) value = 7
Here, In above program function sum is a closure function. var a = 4 is impure closure. the value of a is same and values of b is different.Example:
// Scala closure program to print a string // Creating objectobject GFG{ // Main method def main(args: Array[String]) { var employee = 50 // define closure function val gfg = (name: String) => println(s"Company name is $name"+ s" and total no. of employees are $employee") gfg("geeksforgeeks") }}
Company name is geeksforgeeks and total no. of employees are 50.
Here, In above example gfg is a closure. var employee is mutable variable which can be change.
aarthipa
hoobas20
Picked
Scala
Scala-Method
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
For Loop in Scala
Scala | flatMap Method
Scala | map() method
Scala List filter() method with example
Scala | reduce() Function
String concatenation in Scala
Type Casting in Scala
Scala Tutorial – Learn Scala with Step By Step Guide
Scala List contains() method with example
Scala String substring() method with example | [
{
"code": null,
"e": 26088,
"s": 26060,
"text": "\n05 Nov, 2019"
},
{
"code": null,
"e": 26734,
"s": 26088,
"text": "Scala Closures are functions which uses one or more free variables and the return value of this function is dependent of these variable. The free variables are defined outside of the Closure Function and is not included as a parameter of this function. So the difference between a closure function and a normal function is the free variable. A free variable is any kind of variable which is not defined within the function and not passed as the parameter of the function. A free variable is not bound to a function with a valid value. The function does not contain any values for the free variable.Example:If we define a function as shown below:"
},
{
"code": "def example(a:double) = a*p / 100",
"e": 26768,
"s": 26734,
"text": null
},
{
"code": null,
"e": 26889,
"s": 26768,
"text": "Now on running the above code we’ll get an error starting not found p. So now we give a value to p outside the function."
},
{
"code": "// defined the value of p as 10val p = 10 // define this closure.def example(a:double) = a*p / 100",
"e": 26989,
"s": 26889,
"text": null
},
{
"code": null,
"e": 27094,
"s": 26989,
"text": "Now the above function is ready to run as the free variable has a value. Now if we run the functions as:"
},
{
"code": null,
"e": 27170,
"s": 27094,
"text": "Calling the function: example(10000)\nInput: p = 10\nOutput: double = 1000.0\n"
},
{
"code": null,
"e": 27433,
"s": 27170,
"text": "Now what if the value of the free variable changes, how does the value of the closure function changes?So basically what closure function does is, that it takes the most recent state of the free variable and changes the value of the closure function accordingly."
},
{
"code": null,
"e": 27511,
"s": 27433,
"text": "Input: p = 10\nOutput: double = 1000.0\n\nInput: p = 20\nOutput: double = 2000.0\n"
},
{
"code": null,
"e": 28022,
"s": 27511,
"text": "A closure function can further be classified into pure and impure functions, depending on the type of the free variable. If we give the free variable a type var then the variable tends to change the value any time throughout the entire code and thus may result in changing the value of the closure function. Thus this closure is a impure function. On the other-hand if we declare the free variable of the type val then the value of the variable remains constant and thus making the closure function a pure one."
},
{
"code": null,
"e": 28031,
"s": 28022,
"text": "Example:"
},
{
"code": "// Addition of two numbers with // Scala closure // Creating objectobject GFG{ // Main method def main(args: Array[String]) { println( \"Final_Sum(1) value = \" + sum(1)) println( \"Final_Sum(2) value = \" + sum(2)) println( \"Final_Sum(3) value = \" + sum(3)) } var a = 4 // define closure function val sum = (b:Int) => b + a}",
"e": 28412,
"s": 28031,
"text": null
},
{
"code": null,
"e": 28482,
"s": 28412,
"text": "Final_Sum(1) value = 5\nFinal_Sum(2) value = 6\nFinal_Sum(3) value = 7\n"
},
{
"code": null,
"e": 28631,
"s": 28482,
"text": "Here, In above program function sum is a closure function. var a = 4 is impure closure. the value of a is same and values of b is different.Example:"
},
{
"code": "// Scala closure program to print a string // Creating objectobject GFG{ // Main method def main(args: Array[String]) { var employee = 50 // define closure function val gfg = (name: String) => println(s\"Company name is $name\"+ s\" and total no. of employees are $employee\") gfg(\"geeksforgeeks\") }}",
"e": 29013,
"s": 28631,
"text": null
},
{
"code": null,
"e": 29079,
"s": 29013,
"text": "Company name is geeksforgeeks and total no. of employees are 50.\n"
},
{
"code": null,
"e": 29174,
"s": 29079,
"text": "Here, In above example gfg is a closure. var employee is mutable variable which can be change."
},
{
"code": null,
"e": 29183,
"s": 29174,
"text": "aarthipa"
},
{
"code": null,
"e": 29192,
"s": 29183,
"text": "hoobas20"
},
{
"code": null,
"e": 29199,
"s": 29192,
"text": "Picked"
},
{
"code": null,
"e": 29205,
"s": 29199,
"text": "Scala"
},
{
"code": null,
"e": 29218,
"s": 29205,
"text": "Scala-Method"
},
{
"code": null,
"e": 29224,
"s": 29218,
"text": "Scala"
},
{
"code": null,
"e": 29322,
"s": 29224,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29340,
"s": 29322,
"text": "For Loop in Scala"
},
{
"code": null,
"e": 29363,
"s": 29340,
"text": "Scala | flatMap Method"
},
{
"code": null,
"e": 29384,
"s": 29363,
"text": "Scala | map() method"
},
{
"code": null,
"e": 29424,
"s": 29384,
"text": "Scala List filter() method with example"
},
{
"code": null,
"e": 29450,
"s": 29424,
"text": "Scala | reduce() Function"
},
{
"code": null,
"e": 29480,
"s": 29450,
"text": "String concatenation in Scala"
},
{
"code": null,
"e": 29502,
"s": 29480,
"text": "Type Casting in Scala"
},
{
"code": null,
"e": 29555,
"s": 29502,
"text": "Scala Tutorial – Learn Scala with Step By Step Guide"
},
{
"code": null,
"e": 29597,
"s": 29555,
"text": "Scala List contains() method with example"
}
] |
How to Create Added Variable Plots in R? - GeeksforGeeks | 16 Dec, 2021
In this article, we will discuss how to create an added variable plot in the R Programming Language.
The Added variable plot is an individual plot that displays the relationship between a response variable and one predictor variable in a multiple linear regression model while controlling for the presence of other predictor variables in the model. It is also known as the Partial Regression Plot. These Plots allow us to visualize the relationship between each individual predictor variable and the response variable in a model while holding other predictor variables constant.
Install - install.packages("car")
Now we select desired cran mirror to install the package and then load the package and use the following syntax to create the Added Variable Plot.
Syntax:
avPlots( linear_model )
where,
linear_model: determines the model to be visualized.
Example:
Here is a basic added variable plot example made using the avPlots() function. The dataset used in the example is the diamonds dataset which is provided by the R Language natively.
R
# load library car and tidyverselibrary(car)library(tidyverse) # fit multiple linear regression model# on the datalinear_model <- lm(price ~ depth + table + carat + x + y + z, data = diamonds) # visualize linear regression model using# avPlots functionavPlots(linear_model)
Output:
We can customization the layout of the grid in the avPlots() function by using the layout parameter of the avPlots() function. The layout function takes in a vector as an argument which contains the number of columns and the number of rows variable. These two values determine the layout of the grid.
Syntax:
avPlots( linear_model, layout= c(column, row) )
where,
linear_model: determines the model to be visualized.
column: determines the number of columns in the layout grid.
row: determines the number of rows in the layout grid.
Example:
Here, in this example, we have made added variable plot with a 2X3 grid using layout parameters. The dataset used in the example is the diamonds dataset which is provided by the R Language natively.
R
# load library car and tidyverselibrary(car)library(tidyverse) # fit multiple linear regression model# on the datalinear_model <- lm(price ~ depth + table + carat + x + y + z, data = diamonds) # visualize linear regression model using# avPlots function Use layout parameter for# setting the layout of the plotavPlots(linear_model, layout= c(2,3))
Output:
We can customize the shape, color, and dimension of the plotted objects i.e. lines and points by using tuning parameters of the avPlots() function. We use col, col.lines, pch, and lwd parameters to change the color of plotted points, the color of plotted lines, the shape of plotted data point, and the width of plotted line respectively.
Syntax:
avPlots( linear_model, col, col.lines, pch, lwd)
where,
linear_model: determines the model to be visualized.
col: determines the color of plotted points.
col.lines: determines the color of plotted lines.
pch: determines the shape of plotted points.
lwd: determines the line width for the plotted line.
Example:
Here, is a basic added variable plot with red color points and green color lines with custom shape and width. The dataset used in the example is the diamonds dataset which is provided by the R Language natively.
R
# load library car and tidyverselibrary(car)library(tidyverse) # fit multiple linear regression model on the datalinear_model <- lm(price ~ depth + table + carat + x + y + z, data = diamonds) # visualize linear regression model using avPlots function# Use customization parameters to customize the plotavPlots(linear_model, col="Red", col.lines="green", pch=14, lwd=2)
Output:
sweetyty
Picked
R-Charts
R-Graphs
R-Packages
R-plots
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": "\n16 Dec, 2021"
},
{
"code": null,
"e": 26588,
"s": 26487,
"text": "In this article, we will discuss how to create an added variable plot in the R Programming Language."
},
{
"code": null,
"e": 27066,
"s": 26588,
"text": "The Added variable plot is an individual plot that displays the relationship between a response variable and one predictor variable in a multiple linear regression model while controlling for the presence of other predictor variables in the model. It is also known as the Partial Regression Plot. These Plots allow us to visualize the relationship between each individual predictor variable and the response variable in a model while holding other predictor variables constant."
},
{
"code": null,
"e": 27100,
"s": 27066,
"text": "Install - install.packages(\"car\")"
},
{
"code": null,
"e": 27247,
"s": 27100,
"text": "Now we select desired cran mirror to install the package and then load the package and use the following syntax to create the Added Variable Plot."
},
{
"code": null,
"e": 27255,
"s": 27247,
"text": "Syntax:"
},
{
"code": null,
"e": 27279,
"s": 27255,
"text": "avPlots( linear_model )"
},
{
"code": null,
"e": 27287,
"s": 27279,
"text": "where, "
},
{
"code": null,
"e": 27340,
"s": 27287,
"text": "linear_model: determines the model to be visualized."
},
{
"code": null,
"e": 27349,
"s": 27340,
"text": "Example:"
},
{
"code": null,
"e": 27530,
"s": 27349,
"text": "Here is a basic added variable plot example made using the avPlots() function. The dataset used in the example is the diamonds dataset which is provided by the R Language natively."
},
{
"code": null,
"e": 27532,
"s": 27530,
"text": "R"
},
{
"code": "# load library car and tidyverselibrary(car)library(tidyverse) # fit multiple linear regression model# on the datalinear_model <- lm(price ~ depth + table + carat + x + y + z, data = diamonds) # visualize linear regression model using# avPlots functionavPlots(linear_model)",
"e": 27824,
"s": 27532,
"text": null
},
{
"code": null,
"e": 27832,
"s": 27824,
"text": "Output:"
},
{
"code": null,
"e": 28133,
"s": 27832,
"text": "We can customization the layout of the grid in the avPlots() function by using the layout parameter of the avPlots() function. The layout function takes in a vector as an argument which contains the number of columns and the number of rows variable. These two values determine the layout of the grid."
},
{
"code": null,
"e": 28141,
"s": 28133,
"text": "Syntax:"
},
{
"code": null,
"e": 28189,
"s": 28141,
"text": "avPlots( linear_model, layout= c(column, row) )"
},
{
"code": null,
"e": 28196,
"s": 28189,
"text": "where,"
},
{
"code": null,
"e": 28249,
"s": 28196,
"text": "linear_model: determines the model to be visualized."
},
{
"code": null,
"e": 28310,
"s": 28249,
"text": "column: determines the number of columns in the layout grid."
},
{
"code": null,
"e": 28365,
"s": 28310,
"text": "row: determines the number of rows in the layout grid."
},
{
"code": null,
"e": 28374,
"s": 28365,
"text": "Example:"
},
{
"code": null,
"e": 28573,
"s": 28374,
"text": "Here, in this example, we have made added variable plot with a 2X3 grid using layout parameters. The dataset used in the example is the diamonds dataset which is provided by the R Language natively."
},
{
"code": null,
"e": 28575,
"s": 28573,
"text": "R"
},
{
"code": "# load library car and tidyverselibrary(car)library(tidyverse) # fit multiple linear regression model# on the datalinear_model <- lm(price ~ depth + table + carat + x + y + z, data = diamonds) # visualize linear regression model using# avPlots function Use layout parameter for# setting the layout of the plotavPlots(linear_model, layout= c(2,3))",
"e": 28940,
"s": 28575,
"text": null
},
{
"code": null,
"e": 28949,
"s": 28940,
"text": "Output: "
},
{
"code": null,
"e": 29289,
"s": 28949,
"text": "We can customize the shape, color, and dimension of the plotted objects i.e. lines and points by using tuning parameters of the avPlots() function. We use col, col.lines, pch, and lwd parameters to change the color of plotted points, the color of plotted lines, the shape of plotted data point, and the width of plotted line respectively. "
},
{
"code": null,
"e": 29297,
"s": 29289,
"text": "Syntax:"
},
{
"code": null,
"e": 29346,
"s": 29297,
"text": "avPlots( linear_model, col, col.lines, pch, lwd)"
},
{
"code": null,
"e": 29353,
"s": 29346,
"text": "where,"
},
{
"code": null,
"e": 29406,
"s": 29353,
"text": "linear_model: determines the model to be visualized."
},
{
"code": null,
"e": 29451,
"s": 29406,
"text": "col: determines the color of plotted points."
},
{
"code": null,
"e": 29501,
"s": 29451,
"text": "col.lines: determines the color of plotted lines."
},
{
"code": null,
"e": 29546,
"s": 29501,
"text": "pch: determines the shape of plotted points."
},
{
"code": null,
"e": 29599,
"s": 29546,
"text": "lwd: determines the line width for the plotted line."
},
{
"code": null,
"e": 29608,
"s": 29599,
"text": "Example:"
},
{
"code": null,
"e": 29820,
"s": 29608,
"text": "Here, is a basic added variable plot with red color points and green color lines with custom shape and width. The dataset used in the example is the diamonds dataset which is provided by the R Language natively."
},
{
"code": null,
"e": 29822,
"s": 29820,
"text": "R"
},
{
"code": "# load library car and tidyverselibrary(car)library(tidyverse) # fit multiple linear regression model on the datalinear_model <- lm(price ~ depth + table + carat + x + y + z, data = diamonds) # visualize linear regression model using avPlots function# Use customization parameters to customize the plotavPlots(linear_model, col=\"Red\", col.lines=\"green\", pch=14, lwd=2)",
"e": 30209,
"s": 29822,
"text": null
},
{
"code": null,
"e": 30217,
"s": 30209,
"text": "Output:"
},
{
"code": null,
"e": 30226,
"s": 30217,
"text": "sweetyty"
},
{
"code": null,
"e": 30233,
"s": 30226,
"text": "Picked"
},
{
"code": null,
"e": 30242,
"s": 30233,
"text": "R-Charts"
},
{
"code": null,
"e": 30251,
"s": 30242,
"text": "R-Graphs"
},
{
"code": null,
"e": 30262,
"s": 30251,
"text": "R-Packages"
},
{
"code": null,
"e": 30270,
"s": 30262,
"text": "R-plots"
},
{
"code": null,
"e": 30281,
"s": 30270,
"text": "R Language"
},
{
"code": null,
"e": 30379,
"s": 30281,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30431,
"s": 30379,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 30466,
"s": 30431,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 30504,
"s": 30466,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 30562,
"s": 30504,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 30605,
"s": 30562,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 30654,
"s": 30605,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 30691,
"s": 30654,
"text": "How to import an Excel File into R ?"
},
{
"code": null,
"e": 30717,
"s": 30691,
"text": "Time Series Analysis in R"
},
{
"code": null,
"e": 30734,
"s": 30717,
"text": "R - if statement"
}
] |
Pattern quote(String) method in Java with Examples - GeeksforGeeks | 21 Feb, 2019
quote(String) method of a Pattern class used to returns a literal pattern String for the specified String passed as parameter to method.This method produces a String equivalent to s that can be used to create a Pattern. Metacharacters or escape sequences in the input sequence will be given no special meaning. If you compile the value returned by the quote method, you’ll get a Pattern which matches the literal string that you passed as a parameter to method.\Q and \E mark the beginning and end of the quoted part of the string.
Syntax:
public static String quote(String s)
Parameters: This method accepts a single parameter s which represents the string to be literalized.
Return value: This method returns a literal string replacement for String s.
Below programs illustrate the quote() method:Program 1:
// Java program to demonstrate// Pattern.quote() method import java.util.regex.*; public class GFG { public static void main(String[] args) { // create a REGEX String String REGEX = "ee"; // create the string // in which you want to search String actualString = "geeksforgeeks"; // create equivalent String for REGEX String eqREGEX = Pattern.quote(REGEX); // create a Pattern using eqREGEX Pattern pattern = Pattern.compile(eqREGEX); // get a matcher object Matcher matcher = pattern.matcher(actualString); // print values if match found boolean matchfound = false; while (matcher.find()) { System.out.println("found the Regex in text:" + matcher.group() + " starting index:" + matcher.start() + " and ending index:" + matcher.end()); matchfound = true; } if (!matchfound) { System.out.println("No match found for Regex."); } }}
found the Regex in text:ee starting index:1 and ending index:3
found the Regex in text:ee starting index:9 and ending index:11
Program 2:
// Java program to demonstrate// Pattern.quote() method import java.util.regex.*; public class GFG { public static void main(String[] args) { // create a REGEX String String REGEX = "welcome"; // create the string // in which you want to search String actualString = "welcome to jungle"; // create equivalent String for REGEX String eqREGEX = Pattern.quote(REGEX); // create a Pattern using eqREGEX Pattern pattern = Pattern.compile(eqREGEX); // get a matcher object Matcher matcher = pattern.matcher(actualString); // print values if match found boolean matchfound = false; while (matcher.find()) { System.out.println("match found"); matchfound = true; } if (!matchfound) { System.out.println("No match found"); } }}
match found
Reference: https://docs.oracle.com/javase/10/docs/api/java/util/regex/Pattern.html#quote(java.lang.String)
Java - util package
Java-Functions
Java-Pattern
java-regular-expression
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Internal Working of HashMap in Java
Comparator Interface in Java with Examples
Strings in Java | [
{
"code": null,
"e": 25249,
"s": 25221,
"text": "\n21 Feb, 2019"
},
{
"code": null,
"e": 25781,
"s": 25249,
"text": "quote(String) method of a Pattern class used to returns a literal pattern String for the specified String passed as parameter to method.This method produces a String equivalent to s that can be used to create a Pattern. Metacharacters or escape sequences in the input sequence will be given no special meaning. If you compile the value returned by the quote method, you’ll get a Pattern which matches the literal string that you passed as a parameter to method.\\Q and \\E mark the beginning and end of the quoted part of the string."
},
{
"code": null,
"e": 25789,
"s": 25781,
"text": "Syntax:"
},
{
"code": null,
"e": 25827,
"s": 25789,
"text": "public static String quote(String s)\n"
},
{
"code": null,
"e": 25927,
"s": 25827,
"text": "Parameters: This method accepts a single parameter s which represents the string to be literalized."
},
{
"code": null,
"e": 26004,
"s": 25927,
"text": "Return value: This method returns a literal string replacement for String s."
},
{
"code": null,
"e": 26060,
"s": 26004,
"text": "Below programs illustrate the quote() method:Program 1:"
},
{
"code": "// Java program to demonstrate// Pattern.quote() method import java.util.regex.*; public class GFG { public static void main(String[] args) { // create a REGEX String String REGEX = \"ee\"; // create the string // in which you want to search String actualString = \"geeksforgeeks\"; // create equivalent String for REGEX String eqREGEX = Pattern.quote(REGEX); // create a Pattern using eqREGEX Pattern pattern = Pattern.compile(eqREGEX); // get a matcher object Matcher matcher = pattern.matcher(actualString); // print values if match found boolean matchfound = false; while (matcher.find()) { System.out.println(\"found the Regex in text:\" + matcher.group() + \" starting index:\" + matcher.start() + \" and ending index:\" + matcher.end()); matchfound = true; } if (!matchfound) { System.out.println(\"No match found for Regex.\"); } }}",
"e": 27225,
"s": 26060,
"text": null
},
{
"code": null,
"e": 27353,
"s": 27225,
"text": "found the Regex in text:ee starting index:1 and ending index:3\nfound the Regex in text:ee starting index:9 and ending index:11\n"
},
{
"code": null,
"e": 27364,
"s": 27353,
"text": "Program 2:"
},
{
"code": "// Java program to demonstrate// Pattern.quote() method import java.util.regex.*; public class GFG { public static void main(String[] args) { // create a REGEX String String REGEX = \"welcome\"; // create the string // in which you want to search String actualString = \"welcome to jungle\"; // create equivalent String for REGEX String eqREGEX = Pattern.quote(REGEX); // create a Pattern using eqREGEX Pattern pattern = Pattern.compile(eqREGEX); // get a matcher object Matcher matcher = pattern.matcher(actualString); // print values if match found boolean matchfound = false; while (matcher.find()) { System.out.println(\"match found\"); matchfound = true; } if (!matchfound) { System.out.println(\"No match found\"); } }}",
"e": 28266,
"s": 27364,
"text": null
},
{
"code": null,
"e": 28279,
"s": 28266,
"text": "match found\n"
},
{
"code": null,
"e": 28386,
"s": 28279,
"text": "Reference: https://docs.oracle.com/javase/10/docs/api/java/util/regex/Pattern.html#quote(java.lang.String)"
},
{
"code": null,
"e": 28406,
"s": 28386,
"text": "Java - util package"
},
{
"code": null,
"e": 28421,
"s": 28406,
"text": "Java-Functions"
},
{
"code": null,
"e": 28434,
"s": 28421,
"text": "Java-Pattern"
},
{
"code": null,
"e": 28458,
"s": 28434,
"text": "java-regular-expression"
},
{
"code": null,
"e": 28463,
"s": 28458,
"text": "Java"
},
{
"code": null,
"e": 28468,
"s": 28463,
"text": "Java"
},
{
"code": null,
"e": 28566,
"s": 28468,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28581,
"s": 28566,
"text": "Stream In Java"
},
{
"code": null,
"e": 28602,
"s": 28581,
"text": "Constructors in Java"
},
{
"code": null,
"e": 28621,
"s": 28602,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 28651,
"s": 28621,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 28697,
"s": 28651,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 28714,
"s": 28697,
"text": "Generics in Java"
},
{
"code": null,
"e": 28735,
"s": 28714,
"text": "Introduction to Java"
},
{
"code": null,
"e": 28771,
"s": 28735,
"text": "Internal Working of HashMap in Java"
},
{
"code": null,
"e": 28814,
"s": 28771,
"text": "Comparator Interface in Java with Examples"
}
] |
Assigning function to a variable in C++ - GeeksforGeeks | 19 Apr, 2022
In C++, assigning a function to a variable and using that variable for calling the function as many times as the user wants, increases the code reusability. Below is the syntax for the same:
Syntax:
C++
// Syntax: // Below function is assigned to// the variable funauto fun = [&]() { cout << "inside function" << " variable";};
Program 1: Below is the C++ program to implement a function assigned to a variable:
C++
// C++ program to implement function// assigned to a variable #include <iostream>using namespace std; // Driver Codeint main(){ // Below function i.e., is // assigned to the variable fun auto fun = [&]() { cout << "Inside Function Variable"; }; // Call the function using variable fun(); return 0;}
Inside Function Variable
Program 2: Below is the C++ program to implement a parameterized function assigned to a variable:
C++
// C++ program to implement parameterized// function assigned to a variable#include <iostream>using namespace std; // Driver Codeint main(){ // Passing i and j as 2 parameters auto fun = [&](int i, int j) { cout << "Parameterized Function"; }; // Call the function using variable fun(4, 5); return 0;}
Output:
Parameterized Function
Program 3: Below is the C++ program to implement a function assigned to a variable that returns a value:
C++
// C++ program to implement the function// assigned to a variable returning// some values#include <iostream>using namespace std; // Driver Codeint main(){ // Function taking 2 parameters // and returning sum auto sum = [&](int a, int b) { return a + b; }; // Call the function using variables cout << "The sum is: " << sum(4, 5); return 0;}
The sum is: 9
rkbhola5
CPP-Basics
CPP-Functions
C++
C++ Programs
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Friend class and function in C++
Sorting a vector in C++
std::string class in C++
Header files in C/C++ and its uses
Program to print ASCII Value of a character
How to return multiple values from a function in C or C++?
C++ Program for QuickSort
Sorting a Map by value in C++ STL | [
{
"code": null,
"e": 25343,
"s": 25315,
"text": "\n19 Apr, 2022"
},
{
"code": null,
"e": 25534,
"s": 25343,
"text": "In C++, assigning a function to a variable and using that variable for calling the function as many times as the user wants, increases the code reusability. Below is the syntax for the same:"
},
{
"code": null,
"e": 25542,
"s": 25534,
"text": "Syntax:"
},
{
"code": null,
"e": 25546,
"s": 25542,
"text": "C++"
},
{
"code": "// Syntax: // Below function is assigned to// the variable funauto fun = [&]() { cout << \"inside function\" << \" variable\";};",
"e": 25682,
"s": 25546,
"text": null
},
{
"code": null,
"e": 25766,
"s": 25682,
"text": "Program 1: Below is the C++ program to implement a function assigned to a variable:"
},
{
"code": null,
"e": 25770,
"s": 25766,
"text": "C++"
},
{
"code": "// C++ program to implement function// assigned to a variable #include <iostream>using namespace std; // Driver Codeint main(){ // Below function i.e., is // assigned to the variable fun auto fun = [&]() { cout << \"Inside Function Variable\"; }; // Call the function using variable fun(); return 0;}",
"e": 26118,
"s": 25770,
"text": null
},
{
"code": null,
"e": 26143,
"s": 26118,
"text": "Inside Function Variable"
},
{
"code": null,
"e": 26241,
"s": 26143,
"text": "Program 2: Below is the C++ program to implement a parameterized function assigned to a variable:"
},
{
"code": null,
"e": 26245,
"s": 26241,
"text": "C++"
},
{
"code": "// C++ program to implement parameterized// function assigned to a variable#include <iostream>using namespace std; // Driver Codeint main(){ // Passing i and j as 2 parameters auto fun = [&](int i, int j) { cout << \"Parameterized Function\"; }; // Call the function using variable fun(4, 5); return 0;}",
"e": 26574,
"s": 26245,
"text": null
},
{
"code": null,
"e": 26582,
"s": 26574,
"text": "Output:"
},
{
"code": null,
"e": 26605,
"s": 26582,
"text": "Parameterized Function"
},
{
"code": null,
"e": 26710,
"s": 26605,
"text": "Program 3: Below is the C++ program to implement a function assigned to a variable that returns a value:"
},
{
"code": null,
"e": 26714,
"s": 26710,
"text": "C++"
},
{
"code": "// C++ program to implement the function// assigned to a variable returning// some values#include <iostream>using namespace std; // Driver Codeint main(){ // Function taking 2 parameters // and returning sum auto sum = [&](int a, int b) { return a + b; }; // Call the function using variables cout << \"The sum is: \" << sum(4, 5); return 0;}",
"e": 27093,
"s": 26714,
"text": null
},
{
"code": null,
"e": 27107,
"s": 27093,
"text": "The sum is: 9"
},
{
"code": null,
"e": 27116,
"s": 27107,
"text": "rkbhola5"
},
{
"code": null,
"e": 27127,
"s": 27116,
"text": "CPP-Basics"
},
{
"code": null,
"e": 27141,
"s": 27127,
"text": "CPP-Functions"
},
{
"code": null,
"e": 27145,
"s": 27141,
"text": "C++"
},
{
"code": null,
"e": 27158,
"s": 27145,
"text": "C++ Programs"
},
{
"code": null,
"e": 27162,
"s": 27158,
"text": "CPP"
},
{
"code": null,
"e": 27260,
"s": 27162,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27288,
"s": 27260,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 27308,
"s": 27288,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 27341,
"s": 27308,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 27365,
"s": 27341,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 27390,
"s": 27365,
"text": "std::string class in C++"
},
{
"code": null,
"e": 27425,
"s": 27390,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 27469,
"s": 27425,
"text": "Program to print ASCII Value of a character"
},
{
"code": null,
"e": 27528,
"s": 27469,
"text": "How to return multiple values from a function in C or C++?"
},
{
"code": null,
"e": 27554,
"s": 27528,
"text": "C++ Program for QuickSort"
}
] |
Sequence of Alphabetical Character Letters from A-Z in R - GeeksforGeeks | 23 Sep, 2021
In this article, we are going to discuss how to get a sequence of character letters from A-Z in R programming language.
We will get all letters in lowercase sequence by using the letters function
Syntax:
letters
Example: Return all lowercase letters using letters function
R
# return all lower case letters in sequenceprint(letters)
Output:
[1] “a” “b” “c” “d” “e” “f” “g” “h” “i” “j” “k” “l” “m” “n” “o” “p” “q” “r” “s”
[20] “t” “u” “v” “w” “x” “y” “z”
We will get all letters in uppercase sequence by using LETTERS function.
Syntax:
LETTERS
Example: Return all uppercase letters using LETTERS function
R
# return all upper case letters in sequenceprint(LETTERS)
Output:
[1] “A” “B” “C” “D” “E” “F” “G” “H” “I” “J” “K” “L” “M” “N” “O” “P” “Q” “R” “S”
[20] “T” “U” “V” “W” “X” “Y” “Z”
We can get the subsequence of letters using the index. Index starts with 1 and ends with 26 (since there are 26 letters from a to z). We are getting from letters/LETTERS function.
Syntax:
letters[start:end]
LETTERS[start:end]
Where, start is the starting letter index and end is the ending letter index.
Example: R program to get subsequence letters using index
R
# return all upper case letters from # index 1 to index 12print(LETTERS[1:12]) # return all lower case letters from# index 1 to index 12print(letters[1:12]) # return all upper case letters from# index 5 to index 26print(LETTERS[5:26]) # return all lower case letters from# index 5 to index 26print(letters[5:26])
Output:
[1] “A” “B” “C” “D” “E” “F” “G” “H” “I” “J” “K” “L”
[1] “a” “b” “c” “d” “e” “f” “g” “h” “i” “j” “k” “l”
[1] “E” “F” “G” “H” “I” “J” “K” “L” “M” “N” “O” “P” “Q” “R” “S” “T” “U” “V” “W” “X” “Y” “Z”
[1] “e” “f” “g” “h” “i” “j” “k” “l” “m” “n” “o” “p” “q” “r” “s” “t” “u” “v” “w” “x” “y” “z”
Here in this scenario, we will get the random letters randomly using sample() function. sample() function is used to generate random letters
Syntax:
sample(letters/LETTERS,size)
Where,
letters/LETTERS is a function that is a first parameter to display letters in lower/upper case
size is used to get the number of letters randomly
Example: R program to display random letters
R
# display 20 random lower case letterssample(letters, 20) # display 20 random upper case letterssample(LETTERS, 20) # display 17 random lower case letterssample(letters, 17) # display 17 random upper case letterssample(LETTERS, 17)
Output:
[1] “k” “p” “g” “c” “j” “r” “s” “u” “h” “i” “d” “o” “a” “m” “y” “f” “t” “l” “q” “b”
[1] “D” “A” “K” “G” “W” “E” “N” “C” “P” “T” “M” “S” “F” “V” “B” “R” “H” “Y” “X” “I”
[1] “i” “v” “f” “u” “s” “d” “x” “w” “h” “a” “p” “b” “y” “o” “c” “z” “l”
[1] “Y” “X” “Z” “C” “N” “M” “A” “Q” “V” “R” “O” “E” “B” “J” “F” “U” “I”
Picked
R String-Programs
R-strings
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to 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 Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
How to filter R dataframe by multiple conditions?
Convert Matrix to Dataframe in R | [
{
"code": null,
"e": 26487,
"s": 26459,
"text": "\n23 Sep, 2021"
},
{
"code": null,
"e": 26607,
"s": 26487,
"text": "In this article, we are going to discuss how to get a sequence of character letters from A-Z in R programming language."
},
{
"code": null,
"e": 26683,
"s": 26607,
"text": "We will get all letters in lowercase sequence by using the letters function"
},
{
"code": null,
"e": 26691,
"s": 26683,
"text": "Syntax:"
},
{
"code": null,
"e": 26699,
"s": 26691,
"text": "letters"
},
{
"code": null,
"e": 26760,
"s": 26699,
"text": "Example: Return all lowercase letters using letters function"
},
{
"code": null,
"e": 26762,
"s": 26760,
"text": "R"
},
{
"code": "# return all lower case letters in sequenceprint(letters)",
"e": 26820,
"s": 26762,
"text": null
},
{
"code": null,
"e": 26828,
"s": 26820,
"text": "Output:"
},
{
"code": null,
"e": 26909,
"s": 26828,
"text": " [1] “a” “b” “c” “d” “e” “f” “g” “h” “i” “j” “k” “l” “m” “n” “o” “p” “q” “r” “s”"
},
{
"code": null,
"e": 26942,
"s": 26909,
"text": "[20] “t” “u” “v” “w” “x” “y” “z”"
},
{
"code": null,
"e": 27015,
"s": 26942,
"text": "We will get all letters in uppercase sequence by using LETTERS function."
},
{
"code": null,
"e": 27023,
"s": 27015,
"text": "Syntax:"
},
{
"code": null,
"e": 27031,
"s": 27023,
"text": "LETTERS"
},
{
"code": null,
"e": 27093,
"s": 27031,
"text": "Example: Return all uppercase letters using LETTERS function"
},
{
"code": null,
"e": 27095,
"s": 27093,
"text": "R"
},
{
"code": "# return all upper case letters in sequenceprint(LETTERS)",
"e": 27153,
"s": 27095,
"text": null
},
{
"code": null,
"e": 27161,
"s": 27153,
"text": "Output:"
},
{
"code": null,
"e": 27241,
"s": 27161,
"text": "[1] “A” “B” “C” “D” “E” “F” “G” “H” “I” “J” “K” “L” “M” “N” “O” “P” “Q” “R” “S”"
},
{
"code": null,
"e": 27274,
"s": 27241,
"text": "[20] “T” “U” “V” “W” “X” “Y” “Z”"
},
{
"code": null,
"e": 27454,
"s": 27274,
"text": "We can get the subsequence of letters using the index. Index starts with 1 and ends with 26 (since there are 26 letters from a to z). We are getting from letters/LETTERS function."
},
{
"code": null,
"e": 27462,
"s": 27454,
"text": "Syntax:"
},
{
"code": null,
"e": 27481,
"s": 27462,
"text": "letters[start:end]"
},
{
"code": null,
"e": 27500,
"s": 27481,
"text": "LETTERS[start:end]"
},
{
"code": null,
"e": 27578,
"s": 27500,
"text": "Where, start is the starting letter index and end is the ending letter index."
},
{
"code": null,
"e": 27636,
"s": 27578,
"text": "Example: R program to get subsequence letters using index"
},
{
"code": null,
"e": 27638,
"s": 27636,
"text": "R"
},
{
"code": "# return all upper case letters from # index 1 to index 12print(LETTERS[1:12]) # return all lower case letters from# index 1 to index 12print(letters[1:12]) # return all upper case letters from# index 5 to index 26print(LETTERS[5:26]) # return all lower case letters from# index 5 to index 26print(letters[5:26])",
"e": 27954,
"s": 27638,
"text": null
},
{
"code": null,
"e": 27962,
"s": 27954,
"text": "Output:"
},
{
"code": null,
"e": 28014,
"s": 27962,
"text": "[1] “A” “B” “C” “D” “E” “F” “G” “H” “I” “J” “K” “L”"
},
{
"code": null,
"e": 28066,
"s": 28014,
"text": "[1] “a” “b” “c” “d” “e” “f” “g” “h” “i” “j” “k” “l”"
},
{
"code": null,
"e": 28158,
"s": 28066,
"text": "[1] “E” “F” “G” “H” “I” “J” “K” “L” “M” “N” “O” “P” “Q” “R” “S” “T” “U” “V” “W” “X” “Y” “Z”"
},
{
"code": null,
"e": 28250,
"s": 28158,
"text": "[1] “e” “f” “g” “h” “i” “j” “k” “l” “m” “n” “o” “p” “q” “r” “s” “t” “u” “v” “w” “x” “y” “z”"
},
{
"code": null,
"e": 28391,
"s": 28250,
"text": "Here in this scenario, we will get the random letters randomly using sample() function. sample() function is used to generate random letters"
},
{
"code": null,
"e": 28399,
"s": 28391,
"text": "Syntax:"
},
{
"code": null,
"e": 28428,
"s": 28399,
"text": "sample(letters/LETTERS,size)"
},
{
"code": null,
"e": 28435,
"s": 28428,
"text": "Where,"
},
{
"code": null,
"e": 28531,
"s": 28435,
"text": "letters/LETTERS is a function that is a first parameter to display letters in lower/upper case"
},
{
"code": null,
"e": 28582,
"s": 28531,
"text": "size is used to get the number of letters randomly"
},
{
"code": null,
"e": 28627,
"s": 28582,
"text": "Example: R program to display random letters"
},
{
"code": null,
"e": 28629,
"s": 28627,
"text": "R"
},
{
"code": "# display 20 random lower case letterssample(letters, 20) # display 20 random upper case letterssample(LETTERS, 20) # display 17 random lower case letterssample(letters, 17) # display 17 random upper case letterssample(LETTERS, 17)",
"e": 28864,
"s": 28629,
"text": null
},
{
"code": null,
"e": 28872,
"s": 28864,
"text": "Output:"
},
{
"code": null,
"e": 28956,
"s": 28872,
"text": "[1] “k” “p” “g” “c” “j” “r” “s” “u” “h” “i” “d” “o” “a” “m” “y” “f” “t” “l” “q” “b”"
},
{
"code": null,
"e": 29040,
"s": 28956,
"text": "[1] “D” “A” “K” “G” “W” “E” “N” “C” “P” “T” “M” “S” “F” “V” “B” “R” “H” “Y” “X” “I”"
},
{
"code": null,
"e": 29112,
"s": 29040,
"text": "[1] “i” “v” “f” “u” “s” “d” “x” “w” “h” “a” “p” “b” “y” “o” “c” “z” “l”"
},
{
"code": null,
"e": 29184,
"s": 29112,
"text": "[1] “Y” “X” “Z” “C” “N” “M” “A” “Q” “V” “R” “O” “E” “B” “J” “F” “U” “I”"
},
{
"code": null,
"e": 29191,
"s": 29184,
"text": "Picked"
},
{
"code": null,
"e": 29209,
"s": 29191,
"text": "R String-Programs"
},
{
"code": null,
"e": 29219,
"s": 29209,
"text": "R-strings"
},
{
"code": null,
"e": 29230,
"s": 29219,
"text": "R Language"
},
{
"code": null,
"e": 29241,
"s": 29230,
"text": "R Programs"
},
{
"code": null,
"e": 29339,
"s": 29241,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29391,
"s": 29339,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 29426,
"s": 29391,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 29464,
"s": 29426,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 29522,
"s": 29464,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 29565,
"s": 29522,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 29623,
"s": 29565,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 29666,
"s": 29623,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 29715,
"s": 29666,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 29765,
"s": 29715,
"text": "How to filter R dataframe by multiple conditions?"
}
] |
How to Run R scripts in Jupyter. A short tutorial on how to install the... | by Angelica Lo Duca | Towards Data Science | The Jupyter Notebook is a Web application which permits to create live code in different languages. Usually, developers exploit the Jupyter Notebook to write code in Python. However, Jupyter also supports other programming languages, including Java, R, Julia, Matlab, Octave, Scheme, Processing, Scala and many others.
Jupyter does not provide any compiler or interpreter. Instead, it is a process which communicates with the actual compiler/interpreter. In practice, it sends the code to the compiler/interpreter and gets back the result.
In order to run a code snippet (in a given language) in a Jupyter cell, it is sufficient to install the corresponding kernel for that language.
In this tutorial, I illustrate how to install the Jupyter Kernel for the R software.
Firstly, I need to install the R software on your computer. I can download the R software from its official Web site. Once installed, I can open a terminal and launch R, simply by typing R on the console, followed by the Enter command.
Note: if you use Mac OS, you need to run the R software from the directory where R is installed. Typically, the directory is
/Library/Frameworks/R.framework/Versions/<version>/Resources/bin
where <version> indicates the R version. I can run R by typing the following command on the console:
./R
Once launched the R console, I must download the devtools package through the following command:
install.packages("devtools")
I select the mirror number (e.g. Italy is 48) and I press Enter.
Once the installation is complete, I can install the IRKernel from Github. I run the following command:
devtools::install_github("IRkernel/IRkernel")
It may happen that the previous command fails. In this case, I can force installation, through the following command:
devtools::install_github("IRkernel/IRkernel", force=TRUE)
After that I install the IRkernel:
IRkernel::installspec()
Now I can quit R by typing
quit()
and I can run Jupyter. When Jupyter opens in the browser, I can click on New, on the top right corner and select R as kernel. Happy Enjoyment :)
In this tutorial, I have illustrated how to install the R Kernel in Jupyter. The procedure is quite simple and fast.
If you still experience problems for installation, check out my Youtube tutorial on the installation.
If you wanted to be updated on my research and other activities, you can follow me on Twitter, Youtube and and Github. | [
{
"code": null,
"e": 491,
"s": 172,
"text": "The Jupyter Notebook is a Web application which permits to create live code in different languages. Usually, developers exploit the Jupyter Notebook to write code in Python. However, Jupyter also supports other programming languages, including Java, R, Julia, Matlab, Octave, Scheme, Processing, Scala and many others."
},
{
"code": null,
"e": 712,
"s": 491,
"text": "Jupyter does not provide any compiler or interpreter. Instead, it is a process which communicates with the actual compiler/interpreter. In practice, it sends the code to the compiler/interpreter and gets back the result."
},
{
"code": null,
"e": 856,
"s": 712,
"text": "In order to run a code snippet (in a given language) in a Jupyter cell, it is sufficient to install the corresponding kernel for that language."
},
{
"code": null,
"e": 941,
"s": 856,
"text": "In this tutorial, I illustrate how to install the Jupyter Kernel for the R software."
},
{
"code": null,
"e": 1177,
"s": 941,
"text": "Firstly, I need to install the R software on your computer. I can download the R software from its official Web site. Once installed, I can open a terminal and launch R, simply by typing R on the console, followed by the Enter command."
},
{
"code": null,
"e": 1302,
"s": 1177,
"text": "Note: if you use Mac OS, you need to run the R software from the directory where R is installed. Typically, the directory is"
},
{
"code": null,
"e": 1367,
"s": 1302,
"text": "/Library/Frameworks/R.framework/Versions/<version>/Resources/bin"
},
{
"code": null,
"e": 1468,
"s": 1367,
"text": "where <version> indicates the R version. I can run R by typing the following command on the console:"
},
{
"code": null,
"e": 1472,
"s": 1468,
"text": "./R"
},
{
"code": null,
"e": 1569,
"s": 1472,
"text": "Once launched the R console, I must download the devtools package through the following command:"
},
{
"code": null,
"e": 1598,
"s": 1569,
"text": "install.packages(\"devtools\")"
},
{
"code": null,
"e": 1663,
"s": 1598,
"text": "I select the mirror number (e.g. Italy is 48) and I press Enter."
},
{
"code": null,
"e": 1767,
"s": 1663,
"text": "Once the installation is complete, I can install the IRKernel from Github. I run the following command:"
},
{
"code": null,
"e": 1813,
"s": 1767,
"text": "devtools::install_github(\"IRkernel/IRkernel\")"
},
{
"code": null,
"e": 1931,
"s": 1813,
"text": "It may happen that the previous command fails. In this case, I can force installation, through the following command:"
},
{
"code": null,
"e": 1989,
"s": 1931,
"text": "devtools::install_github(\"IRkernel/IRkernel\", force=TRUE)"
},
{
"code": null,
"e": 2024,
"s": 1989,
"text": "After that I install the IRkernel:"
},
{
"code": null,
"e": 2048,
"s": 2024,
"text": "IRkernel::installspec()"
},
{
"code": null,
"e": 2075,
"s": 2048,
"text": "Now I can quit R by typing"
},
{
"code": null,
"e": 2082,
"s": 2075,
"text": "quit()"
},
{
"code": null,
"e": 2227,
"s": 2082,
"text": "and I can run Jupyter. When Jupyter opens in the browser, I can click on New, on the top right corner and select R as kernel. Happy Enjoyment :)"
},
{
"code": null,
"e": 2344,
"s": 2227,
"text": "In this tutorial, I have illustrated how to install the R Kernel in Jupyter. The procedure is quite simple and fast."
},
{
"code": null,
"e": 2446,
"s": 2344,
"text": "If you still experience problems for installation, check out my Youtube tutorial on the installation."
}
] |
Passing Arrays as Function Arguments in C | If you want to pass a single-dimension array as an argument in a function, you would have to declare a formal parameter in one of following three ways and all three declaration methods produce similar results because each tells the compiler that an integer pointer is going to be received. Similarly, you can pass multi-dimensional arrays as formal parameters.
Formal parameters as a pointer −
void myFunction(int *param) {
.
.
.
}
Formal parameters as a sized array −
void myFunction(int param[10]) {
.
.
.
}
Formal parameters as an unsized array −
void myFunction(int param[]) {
.
.
.
}
Now, consider the following function, which takes an array as an argument along with another argument and based on the passed arguments, it returns the average of the numbers passed through the array as follows −
double getAverage(int arr[], int size) {
int i;
double avg;
double sum = 0;
for (i = 0; i < size; ++i) {
sum += arr[i];
}
avg = sum / size;
return avg;
}
Now, let us call the above function as follows −
#include <stdio.h>
/* function declaration */
double getAverage(int arr[], int size);
int main () {
/* an int array with 5 elements */
int balance[5] = {1000, 2, 3, 17, 50};
double avg;
/* pass pointer to the array as an argument */
avg = getAverage( balance, 5 ) ;
/* output the returned value */
printf( "Average value is: %f ", avg );
return 0;
}
When the above code is compiled together and executed, it produces the following result −
Average value is: 214.400000
As you can see, the length of the array doesn't matter as far as the function is concerned because C performs no bounds checking for formal parameters.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2445,
"s": 2084,
"text": "If you want to pass a single-dimension array as an argument in a function, you would have to declare a formal parameter in one of following three ways and all three declaration methods produce similar results because each tells the compiler that an integer pointer is going to be received. Similarly, you can pass multi-dimensional arrays as formal parameters."
},
{
"code": null,
"e": 2478,
"s": 2445,
"text": "Formal parameters as a pointer −"
},
{
"code": null,
"e": 2525,
"s": 2478,
"text": "void myFunction(int *param) {\n .\n .\n .\n}"
},
{
"code": null,
"e": 2562,
"s": 2525,
"text": "Formal parameters as a sized array −"
},
{
"code": null,
"e": 2612,
"s": 2562,
"text": "void myFunction(int param[10]) {\n .\n .\n .\n}"
},
{
"code": null,
"e": 2652,
"s": 2612,
"text": "Formal parameters as an unsized array −"
},
{
"code": null,
"e": 2700,
"s": 2652,
"text": "void myFunction(int param[]) {\n .\n .\n .\n}"
},
{
"code": null,
"e": 2913,
"s": 2700,
"text": "Now, consider the following function, which takes an array as an argument along with another argument and based on the passed arguments, it returns the average of the numbers passed through the array as follows −"
},
{
"code": null,
"e": 3098,
"s": 2913,
"text": "double getAverage(int arr[], int size) {\n\n int i;\n double avg;\n double sum = 0;\n\n for (i = 0; i < size; ++i) {\n sum += arr[i];\n }\n\n avg = sum / size;\n\n return avg;\n}"
},
{
"code": null,
"e": 3147,
"s": 3098,
"text": "Now, let us call the above function as follows −"
},
{
"code": null,
"e": 3533,
"s": 3147,
"text": "#include <stdio.h>\n \n/* function declaration */\ndouble getAverage(int arr[], int size);\n\nint main () {\n\n /* an int array with 5 elements */\n int balance[5] = {1000, 2, 3, 17, 50};\n double avg;\n\n /* pass pointer to the array as an argument */\n avg = getAverage( balance, 5 ) ;\n \n /* output the returned value */\n printf( \"Average value is: %f \", avg );\n \n return 0;\n}"
},
{
"code": null,
"e": 3623,
"s": 3533,
"text": "When the above code is compiled together and executed, it produces the following result −"
},
{
"code": null,
"e": 3653,
"s": 3623,
"text": "Average value is: 214.400000\n"
},
{
"code": null,
"e": 3805,
"s": 3653,
"text": "As you can see, the length of the array doesn't matter as far as the function is concerned because C performs no bounds checking for formal parameters."
},
{
"code": null,
"e": 3812,
"s": 3805,
"text": " Print"
},
{
"code": null,
"e": 3823,
"s": 3812,
"text": " Add Notes"
}
] |
Using a free API to get geolocation information from a public IP address | by Abid Ebna Saif Utsha | Towards Data Science | This article is a demonstration of a project I have created using a free API. Initially, the purpose was to understand and learn more about API calls. I am working as an intern in a company which works with geospatial information. I got the inspiration to work on this from working there. I will try to explain the code and method I used in brief and along with a potential business perspective. Again, this is free and no additional verifications are needed. Let’s begin!
The business perspective of this project is to identify an area where people are accessing websites, basically audience segmentation. For example, an e-commerce website wants to know how many people in New York are browsing their website. So, imagining I am the owner of that e-commerce company, I am selling gaming gadgets online and want to know roughly how many people are accessing my website from the cities or all over the world. I only have the consumer’s public IP address. Now, I want to know from which state and countries my consumers belong to. This API will give me latitude and longitude from my consumer’s public IP Address. From there I can use geopy (Nominatim) to get address using that derived latitude and longitude. Quite easy, right. Now that the thinking and identifying the resources are done, let’s drive into some python code!
Wait a minute, I don’t have all the consumers public IP address, I was just imagining owning a gaming gadgets company. No worries, Python can support my imagination, let’s see how.
import randomimport socketimport structsocket.inet_ntoa(struct.pack('>I', random.randint(1, 0xffffffff)))
If you run the above lines in a Jupiter Notebook, you will see the following output.
Alright, all of these are great, but looking for one user at a time would be time-consuming and difficult, let’s make an automated python script which will generate 100 random IP addresses like these and look for their location and save the results in a CSV file. I have used VScode while developing this project, but for simplicity and ease of use, I will provide a colab notebook at the end which will contain source code. Also, I will give the GitHub link at the end as well.
To do that I would need the following libraries to be imported. requests, json are needed for the API calls, global_land_mask is used to verify the latitude and longitude(will be discussed later).
import requestsimport pandas as pdimport numpy as npimport jsonimport randomimport socketimport structfrom geopy.geocoders import Nominatimimport osfrom global_land_mask import globe
If you face any error while importing the libraries, just use the following commands in your terminal.
pip install <library> #(pip install global-land-mask)orconda install <library>
The following is the function that generates 100 random IP addresses.
def getting_ip_address(): """This function returns a list of random IP address""" new, explored=[],[] i=0 while i<100: ip = socket.inet_ntoa(struct.pack('>I', random.randint(1, 0xffffffff))) if ip in explored: continue else: new.append(ip) i+=1 new = pd.DataFrame(new, columns=['ip']) return new
I also created a list which stores generated IP Address which will be later used to check whether that IP Address already created before or not. I have converted the final list into a pandas DataFrame as I am more comfortable in working with pandas. Now, the next step would be to identify and get their latitude and longitude information.
def getting_ip(row): """This function calls the api and return the response""" url = f"https://freegeoip.app/json/{row}" # getting records from getting ip address headers = { 'accept': "application/json", 'content-type': "application/json" } response = requests.request("GET", url, headers=headers) respond = json.loads(response.text) return respond
This function takes each IP address and sends the request to the API to get latitude and longitude information along with other information. A sample output for one location is given below.
The output is in JSON format and is saved as a column in a pandas datagram. After that from that column, information like latitude, longitude, and tim_zone are deduced, which is shown below:
def get_information(): """This function calls both api and add information to the pandas dataframe column""" new = getting_ip_address() new['info'] = new['ip'].apply(lambda row: getting_ip(row)) new['time_zone'] = new['info'].apply(lambda row: row['time_zone']) new['latitude'] = new['info'].apply(lambda row: row['latitude']) new['longitude'] = new['info'].apply(lambda row: row['longitude']) new['on_land'] = new.apply(lambda row: globe.is_land(row['latitude'],row['longitude']),axis=1) new = new[new['latitude']!=0] new = new[new['on_land']==True] new['address'] = new.apply(lambda row: getting_city_nominatim(row),axis=1) return new
This is the main information extracting function which calls two API and processes their information. First, remember generating 100 random IP address function shown above, that function is called and a dataframe containing IP addresses are returned. After that using lambda function to call API for each IP addresses and store that result in a column named ‘info’. After that, from that column for each IP address, time_zone, latitude, longitude is derived. Now, it comes to before mentioned global_land_mask library. I want to check whether the latitude and longitude fall under land areas or in the ocean. This globe.is_land(latitude, longitude) returns boolean True or False for each row which is saved in another column named on_land, later a simple filter has been done on dataframe to remove if any latitude is exactly 0 and if the latitude and longitude are in the ocean. After that calling the geopy Nominatim API to get a deeper address. The function that calls the geopy API is shown below:
def getting_city_nominatim(row): """This function calls the geopy api and return the json address output""" try: lat = row['latitude'] lon = row['longitude'] geolocator = Nominatim(user_agent="my-application") location = geolocator.reverse(f"""{lat,lon}""") address = location.raw['address'] return address except: print('timeout')
This function calls geopy Nominatim using latitude and longitude derived from earlier API calls. For the same IP address is shown as a sample before ‘192.168.10.111’ returned latitude and longitude, the below image is showing a sample nominatim call using that latitude and longitude.
Now, I have all the building blocks ready, I need to save the results in CSV. the function for that is given below:
def append_to_existing_df(new): """This function appends the new ip addresses to the dataframe""" if os.path.isfile(f'{os.path.abspath("")}\location_of_ip_address.csv'): new.to_csv('location_of_ip_address.csv', mode='a', header=False,index=False) else: new.to_csv('location_of_ip_address.csv', mode='w', header=True,\ columns=['ip','info','time_zone','latitude','longitude','address'],index=False)def deleting_duplicate_entries(): """This function makes sure there are no duplicate ip addresses saved in the csv file""" df = pd.read_csv('location_of_ip_address.csv') df.sort_values('ip',inplace=True) df.drop_duplicates(subset='ip',keep='first',inplace=True) df.to_csv('location_of_ip_address.csv',index=False)
The first function above looks for whether there is a CSV file existing or not, if the file exists then the results are appended to that existing file, if the file does not exist in that directory then a new CSV file is created. os.path.abspath(“”) returns the path for the current directory where the python file is. and os.path.isfile() check if the file exists or not. After saving them and running the program multiple times, I noticed several IP addresses contains the same because the initial duplicate check was only for 100 random generate IP addresses. But now, I have run the program multiple times and the same IP address is found in multiple places. To remove that, an add on function was added later which read the whole CSV in a pandas dataframe and drop duplicates value and save the file back.
Now, that we have all the functions ready, the below block is showing the main function which calls all the functions created before.
def main(): """main function""" new = get_information() append_to_existing_df(new) deleting_duplicate_entries()if __name__ == '__main__': main()
After running, this creates a CSV which results are given below:
So, this was the project I created. I just gave an overview of how I came up with this idea, created materials, and automated a process. I didn’t delve into too many technical details. I am planning to write separately for that. This can be further improved and modified, for example, further automated the process so that it runs every day at certain times. The source code shown here is given in colab. Also, it is available in GitHub.
Thank you very much for reading the article. This is my first time writing for Medium, I will try to improve my writing and publish more often with some projects and ideas. | [
{
"code": null,
"e": 645,
"s": 172,
"text": "This article is a demonstration of a project I have created using a free API. Initially, the purpose was to understand and learn more about API calls. I am working as an intern in a company which works with geospatial information. I got the inspiration to work on this from working there. I will try to explain the code and method I used in brief and along with a potential business perspective. Again, this is free and no additional verifications are needed. Let’s begin!"
},
{
"code": null,
"e": 1498,
"s": 645,
"text": "The business perspective of this project is to identify an area where people are accessing websites, basically audience segmentation. For example, an e-commerce website wants to know how many people in New York are browsing their website. So, imagining I am the owner of that e-commerce company, I am selling gaming gadgets online and want to know roughly how many people are accessing my website from the cities or all over the world. I only have the consumer’s public IP address. Now, I want to know from which state and countries my consumers belong to. This API will give me latitude and longitude from my consumer’s public IP Address. From there I can use geopy (Nominatim) to get address using that derived latitude and longitude. Quite easy, right. Now that the thinking and identifying the resources are done, let’s drive into some python code!"
},
{
"code": null,
"e": 1679,
"s": 1498,
"text": "Wait a minute, I don’t have all the consumers public IP address, I was just imagining owning a gaming gadgets company. No worries, Python can support my imagination, let’s see how."
},
{
"code": null,
"e": 1785,
"s": 1679,
"text": "import randomimport socketimport structsocket.inet_ntoa(struct.pack('>I', random.randint(1, 0xffffffff)))"
},
{
"code": null,
"e": 1870,
"s": 1785,
"text": "If you run the above lines in a Jupiter Notebook, you will see the following output."
},
{
"code": null,
"e": 2349,
"s": 1870,
"text": "Alright, all of these are great, but looking for one user at a time would be time-consuming and difficult, let’s make an automated python script which will generate 100 random IP addresses like these and look for their location and save the results in a CSV file. I have used VScode while developing this project, but for simplicity and ease of use, I will provide a colab notebook at the end which will contain source code. Also, I will give the GitHub link at the end as well."
},
{
"code": null,
"e": 2546,
"s": 2349,
"text": "To do that I would need the following libraries to be imported. requests, json are needed for the API calls, global_land_mask is used to verify the latitude and longitude(will be discussed later)."
},
{
"code": null,
"e": 2729,
"s": 2546,
"text": "import requestsimport pandas as pdimport numpy as npimport jsonimport randomimport socketimport structfrom geopy.geocoders import Nominatimimport osfrom global_land_mask import globe"
},
{
"code": null,
"e": 2832,
"s": 2729,
"text": "If you face any error while importing the libraries, just use the following commands in your terminal."
},
{
"code": null,
"e": 2912,
"s": 2832,
"text": "pip install <library> #(pip install global-land-mask)orconda install <library>"
},
{
"code": null,
"e": 2982,
"s": 2912,
"text": "The following is the function that generates 100 random IP addresses."
},
{
"code": null,
"e": 3346,
"s": 2982,
"text": "def getting_ip_address(): \"\"\"This function returns a list of random IP address\"\"\" new, explored=[],[] i=0 while i<100: ip = socket.inet_ntoa(struct.pack('>I', random.randint(1, 0xffffffff))) if ip in explored: continue else: new.append(ip) i+=1 new = pd.DataFrame(new, columns=['ip']) return new"
},
{
"code": null,
"e": 3686,
"s": 3346,
"text": "I also created a list which stores generated IP Address which will be later used to check whether that IP Address already created before or not. I have converted the final list into a pandas DataFrame as I am more comfortable in working with pandas. Now, the next step would be to identify and get their latitude and longitude information."
},
{
"code": null,
"e": 4081,
"s": 3686,
"text": "def getting_ip(row): \"\"\"This function calls the api and return the response\"\"\" url = f\"https://freegeoip.app/json/{row}\" # getting records from getting ip address headers = { 'accept': \"application/json\", 'content-type': \"application/json\" } response = requests.request(\"GET\", url, headers=headers) respond = json.loads(response.text) return respond"
},
{
"code": null,
"e": 4271,
"s": 4081,
"text": "This function takes each IP address and sends the request to the API to get latitude and longitude information along with other information. A sample output for one location is given below."
},
{
"code": null,
"e": 4462,
"s": 4271,
"text": "The output is in JSON format and is saved as a column in a pandas datagram. After that from that column, information like latitude, longitude, and tim_zone are deduced, which is shown below:"
},
{
"code": null,
"e": 5132,
"s": 4462,
"text": "def get_information(): \"\"\"This function calls both api and add information to the pandas dataframe column\"\"\" new = getting_ip_address() new['info'] = new['ip'].apply(lambda row: getting_ip(row)) new['time_zone'] = new['info'].apply(lambda row: row['time_zone']) new['latitude'] = new['info'].apply(lambda row: row['latitude']) new['longitude'] = new['info'].apply(lambda row: row['longitude']) new['on_land'] = new.apply(lambda row: globe.is_land(row['latitude'],row['longitude']),axis=1) new = new[new['latitude']!=0] new = new[new['on_land']==True] new['address'] = new.apply(lambda row: getting_city_nominatim(row),axis=1) return new"
},
{
"code": null,
"e": 6134,
"s": 5132,
"text": "This is the main information extracting function which calls two API and processes their information. First, remember generating 100 random IP address function shown above, that function is called and a dataframe containing IP addresses are returned. After that using lambda function to call API for each IP addresses and store that result in a column named ‘info’. After that, from that column for each IP address, time_zone, latitude, longitude is derived. Now, it comes to before mentioned global_land_mask library. I want to check whether the latitude and longitude fall under land areas or in the ocean. This globe.is_land(latitude, longitude) returns boolean True or False for each row which is saved in another column named on_land, later a simple filter has been done on dataframe to remove if any latitude is exactly 0 and if the latitude and longitude are in the ocean. After that calling the geopy Nominatim API to get a deeper address. The function that calls the geopy API is shown below:"
},
{
"code": null,
"e": 6524,
"s": 6134,
"text": "def getting_city_nominatim(row): \"\"\"This function calls the geopy api and return the json address output\"\"\" try: lat = row['latitude'] lon = row['longitude'] geolocator = Nominatim(user_agent=\"my-application\") location = geolocator.reverse(f\"\"\"{lat,lon}\"\"\") address = location.raw['address'] return address except: print('timeout')"
},
{
"code": null,
"e": 6809,
"s": 6524,
"text": "This function calls geopy Nominatim using latitude and longitude derived from earlier API calls. For the same IP address is shown as a sample before ‘192.168.10.111’ returned latitude and longitude, the below image is showing a sample nominatim call using that latitude and longitude."
},
{
"code": null,
"e": 6925,
"s": 6809,
"text": "Now, I have all the building blocks ready, I need to save the results in CSV. the function for that is given below:"
},
{
"code": null,
"e": 7692,
"s": 6925,
"text": "def append_to_existing_df(new): \"\"\"This function appends the new ip addresses to the dataframe\"\"\" if os.path.isfile(f'{os.path.abspath(\"\")}\\location_of_ip_address.csv'): new.to_csv('location_of_ip_address.csv', mode='a', header=False,index=False) else: new.to_csv('location_of_ip_address.csv', mode='w', header=True,\\ columns=['ip','info','time_zone','latitude','longitude','address'],index=False)def deleting_duplicate_entries(): \"\"\"This function makes sure there are no duplicate ip addresses saved in the csv file\"\"\" df = pd.read_csv('location_of_ip_address.csv') df.sort_values('ip',inplace=True) df.drop_duplicates(subset='ip',keep='first',inplace=True) df.to_csv('location_of_ip_address.csv',index=False)"
},
{
"code": null,
"e": 8502,
"s": 7692,
"text": "The first function above looks for whether there is a CSV file existing or not, if the file exists then the results are appended to that existing file, if the file does not exist in that directory then a new CSV file is created. os.path.abspath(“”) returns the path for the current directory where the python file is. and os.path.isfile() check if the file exists or not. After saving them and running the program multiple times, I noticed several IP addresses contains the same because the initial duplicate check was only for 100 random generate IP addresses. But now, I have run the program multiple times and the same IP address is found in multiple places. To remove that, an add on function was added later which read the whole CSV in a pandas dataframe and drop duplicates value and save the file back."
},
{
"code": null,
"e": 8636,
"s": 8502,
"text": "Now, that we have all the functions ready, the below block is showing the main function which calls all the functions created before."
},
{
"code": null,
"e": 8796,
"s": 8636,
"text": "def main(): \"\"\"main function\"\"\" new = get_information() append_to_existing_df(new) deleting_duplicate_entries()if __name__ == '__main__': main()"
},
{
"code": null,
"e": 8861,
"s": 8796,
"text": "After running, this creates a CSV which results are given below:"
},
{
"code": null,
"e": 9299,
"s": 8861,
"text": "So, this was the project I created. I just gave an overview of how I came up with this idea, created materials, and automated a process. I didn’t delve into too many technical details. I am planning to write separately for that. This can be further improved and modified, for example, further automated the process so that it runs every day at certain times. The source code shown here is given in colab. Also, it is available in GitHub."
}
] |
Implementing Flutter Gauge - GeeksforGeeks | 15 Feb, 2021
Flutter gauge is an information perception widget written in dart language to make a modern, interactive, and animated gauge check and is utilized to make excellent portable application user interfaces utilizing Flutter. There is an alternate style of gauge in flutter.
Following are the steps to follow in order to implement the Flutter Gauge in the Flutter app:
Step 1: Add the following dependencies to pubspec.yaml file.
dependencies:
flutter_gauge: ^1.0.8
Step 2: Import the following packages
import 'package:flutter_gauge/flutter_gauge.dart';
Step 3: Run flutter packages in the root directory of your app.
Step 4: Next, enable AndriodX by adding the following to your grade.properties file:
org.gradle.jvmargs=-Xmx1536M
android.enableR8=true
android.useAndroidX=true
android.enableJetifier=true
Step 5: Now, the following code needs to be implemented in the respective dart file
Dart
import 'package:flutter/material.dart';import 'package:flutter_gauge/flutter_gauge.dart'; class FlutterGaugePage extends StatefulWidget { @override _FlutterGaugePageState createState() => _FlutterGaugePageState();} class _FlutterGaugePageState extends State<FlutterGaugePage> { @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.white, appBar: AppBar( title: Text("GeeksforGeeks"), backgroundColor: Color(0xFF4CAF50), automaticallyImplyLeading: false, centerTitle: true, ), body: SingleChildScrollView( child: Column( children: <Widget>[ Row( children: <Widget>[ Expanded( child: Center( child: FlutterGauge( handSize: 25,index: 40.0, end: 100,number: Number.endAndCenterAndStart, circleColor: Color(0xFF47505F), secondsMarker: SecondsMarker.secondsAndMinute, counterStyle: TextStyle( color: Colors.black,fontSize: 20,) ), ) ), Expanded( child: FlutterGauge( secondsMarker: SecondsMarker.none, hand: Hand.short, number: Number.none, index: 66.0,circleColor: Color(0xFF9DC1DC), counterStyle: TextStyle(color: Colors.black, fontSize: 25 ), counterAlign: CounterAlign.center, isDecimal: false )), ], ), Row( children: <Widget>[ Expanded( child: FlutterGauge( handSize: 25,index: 70.0,end: 100, number: Number.endAndCenterAndStart, secondsMarker: SecondsMarker.secondsAndMinute ,hand: Hand.short, circleColor: Color(0xFF59EA50), counterStyle: TextStyle(color: Colors.black,fontSize: 20,) ), ), Expanded( child: FlutterGauge( handSize: 25,index: 100.0,end: 500, number: Number.endAndStart, secondsMarker: SecondsMarker.minutes, isCircle: false, counterStyle: TextStyle(color: Colors.black,fontSize: 20,) ), ), ], ), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Expanded( child: FlutterGauge( index: 50,width:280,counterStyle : TextStyle (color: Colors.black,fontSize: 22,), secondsMarker: SecondsMarker.secondsAndMinute, number: Number.all, numberInAndOut: NumberInAndOut.outside, ), ), ], ), ); }}
Output:
Flutter Gauge demo
Following is the explanation of the types of flutter gauge implemented in the above dart code.
Dart
FlutterGauge( handSize: 25,index: 40.0, end: 100,number: Number.endAndCenterAndStart, circleColor: Color(0xFF47505F), secondsMarker: SecondsMarker.secondsAndMinute, counterStyle: TextStyle( color: Colors.black,fontSize: 20, )),
Output:
Flutter Gauge Type 1
In this above flutter gauge, we have set the index at 40. We have also set the handSize at 25 as well as the number as endAndCenterAndStart starting with 0 and ending with 100. The secondsMarker used in this flutter gauge is the second and minute functions. We have also set the circle color but the default color is blue.
Dart
FlutterGauge( secondsMarker: SecondsMarker.none, hand: Hand.short, number: Number.none, index: 66.0, circleColor: Color(0xFF9DC1DC), counterStyle: TextStyle( color: Colors.black, fontSize:25), counterAlign: CounterAlign.center, isDecimal: false )),
Output:
Flutter Gauge Type 2
In this above flutter gauge, we have set the index at 66. The hand is set as short. The number and the second’s marker is set as none. We have also set the circle color but the default color is blue. We have set the decimal value as false and the counter alignment in the center.
Dart
FlutterGauge( handSize: 25,index: 70.0,end: 100, number: Number.endAndCenterAndStart, secondsMarker: SecondsMarker.secondsAndMinute, hand: Hand.short, circleColor: Color(0xFF59EA50), counterStyle: TextStyle(color: Colors.black, fontSize: 20, )),
Output:
Flutter Gauge Type 3
In this above flutter gauge, we have set the index at 70. We have also set the handSize at 25 as well as the number as endAndCenterAndStart starting with 0 and ending with 100. The secondsMarker used in this flutter gauge is the second and minute function and the hand is set as short. We have also set the circle color but the default color is blue.
Dart
FlutterGauge( handSize: 25, index: 100.0, end: 500, number: Number.endAndStart, secondsMarker: SecondsMarker.minutes, isCircle: false, counterStyle: textStyle( color: Colors.black, fontSize: 20, ) )
Output:
Flutter Gauge Type 4
In this above flutter gauge, we have set the index at 100. We have also set the handSize at 25 as well as the number as endandStart starting with 0 and ending with 500. The secondsMarker used in this flutter gauge is the minute function and the hand is set as short. We have also set the circle as false.
Dart
FlutterGauge( index: 50,width:280, counterStyle : TextStyle(color: Colors.black, fontSize: 22,), secondsMarker: SecondsMarker.secondsAndMinute, number: Number.all, numberInAndOut: NumberInAndOut.outside,),
Output:
Flutter Gauge Type 5
In this above flutter gauge, we have set the index at 50. We have also set the width at 280 and the number as all. The secondsMarker used in this flutter gauge is a minute function and the number is shown InAndOut outside. We have also set the circle color but the default color is blue.
android
Flutter
Flutter UI-components
Android
Dart
Flutter
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Resource Raw Folder in Android Studio
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
Flexbox-Layout in Android
How to Post Data to API using Retrofit in Android?
Flutter - DropDownButton Widget
Listview.builder in Flutter
Flutter - Asset Image
Splash Screen in Flutter
Flutter - Custom Bottom Navigation Bar | [
{
"code": null,
"e": 26517,
"s": 26489,
"text": "\n15 Feb, 2021"
},
{
"code": null,
"e": 26787,
"s": 26517,
"text": "Flutter gauge is an information perception widget written in dart language to make a modern, interactive, and animated gauge check and is utilized to make excellent portable application user interfaces utilizing Flutter. There is an alternate style of gauge in flutter."
},
{
"code": null,
"e": 26881,
"s": 26787,
"text": "Following are the steps to follow in order to implement the Flutter Gauge in the Flutter app:"
},
{
"code": null,
"e": 26942,
"s": 26881,
"text": "Step 1: Add the following dependencies to pubspec.yaml file."
},
{
"code": null,
"e": 26980,
"s": 26942,
"text": "dependencies:\nflutter_gauge: ^1.0.8\n\n"
},
{
"code": null,
"e": 27018,
"s": 26980,
"text": "Step 2: Import the following packages"
},
{
"code": null,
"e": 27071,
"s": 27018,
"text": "import 'package:flutter_gauge/flutter_gauge.dart';\n\n"
},
{
"code": null,
"e": 27135,
"s": 27071,
"text": "Step 3: Run flutter packages in the root directory of your app."
},
{
"code": null,
"e": 27220,
"s": 27135,
"text": "Step 4: Next, enable AndriodX by adding the following to your grade.properties file:"
},
{
"code": null,
"e": 27326,
"s": 27220,
"text": "org.gradle.jvmargs=-Xmx1536M\nandroid.enableR8=true\nandroid.useAndroidX=true\nandroid.enableJetifier=true\n\n"
},
{
"code": null,
"e": 27410,
"s": 27326,
"text": "Step 5: Now, the following code needs to be implemented in the respective dart file"
},
{
"code": null,
"e": 27415,
"s": 27410,
"text": "Dart"
},
{
"code": "import 'package:flutter/material.dart';import 'package:flutter_gauge/flutter_gauge.dart'; class FlutterGaugePage extends StatefulWidget { @override _FlutterGaugePageState createState() => _FlutterGaugePageState();} class _FlutterGaugePageState extends State<FlutterGaugePage> { @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.white, appBar: AppBar( title: Text(\"GeeksforGeeks\"), backgroundColor: Color(0xFF4CAF50), automaticallyImplyLeading: false, centerTitle: true, ), body: SingleChildScrollView( child: Column( children: <Widget>[ Row( children: <Widget>[ Expanded( child: Center( child: FlutterGauge( handSize: 25,index: 40.0, end: 100,number: Number.endAndCenterAndStart, circleColor: Color(0xFF47505F), secondsMarker: SecondsMarker.secondsAndMinute, counterStyle: TextStyle( color: Colors.black,fontSize: 20,) ), ) ), Expanded( child: FlutterGauge( secondsMarker: SecondsMarker.none, hand: Hand.short, number: Number.none, index: 66.0,circleColor: Color(0xFF9DC1DC), counterStyle: TextStyle(color: Colors.black, fontSize: 25 ), counterAlign: CounterAlign.center, isDecimal: false )), ], ), Row( children: <Widget>[ Expanded( child: FlutterGauge( handSize: 25,index: 70.0,end: 100, number: Number.endAndCenterAndStart, secondsMarker: SecondsMarker.secondsAndMinute ,hand: Hand.short, circleColor: Color(0xFF59EA50), counterStyle: TextStyle(color: Colors.black,fontSize: 20,) ), ), Expanded( child: FlutterGauge( handSize: 25,index: 100.0,end: 500, number: Number.endAndStart, secondsMarker: SecondsMarker.minutes, isCircle: false, counterStyle: TextStyle(color: Colors.black,fontSize: 20,) ), ), ], ), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Expanded( child: FlutterGauge( index: 50,width:280,counterStyle : TextStyle (color: Colors.black,fontSize: 22,), secondsMarker: SecondsMarker.secondsAndMinute, number: Number.all, numberInAndOut: NumberInAndOut.outside, ), ), ], ), ); }}",
"e": 30728,
"s": 27415,
"text": null
},
{
"code": null,
"e": 30736,
"s": 30728,
"text": "Output:"
},
{
"code": null,
"e": 30755,
"s": 30736,
"text": "Flutter Gauge demo"
},
{
"code": null,
"e": 30851,
"s": 30755,
"text": "Following is the explanation of the types of flutter gauge implemented in the above dart code. "
},
{
"code": null,
"e": 30856,
"s": 30851,
"text": "Dart"
},
{
"code": "FlutterGauge( handSize: 25,index: 40.0, end: 100,number: Number.endAndCenterAndStart, circleColor: Color(0xFF47505F), secondsMarker: SecondsMarker.secondsAndMinute, counterStyle: TextStyle( color: Colors.black,fontSize: 20, )),",
"e": 31109,
"s": 30856,
"text": null
},
{
"code": null,
"e": 31117,
"s": 31109,
"text": "Output:"
},
{
"code": null,
"e": 31138,
"s": 31117,
"text": "Flutter Gauge Type 1"
},
{
"code": null,
"e": 31461,
"s": 31138,
"text": "In this above flutter gauge, we have set the index at 40. We have also set the handSize at 25 as well as the number as endAndCenterAndStart starting with 0 and ending with 100. The secondsMarker used in this flutter gauge is the second and minute functions. We have also set the circle color but the default color is blue."
},
{
"code": null,
"e": 31466,
"s": 31461,
"text": "Dart"
},
{
"code": "FlutterGauge( secondsMarker: SecondsMarker.none, hand: Hand.short, number: Number.none, index: 66.0, circleColor: Color(0xFF9DC1DC), counterStyle: TextStyle( color: Colors.black, fontSize:25), counterAlign: CounterAlign.center, isDecimal: false )),",
"e": 31726,
"s": 31466,
"text": null
},
{
"code": null,
"e": 31734,
"s": 31726,
"text": "Output:"
},
{
"code": null,
"e": 31755,
"s": 31734,
"text": "Flutter Gauge Type 2"
},
{
"code": null,
"e": 32035,
"s": 31755,
"text": "In this above flutter gauge, we have set the index at 66. The hand is set as short. The number and the second’s marker is set as none. We have also set the circle color but the default color is blue. We have set the decimal value as false and the counter alignment in the center."
},
{
"code": null,
"e": 32040,
"s": 32035,
"text": "Dart"
},
{
"code": "FlutterGauge( handSize: 25,index: 70.0,end: 100, number: Number.endAndCenterAndStart, secondsMarker: SecondsMarker.secondsAndMinute, hand: Hand.short, circleColor: Color(0xFF59EA50), counterStyle: TextStyle(color: Colors.black, fontSize: 20, )),",
"e": 32308,
"s": 32040,
"text": null
},
{
"code": null,
"e": 32316,
"s": 32308,
"text": "Output:"
},
{
"code": null,
"e": 32337,
"s": 32316,
"text": "Flutter Gauge Type 3"
},
{
"code": null,
"e": 32688,
"s": 32337,
"text": "In this above flutter gauge, we have set the index at 70. We have also set the handSize at 25 as well as the number as endAndCenterAndStart starting with 0 and ending with 100. The secondsMarker used in this flutter gauge is the second and minute function and the hand is set as short. We have also set the circle color but the default color is blue."
},
{
"code": null,
"e": 32693,
"s": 32688,
"text": "Dart"
},
{
"code": "FlutterGauge( handSize: 25, index: 100.0, end: 500, number: Number.endAndStart, secondsMarker: SecondsMarker.minutes, isCircle: false, counterStyle: textStyle( color: Colors.black, fontSize: 20, ) )",
"e": 32904,
"s": 32693,
"text": null
},
{
"code": null,
"e": 32912,
"s": 32904,
"text": "Output:"
},
{
"code": null,
"e": 32933,
"s": 32912,
"text": "Flutter Gauge Type 4"
},
{
"code": null,
"e": 33238,
"s": 32933,
"text": "In this above flutter gauge, we have set the index at 100. We have also set the handSize at 25 as well as the number as endandStart starting with 0 and ending with 500. The secondsMarker used in this flutter gauge is the minute function and the hand is set as short. We have also set the circle as false."
},
{
"code": null,
"e": 33243,
"s": 33238,
"text": "Dart"
},
{
"code": "FlutterGauge( index: 50,width:280, counterStyle : TextStyle(color: Colors.black, fontSize: 22,), secondsMarker: SecondsMarker.secondsAndMinute, number: Number.all, numberInAndOut: NumberInAndOut.outside,),",
"e": 33456,
"s": 33243,
"text": null
},
{
"code": null,
"e": 33464,
"s": 33456,
"text": "Output:"
},
{
"code": null,
"e": 33485,
"s": 33464,
"text": "Flutter Gauge Type 5"
},
{
"code": null,
"e": 33773,
"s": 33485,
"text": "In this above flutter gauge, we have set the index at 50. We have also set the width at 280 and the number as all. The secondsMarker used in this flutter gauge is a minute function and the number is shown InAndOut outside. We have also set the circle color but the default color is blue."
},
{
"code": null,
"e": 33781,
"s": 33773,
"text": "android"
},
{
"code": null,
"e": 33789,
"s": 33781,
"text": "Flutter"
},
{
"code": null,
"e": 33811,
"s": 33789,
"text": "Flutter UI-components"
},
{
"code": null,
"e": 33819,
"s": 33811,
"text": "Android"
},
{
"code": null,
"e": 33824,
"s": 33819,
"text": "Dart"
},
{
"code": null,
"e": 33832,
"s": 33824,
"text": "Flutter"
},
{
"code": null,
"e": 33840,
"s": 33832,
"text": "Android"
},
{
"code": null,
"e": 33938,
"s": 33840,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33976,
"s": 33938,
"text": "Resource Raw Folder in Android Studio"
},
{
"code": null,
"e": 34015,
"s": 33976,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 34065,
"s": 34015,
"text": "How to Read Data from SQLite Database in Android?"
},
{
"code": null,
"e": 34091,
"s": 34065,
"text": "Flexbox-Layout in Android"
},
{
"code": null,
"e": 34142,
"s": 34091,
"text": "How to Post Data to API using Retrofit in Android?"
},
{
"code": null,
"e": 34174,
"s": 34142,
"text": "Flutter - DropDownButton Widget"
},
{
"code": null,
"e": 34202,
"s": 34174,
"text": "Listview.builder in Flutter"
},
{
"code": null,
"e": 34224,
"s": 34202,
"text": "Flutter - Asset Image"
},
{
"code": null,
"e": 34249,
"s": 34224,
"text": "Splash Screen in Flutter"
}
] |
How to have logarithmic bins in a Python histogram? | We can set the logarithmic bins while plotting histogram using plt.hist(bin="").
Create an array x, where range is 100.
Create an array x, where range is 100.
Plot a histogram using plt.hist() method. We can pass logarithmic bins using logarithmic bins that returns numbers spaced evenly on a log scale.
Plot a histogram using plt.hist() method. We can pass logarithmic bins using logarithmic bins that returns numbers spaced evenly on a log scale.
Get the current axes, creating one if necessary and set the X-axis scale.
Get the current axes, creating one if necessary and set the X-axis scale.
To show the figure, use plt.show() method.
To show the figure, use plt.show() method.
from matplotlib import pyplot as plt
import numpy as np
x = np.array(range(100))
plt.hist(x, bins=np.logspace(start=np.log10(10), stop=np.log10(15), num=10))
plt.gca().set_xscale("log")
plt.show() | [
{
"code": null,
"e": 1143,
"s": 1062,
"text": "We can set the logarithmic bins while plotting histogram using plt.hist(bin=\"\")."
},
{
"code": null,
"e": 1182,
"s": 1143,
"text": "Create an array x, where range is 100."
},
{
"code": null,
"e": 1221,
"s": 1182,
"text": "Create an array x, where range is 100."
},
{
"code": null,
"e": 1366,
"s": 1221,
"text": "Plot a histogram using plt.hist() method. We can pass logarithmic bins using logarithmic bins that returns numbers spaced evenly on a log scale."
},
{
"code": null,
"e": 1511,
"s": 1366,
"text": "Plot a histogram using plt.hist() method. We can pass logarithmic bins using logarithmic bins that returns numbers spaced evenly on a log scale."
},
{
"code": null,
"e": 1585,
"s": 1511,
"text": "Get the current axes, creating one if necessary and set the X-axis scale."
},
{
"code": null,
"e": 1659,
"s": 1585,
"text": "Get the current axes, creating one if necessary and set the X-axis scale."
},
{
"code": null,
"e": 1702,
"s": 1659,
"text": "To show the figure, use plt.show() method."
},
{
"code": null,
"e": 1745,
"s": 1702,
"text": "To show the figure, use plt.show() method."
},
{
"code": null,
"e": 1944,
"s": 1745,
"text": "from matplotlib import pyplot as plt\nimport numpy as np\n\nx = np.array(range(100))\n\nplt.hist(x, bins=np.logspace(start=np.log10(10), stop=np.log10(15), num=10))\nplt.gca().set_xscale(\"log\")\nplt.show()"
}
] |
How to invert the elements of a boolean array in Python? - GeeksforGeeks | 17 Dec, 2020
Given a boolean array the task here is to invert its elements. A boolean array is an array which contains only boolean values like True or False, 1 or 0.
Input : A=[true , true , false]
Output: A= [false , false , true]
Input: A=[0,1,0,1]
Output: A=[1,0,1,0]
Method 1:
You can use simple if else method to invert the array. In the implementation shown below method you just need to check the value of each index in array if the value is true change it to false else change it to true. This is one of the simplest method you can use to invert elements of a boolean array.
Program:
Python3
a1 = ((0, 1, 0, 1))
a = list(a1)
for x in range(len(a)):
if(a[x]):
a[x] = 0
else:
a[x] = 1
print(a)
Output:
[1, 0, 1, 0]
Method 2:
You can also use an inbuilt function of numpy library to invert the whole array.
Syntax:
np.invert(boolean[] a)
Program:
Python
import numpy as np
a = np.array((True, True, False, True, False))
b = np.invert(a)
print(b)
Output:
[False False True False True]
Method 3:
We can also use the Tilde operator (~) also known as bitwise negation operator in computing to invert the given array. It takes the number n as binary number and “flips” all 0 bits to 1 and 1 to 0 to obtain the complement binary number.
So in the boolean array for True or 1 it will result in -2 and for False or 0 it will result as -1. And again by using if..else we can convert the array into or required answer.
Program:
Python3
a1 = ((0, 1, 0, 1))
a = list(a1)
for x in range(len(a)):
# using Tilde operator(~)
a[x] = ~a[x]
print(a)
Output:
[-1, -2, -1, -2]
Picked
Python-datatype
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Selecting rows in pandas DataFrame based on conditions
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Defaultdict in Python
Python OOPs Concepts
Python | os.path.join() method
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 24364,
"s": 24333,
"text": " \n17 Dec, 2020\n"
},
{
"code": null,
"e": 24519,
"s": 24364,
"text": "Given a boolean array the task here is to invert its elements. A boolean array is an array which contains only boolean values like True or False, 1 or 0. "
},
{
"code": null,
"e": 24551,
"s": 24519,
"text": "Input : A=[true , true , false]"
},
{
"code": null,
"e": 24585,
"s": 24551,
"text": "Output: A= [false , false , true]"
},
{
"code": null,
"e": 24605,
"s": 24585,
"text": "Input: A=[0,1,0,1] "
},
{
"code": null,
"e": 24625,
"s": 24605,
"text": "Output: A=[1,0,1,0]"
},
{
"code": null,
"e": 24635,
"s": 24625,
"text": "Method 1:"
},
{
"code": null,
"e": 24937,
"s": 24635,
"text": "You can use simple if else method to invert the array. In the implementation shown below method you just need to check the value of each index in array if the value is true change it to false else change it to true. This is one of the simplest method you can use to invert elements of a boolean array."
},
{
"code": null,
"e": 24946,
"s": 24937,
"text": "Program:"
},
{
"code": null,
"e": 24954,
"s": 24946,
"text": "Python3"
},
{
"code": "\n\n\n\n\n\n\na1 = ((0, 1, 0, 1)) \na = list(a1) \n \nfor x in range(len(a)): \n if(a[x]): \n a[x] = 0\n else: \n a[x] = 1\n \nprint(a) \n\n\n\n\n\n",
"e": 25113,
"s": 24964,
"text": null
},
{
"code": null,
"e": 25121,
"s": 25113,
"text": "Output:"
},
{
"code": null,
"e": 25134,
"s": 25121,
"text": "[1, 0, 1, 0]"
},
{
"code": null,
"e": 25144,
"s": 25134,
"text": "Method 2:"
},
{
"code": null,
"e": 25225,
"s": 25144,
"text": "You can also use an inbuilt function of numpy library to invert the whole array."
},
{
"code": null,
"e": 25233,
"s": 25225,
"text": "Syntax:"
},
{
"code": null,
"e": 25256,
"s": 25233,
"text": "np.invert(boolean[] a)"
},
{
"code": null,
"e": 25265,
"s": 25256,
"text": "Program:"
},
{
"code": null,
"e": 25272,
"s": 25265,
"text": "Python"
},
{
"code": "\n\n\n\n\n\n\nimport numpy as np \n \n \na = np.array((True, True, False, True, False)) \nb = np.invert(a) \nprint(b) \n\n\n\n\n\n",
"e": 25397,
"s": 25282,
"text": null
},
{
"code": null,
"e": 25405,
"s": 25397,
"text": "Output:"
},
{
"code": null,
"e": 25437,
"s": 25405,
"text": "[False False True False True]"
},
{
"code": null,
"e": 25447,
"s": 25437,
"text": "Method 3:"
},
{
"code": null,
"e": 25686,
"s": 25447,
"text": "We can also use the Tilde operator (~) also known as bitwise negation operator in computing to invert the given array. It takes the number n as binary number and “flips” all 0 bits to 1 and 1 to 0 to obtain the complement binary number. "
},
{
"code": null,
"e": 25865,
"s": 25686,
"text": "So in the boolean array for True or 1 it will result in -2 and for False or 0 it will result as -1. And again by using if..else we can convert the array into or required answer."
},
{
"code": null,
"e": 25874,
"s": 25865,
"text": "Program:"
},
{
"code": null,
"e": 25882,
"s": 25874,
"text": "Python3"
},
{
"code": "\n\n\n\n\n\n\na1 = ((0, 1, 0, 1)) \na = list(a1) \n \nfor x in range(len(a)): \n # using Tilde operator(~) \n a[x] = ~a[x] \n \nprint(a) \n\n\n\n\n\n",
"e": 26030,
"s": 25892,
"text": null
},
{
"code": null,
"e": 26038,
"s": 26030,
"text": "Output:"
},
{
"code": null,
"e": 26055,
"s": 26038,
"text": "[-1, -2, -1, -2]"
},
{
"code": null,
"e": 26064,
"s": 26055,
"text": "\nPicked\n"
},
{
"code": null,
"e": 26082,
"s": 26064,
"text": "\nPython-datatype\n"
},
{
"code": null,
"e": 26091,
"s": 26082,
"text": "\nPython\n"
},
{
"code": null,
"e": 26296,
"s": 26091,
"text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n "
},
{
"code": null,
"e": 26328,
"s": 26296,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26383,
"s": 26328,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 26439,
"s": 26383,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26481,
"s": 26439,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26523,
"s": 26481,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26562,
"s": 26523,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 26584,
"s": 26562,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26605,
"s": 26584,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 26636,
"s": 26605,
"text": "Python | os.path.join() method"
}
] |
Callbacks in C - GeeksforGeeks | 05 Mar, 2019
A callback is any executable code that is passed as an argument to other code, which is expected to call back (execute) the argument at a given time [Source : Wiki]. In simple language, If a reference of a function is passed to another function as an argument to call it, then it will be called as a Callback function.
In C, a callback function is a function that is called through a function pointer.
Below is a simple example in C to illustrate the above definition to make it more clear:
// A simple C program to demonstrate callback#include<stdio.h> void A(){ printf("I am function A\n");} // callback functionvoid B(void (*ptr)()){ (*ptr) (); // callback to A} int main(){ void (*ptr)() = &A; // calling function B and passing // address of the function A as argument B(ptr); return 0;}
I am function A
In C++ STL, functors are also used for this purpose.
This article is contributed by Ranju Kumari. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Subhajit Mandal
CPP-Functions
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Multidimensional Arrays in C / C++
Left Shift and Right Shift Operators in C/C++
Core Dump (Segmentation fault) in C/C++
Function Pointer in C
rand() and srand() in C/C++
Substring in C++
fork() in C
Converting Strings to Numbers in C/C++
std::string class in C++
Enumeration (or enum) in C | [
{
"code": null,
"e": 25837,
"s": 25809,
"text": "\n05 Mar, 2019"
},
{
"code": null,
"e": 26156,
"s": 25837,
"text": "A callback is any executable code that is passed as an argument to other code, which is expected to call back (execute) the argument at a given time [Source : Wiki]. In simple language, If a reference of a function is passed to another function as an argument to call it, then it will be called as a Callback function."
},
{
"code": null,
"e": 26239,
"s": 26156,
"text": "In C, a callback function is a function that is called through a function pointer."
},
{
"code": null,
"e": 26328,
"s": 26239,
"text": "Below is a simple example in C to illustrate the above definition to make it more clear:"
},
{
"code": "// A simple C program to demonstrate callback#include<stdio.h> void A(){ printf(\"I am function A\\n\");} // callback functionvoid B(void (*ptr)()){ (*ptr) (); // callback to A} int main(){ void (*ptr)() = &A; // calling function B and passing // address of the function A as argument B(ptr); return 0;}",
"e": 26660,
"s": 26328,
"text": null
},
{
"code": null,
"e": 26677,
"s": 26660,
"text": "I am function A\n"
},
{
"code": null,
"e": 26730,
"s": 26677,
"text": "In C++ STL, functors are also used for this purpose."
},
{
"code": null,
"e": 27030,
"s": 26730,
"text": "This article is contributed by Ranju Kumari. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 27155,
"s": 27030,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 27171,
"s": 27155,
"text": "Subhajit Mandal"
},
{
"code": null,
"e": 27185,
"s": 27171,
"text": "CPP-Functions"
},
{
"code": null,
"e": 27196,
"s": 27185,
"text": "C Language"
},
{
"code": null,
"e": 27294,
"s": 27196,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27329,
"s": 27294,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 27375,
"s": 27329,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 27415,
"s": 27375,
"text": "Core Dump (Segmentation fault) in C/C++"
},
{
"code": null,
"e": 27437,
"s": 27415,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 27465,
"s": 27437,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 27482,
"s": 27465,
"text": "Substring in C++"
},
{
"code": null,
"e": 27494,
"s": 27482,
"text": "fork() in C"
},
{
"code": null,
"e": 27533,
"s": 27494,
"text": "Converting Strings to Numbers in C/C++"
},
{
"code": null,
"e": 27558,
"s": 27533,
"text": "std::string class in C++"
}
] |
Illustrated: Efficient Neural Architecture Search | by Raimi Karim | Towards Data Science | (TL;DR the only two animations you need to know are here)
Updated:23 Mar 2020: Erratum — Previously it was mentioned that all convolution cells in micro search are different from one another. This is wrong; the convolution cell is repeated multiple times in the final child models. This information is verified by the author. Thank you Martin Ferianc for the correction!
Designing neural networks for various tasks like image classification and natural language understanding often requires significant architecture engineering and expertise. Enter Neural Architecture Search (NAS), a task to automate the manual process of designing neural networks. NAS owes its growing research interest to the increasing prominence of deep learning models of late.
There are many ways to search for or discover neural architectures. Over the past couple of years, the community has seen different search methods proposed including:
Reinforcement learningNeural Architecture Search with Reinforcement Learning (Zoph and Le, 2016)NASNet (Zoph et al., 2017)ENAS (Pham et al., 2018)
Evolutionary algorithmHierarchical Evo (Liu et al., 2017)AmoebaNet (Real et al., 2018)
Sequential model-based optimisation (SMBO)PNAS (Liu et al., 2017)
Bayesian optimisationAuto-Keras (Jin et al., 2018)NASBOT (Kandasamy et al. 2018)
Gradient-based optimisationSNAS (Xie et al., 2018)DARTS (Liu et al., 2018)
In this post, we will look at Efficient Neural Architecture Search (ENAS) which employs reinforcement learning to build convolutional neural networks (CNNs) and recurrent neural networks (RNNs). The authors Hieu Pham, Melody Guan, Barret Zoph, Quoc V. Le, and Jeff Dean proposed a predefined neural network to generate new neural networks guided by a reinforcement learning framework using macro search and micro search (see the paper here). That’s right – a neural network building another neural network.
This article is a tutorial on how the macro and micro search strategies lead to generating neural networks. While the illustrations and animations serve to guide the readers, the sequence of animations do not necessarily reflect the flow of operations (due to vectorisation etc.).
We shall narrow the scope of this tutorial to neural architecture search for CNNs in an image classification task. This article assumes that the reader is familiar with the basics of RNNs, CNNs, and reinforcement learning. Familiarity with deep learning concepts like transfer learning and skip/residual connections will greatly help as they are heavily used in the architecture search. It is not required to have read the paper, but it would speed up your understanding.
0. Overview1. Search strategy1.1. Macro search1.2. Micro search 2. Notes3. Summary4. Implementations5. References
In ENAS, there are 2 types of neural networks involved:
Controller – a predefined RNN, which is a long short-term memory (LSTM) cell
Child model – the desired CNN for image classification
Like most other NAS algorithms, the ENAS involves 3 concepts:
Search space — all the different possible architectures or child models that can possibly be generatedSearch strategy — a method to generate these architectures or child modelsPerformance evaluation — a method to measure the effectiveness of the generated child models
Search space — all the different possible architectures or child models that can possibly be generated
Search strategy — a method to generate these architectures or child models
Performance evaluation — a method to measure the effectiveness of the generated child models
Let’s see how these five ideas form the ENAS story.
The controller controls or directs the building of the child model’s architecture by “generating a set of instructions” (or, more rigorously, making decisions or sampling decisions) using a certain search strategy. These decisions are things like what types of operations (convolutions, pooling etc.) to perform at a particular layer of the child model. Using these decisions, a child model is built. A generated child model is one of the many possible child models that can be built in the search space.
This particular child model is then trained to convergence (~95% training accuracy) using stochastic gradient descent to minimise the expected loss function between the predicted class and ground truth class (for an image classification task). This is done for a specified number of epochs, what I’d like to call child epochs, say 100. Then, a validation accuracy is obtained from this trained model.
Then, we update the controller’s parameters using REINFORCE, a policy-based reinforcement learning algorithm, to maximise the expected reward function which is the validation accuracy. This parameter update hopes to improve the controller in generating better decisions that give higher validation accuracies.
This entire process (from 3 paragraphs before this) is just one epoch — let’s call it controller epoch. We then repeat this for a specified number of controller epochs, say 2000.
Of all the 2000 child models generated, the one with the highest validation accuracy gets the honour to be the neural network for your image classification task. However, this child model must go through just one more round of training (again specified by the number of child epochs), before it can be used for deployment.
A pseudo algorithm for the entire training is written below:
CONTROLLER_EPOCHS = 2000CHILD_EPOCHS = 100Build controller networkfor i in CONTROLLER_EPOCHS: 1. Generate a child model 2. Train this child model for CHILD_EPOCHS 3. Obtain val_acc 4. Update controller parametersGet child model with the highest val_accTrain this child model for CHILD_EPOCHS
This entire problem is essentially a reinforcement learning framework with the archetypal elements:
Agent — Controller
Action — The decisions taken to build the child network
Reward — Validation accuracy from the child network
The aim of this reinforcement learning task is to maximise the reward (validation accuracy) from the actions taken (decisions taken to build child model architecture) by the agent (controller).
[Back to top]
Recall in the previous section that the controller generates the child model’s architecture using a certain search strategy. There are two questions that you should ask in this statement — (1) how does the controller make decisions and (2) what search strategy?
How does the controller make decisions?
This brings us to the model of the controller, which is an LSTM. This LSTM samples decisions via softmax classifiers, in an auto-regressive fashion: the decision in the previous step is fed as input embedding into the next step.
What are the search strategies?
The authors of ENAS proposed 2 strategies for searching for or generating an architecture.
Macro searchMicro search
Macro search
Micro search
Macro search is an approach where the controller designs the entire network. Examples of publications that use this include NAS by Zoph and Le, FractalNet and SMASH. On the other hand, micro search is an approach where the controller designs modules or building blocks, which are combined to build the final network. Some papers that implement this approach are Hierarchical NAS, Progressive NAS and NASNet.
In the following 2 sub-sections we will see how ENAS implements these 2 strategies.
[Macro search][Micro search]
In macro search, the controller makes 2 decisions for every layer in the child model:
the operation to perform on the previous layer (see Notes for the list of operations)
the previous layer to connect to for skip connections
In this macro search example, we will see how the controller generates a 4-layer child model. Each layer in this child model is colour-coded with red, green, blue and purple respectively.
Convolutional layer 1 (red)
We’ll start with running the first time step of the controller. The output of this time step is softmaxed to get a vector, which translates to a conv3×3 operation.
What this means for the child model is that the we perform a convolution with a 3×3 filter on the input image.
I know I mentioned that the controller needs to make 2 decisions but there’s only 1 here. Since this is the first layer, we can only sample one decision which is the operation to perform, because there’s nothing else to connect to except for the input image itself.
Convolutional layer 2 (green)
To build the subsequent convolutional layers, the controller makes 2 decisions (no more lies): (i) operation and (ii) layer(s) to connect to. Here, we see that it generated 1 and sep5×5.
What this means for the child model is that we first perform a sep5×5 operation on the output of the previous layer. Then, this output is concatenated along the depth together with the output of Layer 1, i.e. the output from the red layer.
Convolutional layer 3 (blue)
We repeat the previous step again to generate the 3rd convolutional layer. Again, we see here that the controller generates 2 things: (i) operation and (ii) layer(s) to connect to. Below, the controller generated 1 and 2, and the operation max3×3.
So, the child model performs the operation max3×3 on the output of the previous layer (Layer 2, green). Then, the result of this operation is concatenated along the depth dimension with Layers 1 and 2.
Convolutional layer 4 (purple)
We repeat the previous step again to generate the 4th convolutional layer. This time the controller generated 1 and 3, and the operation conv5×5.
The child model performs the operation conv5×5 on the output of the previous layer (Layer 3, blue). Then, the result of this operation is concatenated along the depth dimension with Layers 1 and 3.
End
And there you have it — a child model generated using the macro search! Now on to micro search.
[Back to top]
Micro search designs only one building block whose architecture is repeated throughout the final architecture. ENAS calls this building block a convolutional cell and reduction cell. Both are similar — the only thing different about reduction cells is that the operations are applied with a stride of 2, thus reducing the spatial dimensions.
The idea of micro search is to build one single architecture for a convolutional cell and repeat this same architecture through out the final model. In the example below, the final model consists of a convolutional cell whose architecture is repeated N times across 3 blocks. As mentioned in the previous paragraph, the reduction cell is similar to the architecture of the convolutional cell.
Let’s come back to this in a bit.
Building units for networks derived for micro search
There’s sort of a hierarchy in the ‘building units’ of child networks derived from micro search. From biggest to smallest:
block
convolutional cell / reduction cell
node
A child model consists of several blocks. Each block consists of N convolutional cells and 1 reduction cell. Each convolutional/reduction cell comprises B nodes. And each node consists of standard convolutional operations (we’ll see this later). (N and B are hyperparameters that can be tuned by you, the architect.)
Below is a child model with 3 blocks. Each block consists of N=3 convolutional cells and 1 reduction cell. The operations within each cell are not shown here.
So how to generate this child model from micro search, you may ask? Continue reading!
Generate a child model from micro search
For this micro search tutorial, let’s build a child model that has 1 block, for simplicity’s sake. This block comprises N=3 convolutional cells and 1 reduction cell, and each cell comprises B=4 nodes.
Recall that what this means is simply to design one single architecture for a convolutional cell, then repeat it for 3 more times (2 more convolutional cells and 1 reduction cell). This means our generated child model should look like this:
Let’s now build a convolutional cell!
To explain how to build a convolutional cell, let’s assume we already have 2 convolutional cells. Notice that the last operations from each of these 2 cells are add operations.
Recall that a convolutional cell consists of 4 nodes. So where are these nodes?
Node 1 and Node 2
The two previous cells (red and blue) will be considered as Node 1 and Node 2 respectively. The other 2 nodes fall in this very convolutional cell that we are building now.
From this section onwards, you can safely disregard the ‘Convolutional cell’ labels you see on the image above and concentrate on the ‘Nodes’ labels:
Node 1 — red
Node 2 — blue
Node 3 — green
Node 4 — purple
ErratumI̶f̶ ̶y̶o̶u̶’̶r̶e̶ ̶w̶o̶n̶d̶e̶r̶i̶n̶g̶ ̶i̶f̶ ̶t̶h̶e̶s̶e̶ ̶n̶o̶d̶e̶s̶ ̶w̶i̶l̶l̶ ̶c̶h̶a̶n̶g̶e̶ ̶f̶o̶r̶ ̶e̶v̶e̶r̶y̶ ̶c̶o̶n̶v̶o̶l̶u̶t̶i̶o̶n̶a̶l̶ ̶c̶e̶l̶l̶ ̶w̶e̶’̶r̶e̶ ̶b̶u̶i̶l̶d̶i̶n̶g̶,̶ ̶t̶h̶e̶ ̶a̶n̶s̶w̶e̶r̶ ̶i̶s̶ ̶y̶e̶s̶!̶ ̶E̶v̶e̶r̶y̶ ̶c̶e̶l̶l̶ ̶w̶i̶l̶l̶ ̶’̶a̶s̶s̶i̶g̶n̶’̶ ̶t̶h̶e̶ ̶n̶o̶d̶e̶s̶ ̶i̶n̶ ̶t̶h̶i̶s̶ ̶m̶a̶n̶n̶e̶r̶.̶
Node 3
Node 3 is where the building starts. The controller samples 4 decisions (or rather 2 sets of decisions):
2 nodes to connect to
the respective 2 operations to perform on the nodes to connect to
With 4 decisions to make, the controller runs 4 time steps. Have a look below:
From the above we see that the controller sampled Node2, Node 1, avg5×5, and sep5×5 from each of the four time steps. How does this translate to the architecture of the child model? Let’s see:
From the above, we observe three things:
The output from Node2 (blue) undergoes the avg5×5 operation.The output from Node 1 (red) undergoes a sep5×5 operation.Both the results from these two operations undergo an add operation.
The output from Node2 (blue) undergoes the avg5×5 operation.
The output from Node 1 (red) undergoes a sep5×5 operation.
Both the results from these two operations undergo an add operation.
The output from this node is the tensor that undergoes the add operation. This explains why Nodes 1 and 2 end with add operations.
Node 4
Now for Node 4. We repeat the same steps, but now the controller now has three nodes to choose from (Nodes 1, 2 and 3). Below, the controller generated 3, 1, id and avg3×3.
This translates to building the following:
What just happened?
The output from Node3 (green) undergoes an id operation.The output from Node 1 (red) undergoes an avg3×3 operation.Both the results from these two operations undergo an add operation.
The output from Node3 (green) undergoes an id operation.
The output from Node 1 (red) undergoes an avg3×3 operation.
Both the results from these two operations undergo an add operation.
And that’s it! All convolutional cells in the final child model will share the same architecture. Similarly, all reduction cells (whose architecture differ from that of convolutional cell by having stride 2 operations) in the final child model will share the same architecture.
[Back to top]
Because this post mainly shows the macro and micro search strategies, I’ve left out many small details (especially on the concept of transfer learning). Let me briefly cover them:
What’s so ‘efficient’ in ENAS? Answer: transfer learning. If a computation between two nodes has been done (trained) before, the weights from the convolutional filters and 1×1 convolutions (to maintain number of channel outputs; not mentioned in the previous sections) will be reused. This is what makes ENAS faster than its predecessors!
It is possible that the controller samples a decision where no skip connection is needed.
There are 6 operations available for the controller: convolutions with filter sizes 3×3 and 5×5, depthwise-separable convolutions with filter sizes 3×3 and 5×5, max pooling and average pooling of kernel size 3×3.
Do read up on the concatenate operation at the end of each cell which ties up ‘loose ends’ of any nodes.
Do read up briefly on the policy gradient algorithm (REINFORCE) reinforcement learning.
[Back to top]
Macro search (for an entire network)
The final child model is as shown below.
Micro search (for a convolutional cell)
Note that only part of the final child model is shown here.
[Back to top]
TensorFlow implementation by the authors
Keras implementation
PyTorch implementation
[Back to top]
Efficient Neural Architecture Search via Parameter Sharing
Neural Architecture Search with Reinforcement Learning
Learning Transferable Architectures for Scalable Image Recognition
That’s it! Remember to read the ENAS paper Efficient Neural Architecture Search via Parameter Sharing. If you have any questions, please highlight and leave a comment.
General
Counting No. of Parameters in Deep Learning Models
Related to NLP
Animated RNN, LSTM and GRU
Attn: Illustrated Attention
Illustrated: Self-Attention
Line-by-Line Word2Vec Implementation
Related to Computer Vision
Breaking down Mean Average Precision (mAP)
Optimisation
Step-by-Step Tutorial on Linear Regression with Stochastic Gradient Descent
10 Gradient Descent Optimisation Algorithms + Cheat Sheet
Follow me on Twitter @remykarem or LinkedIn. You may also reach out to me via [email protected]. Feel free to visit my website at remykarem.github.io. | [
{
"code": null,
"e": 230,
"s": 172,
"text": "(TL;DR the only two animations you need to know are here)"
},
{
"code": null,
"e": 543,
"s": 230,
"text": "Updated:23 Mar 2020: Erratum — Previously it was mentioned that all convolution cells in micro search are different from one another. This is wrong; the convolution cell is repeated multiple times in the final child models. This information is verified by the author. Thank you Martin Ferianc for the correction!"
},
{
"code": null,
"e": 924,
"s": 543,
"text": "Designing neural networks for various tasks like image classification and natural language understanding often requires significant architecture engineering and expertise. Enter Neural Architecture Search (NAS), a task to automate the manual process of designing neural networks. NAS owes its growing research interest to the increasing prominence of deep learning models of late."
},
{
"code": null,
"e": 1091,
"s": 924,
"text": "There are many ways to search for or discover neural architectures. Over the past couple of years, the community has seen different search methods proposed including:"
},
{
"code": null,
"e": 1238,
"s": 1091,
"text": "Reinforcement learningNeural Architecture Search with Reinforcement Learning (Zoph and Le, 2016)NASNet (Zoph et al., 2017)ENAS (Pham et al., 2018)"
},
{
"code": null,
"e": 1325,
"s": 1238,
"text": "Evolutionary algorithmHierarchical Evo (Liu et al., 2017)AmoebaNet (Real et al., 2018)"
},
{
"code": null,
"e": 1391,
"s": 1325,
"text": "Sequential model-based optimisation (SMBO)PNAS (Liu et al., 2017)"
},
{
"code": null,
"e": 1472,
"s": 1391,
"text": "Bayesian optimisationAuto-Keras (Jin et al., 2018)NASBOT (Kandasamy et al. 2018)"
},
{
"code": null,
"e": 1547,
"s": 1472,
"text": "Gradient-based optimisationSNAS (Xie et al., 2018)DARTS (Liu et al., 2018)"
},
{
"code": null,
"e": 2054,
"s": 1547,
"text": "In this post, we will look at Efficient Neural Architecture Search (ENAS) which employs reinforcement learning to build convolutional neural networks (CNNs) and recurrent neural networks (RNNs). The authors Hieu Pham, Melody Guan, Barret Zoph, Quoc V. Le, and Jeff Dean proposed a predefined neural network to generate new neural networks guided by a reinforcement learning framework using macro search and micro search (see the paper here). That’s right – a neural network building another neural network."
},
{
"code": null,
"e": 2335,
"s": 2054,
"text": "This article is a tutorial on how the macro and micro search strategies lead to generating neural networks. While the illustrations and animations serve to guide the readers, the sequence of animations do not necessarily reflect the flow of operations (due to vectorisation etc.)."
},
{
"code": null,
"e": 2807,
"s": 2335,
"text": "We shall narrow the scope of this tutorial to neural architecture search for CNNs in an image classification task. This article assumes that the reader is familiar with the basics of RNNs, CNNs, and reinforcement learning. Familiarity with deep learning concepts like transfer learning and skip/residual connections will greatly help as they are heavily used in the architecture search. It is not required to have read the paper, but it would speed up your understanding."
},
{
"code": null,
"e": 2921,
"s": 2807,
"text": "0. Overview1. Search strategy1.1. Macro search1.2. Micro search 2. Notes3. Summary4. Implementations5. References"
},
{
"code": null,
"e": 2977,
"s": 2921,
"text": "In ENAS, there are 2 types of neural networks involved:"
},
{
"code": null,
"e": 3054,
"s": 2977,
"text": "Controller – a predefined RNN, which is a long short-term memory (LSTM) cell"
},
{
"code": null,
"e": 3109,
"s": 3054,
"text": "Child model – the desired CNN for image classification"
},
{
"code": null,
"e": 3171,
"s": 3109,
"text": "Like most other NAS algorithms, the ENAS involves 3 concepts:"
},
{
"code": null,
"e": 3440,
"s": 3171,
"text": "Search space — all the different possible architectures or child models that can possibly be generatedSearch strategy — a method to generate these architectures or child modelsPerformance evaluation — a method to measure the effectiveness of the generated child models"
},
{
"code": null,
"e": 3543,
"s": 3440,
"text": "Search space — all the different possible architectures or child models that can possibly be generated"
},
{
"code": null,
"e": 3618,
"s": 3543,
"text": "Search strategy — a method to generate these architectures or child models"
},
{
"code": null,
"e": 3711,
"s": 3618,
"text": "Performance evaluation — a method to measure the effectiveness of the generated child models"
},
{
"code": null,
"e": 3763,
"s": 3711,
"text": "Let’s see how these five ideas form the ENAS story."
},
{
"code": null,
"e": 4268,
"s": 3763,
"text": "The controller controls or directs the building of the child model’s architecture by “generating a set of instructions” (or, more rigorously, making decisions or sampling decisions) using a certain search strategy. These decisions are things like what types of operations (convolutions, pooling etc.) to perform at a particular layer of the child model. Using these decisions, a child model is built. A generated child model is one of the many possible child models that can be built in the search space."
},
{
"code": null,
"e": 4669,
"s": 4268,
"text": "This particular child model is then trained to convergence (~95% training accuracy) using stochastic gradient descent to minimise the expected loss function between the predicted class and ground truth class (for an image classification task). This is done for a specified number of epochs, what I’d like to call child epochs, say 100. Then, a validation accuracy is obtained from this trained model."
},
{
"code": null,
"e": 4979,
"s": 4669,
"text": "Then, we update the controller’s parameters using REINFORCE, a policy-based reinforcement learning algorithm, to maximise the expected reward function which is the validation accuracy. This parameter update hopes to improve the controller in generating better decisions that give higher validation accuracies."
},
{
"code": null,
"e": 5158,
"s": 4979,
"text": "This entire process (from 3 paragraphs before this) is just one epoch — let’s call it controller epoch. We then repeat this for a specified number of controller epochs, say 2000."
},
{
"code": null,
"e": 5481,
"s": 5158,
"text": "Of all the 2000 child models generated, the one with the highest validation accuracy gets the honour to be the neural network for your image classification task. However, this child model must go through just one more round of training (again specified by the number of child epochs), before it can be used for deployment."
},
{
"code": null,
"e": 5542,
"s": 5481,
"text": "A pseudo algorithm for the entire training is written below:"
},
{
"code": null,
"e": 5850,
"s": 5542,
"text": "CONTROLLER_EPOCHS = 2000CHILD_EPOCHS = 100Build controller networkfor i in CONTROLLER_EPOCHS: 1. Generate a child model 2. Train this child model for CHILD_EPOCHS 3. Obtain val_acc 4. Update controller parametersGet child model with the highest val_accTrain this child model for CHILD_EPOCHS"
},
{
"code": null,
"e": 5950,
"s": 5850,
"text": "This entire problem is essentially a reinforcement learning framework with the archetypal elements:"
},
{
"code": null,
"e": 5969,
"s": 5950,
"text": "Agent — Controller"
},
{
"code": null,
"e": 6025,
"s": 5969,
"text": "Action — The decisions taken to build the child network"
},
{
"code": null,
"e": 6077,
"s": 6025,
"text": "Reward — Validation accuracy from the child network"
},
{
"code": null,
"e": 6271,
"s": 6077,
"text": "The aim of this reinforcement learning task is to maximise the reward (validation accuracy) from the actions taken (decisions taken to build child model architecture) by the agent (controller)."
},
{
"code": null,
"e": 6285,
"s": 6271,
"text": "[Back to top]"
},
{
"code": null,
"e": 6547,
"s": 6285,
"text": "Recall in the previous section that the controller generates the child model’s architecture using a certain search strategy. There are two questions that you should ask in this statement — (1) how does the controller make decisions and (2) what search strategy?"
},
{
"code": null,
"e": 6587,
"s": 6547,
"text": "How does the controller make decisions?"
},
{
"code": null,
"e": 6816,
"s": 6587,
"text": "This brings us to the model of the controller, which is an LSTM. This LSTM samples decisions via softmax classifiers, in an auto-regressive fashion: the decision in the previous step is fed as input embedding into the next step."
},
{
"code": null,
"e": 6848,
"s": 6816,
"text": "What are the search strategies?"
},
{
"code": null,
"e": 6939,
"s": 6848,
"text": "The authors of ENAS proposed 2 strategies for searching for or generating an architecture."
},
{
"code": null,
"e": 6964,
"s": 6939,
"text": "Macro searchMicro search"
},
{
"code": null,
"e": 6977,
"s": 6964,
"text": "Macro search"
},
{
"code": null,
"e": 6990,
"s": 6977,
"text": "Micro search"
},
{
"code": null,
"e": 7398,
"s": 6990,
"text": "Macro search is an approach where the controller designs the entire network. Examples of publications that use this include NAS by Zoph and Le, FractalNet and SMASH. On the other hand, micro search is an approach where the controller designs modules or building blocks, which are combined to build the final network. Some papers that implement this approach are Hierarchical NAS, Progressive NAS and NASNet."
},
{
"code": null,
"e": 7482,
"s": 7398,
"text": "In the following 2 sub-sections we will see how ENAS implements these 2 strategies."
},
{
"code": null,
"e": 7511,
"s": 7482,
"text": "[Macro search][Micro search]"
},
{
"code": null,
"e": 7597,
"s": 7511,
"text": "In macro search, the controller makes 2 decisions for every layer in the child model:"
},
{
"code": null,
"e": 7683,
"s": 7597,
"text": "the operation to perform on the previous layer (see Notes for the list of operations)"
},
{
"code": null,
"e": 7737,
"s": 7683,
"text": "the previous layer to connect to for skip connections"
},
{
"code": null,
"e": 7925,
"s": 7737,
"text": "In this macro search example, we will see how the controller generates a 4-layer child model. Each layer in this child model is colour-coded with red, green, blue and purple respectively."
},
{
"code": null,
"e": 7953,
"s": 7925,
"text": "Convolutional layer 1 (red)"
},
{
"code": null,
"e": 8117,
"s": 7953,
"text": "We’ll start with running the first time step of the controller. The output of this time step is softmaxed to get a vector, which translates to a conv3×3 operation."
},
{
"code": null,
"e": 8228,
"s": 8117,
"text": "What this means for the child model is that the we perform a convolution with a 3×3 filter on the input image."
},
{
"code": null,
"e": 8494,
"s": 8228,
"text": "I know I mentioned that the controller needs to make 2 decisions but there’s only 1 here. Since this is the first layer, we can only sample one decision which is the operation to perform, because there’s nothing else to connect to except for the input image itself."
},
{
"code": null,
"e": 8524,
"s": 8494,
"text": "Convolutional layer 2 (green)"
},
{
"code": null,
"e": 8711,
"s": 8524,
"text": "To build the subsequent convolutional layers, the controller makes 2 decisions (no more lies): (i) operation and (ii) layer(s) to connect to. Here, we see that it generated 1 and sep5×5."
},
{
"code": null,
"e": 8951,
"s": 8711,
"text": "What this means for the child model is that we first perform a sep5×5 operation on the output of the previous layer. Then, this output is concatenated along the depth together with the output of Layer 1, i.e. the output from the red layer."
},
{
"code": null,
"e": 8980,
"s": 8951,
"text": "Convolutional layer 3 (blue)"
},
{
"code": null,
"e": 9228,
"s": 8980,
"text": "We repeat the previous step again to generate the 3rd convolutional layer. Again, we see here that the controller generates 2 things: (i) operation and (ii) layer(s) to connect to. Below, the controller generated 1 and 2, and the operation max3×3."
},
{
"code": null,
"e": 9430,
"s": 9228,
"text": "So, the child model performs the operation max3×3 on the output of the previous layer (Layer 2, green). Then, the result of this operation is concatenated along the depth dimension with Layers 1 and 2."
},
{
"code": null,
"e": 9461,
"s": 9430,
"text": "Convolutional layer 4 (purple)"
},
{
"code": null,
"e": 9607,
"s": 9461,
"text": "We repeat the previous step again to generate the 4th convolutional layer. This time the controller generated 1 and 3, and the operation conv5×5."
},
{
"code": null,
"e": 9805,
"s": 9607,
"text": "The child model performs the operation conv5×5 on the output of the previous layer (Layer 3, blue). Then, the result of this operation is concatenated along the depth dimension with Layers 1 and 3."
},
{
"code": null,
"e": 9809,
"s": 9805,
"text": "End"
},
{
"code": null,
"e": 9905,
"s": 9809,
"text": "And there you have it — a child model generated using the macro search! Now on to micro search."
},
{
"code": null,
"e": 9919,
"s": 9905,
"text": "[Back to top]"
},
{
"code": null,
"e": 10261,
"s": 9919,
"text": "Micro search designs only one building block whose architecture is repeated throughout the final architecture. ENAS calls this building block a convolutional cell and reduction cell. Both are similar — the only thing different about reduction cells is that the operations are applied with a stride of 2, thus reducing the spatial dimensions."
},
{
"code": null,
"e": 10654,
"s": 10261,
"text": "The idea of micro search is to build one single architecture for a convolutional cell and repeat this same architecture through out the final model. In the example below, the final model consists of a convolutional cell whose architecture is repeated N times across 3 blocks. As mentioned in the previous paragraph, the reduction cell is similar to the architecture of the convolutional cell."
},
{
"code": null,
"e": 10688,
"s": 10654,
"text": "Let’s come back to this in a bit."
},
{
"code": null,
"e": 10741,
"s": 10688,
"text": "Building units for networks derived for micro search"
},
{
"code": null,
"e": 10864,
"s": 10741,
"text": "There’s sort of a hierarchy in the ‘building units’ of child networks derived from micro search. From biggest to smallest:"
},
{
"code": null,
"e": 10870,
"s": 10864,
"text": "block"
},
{
"code": null,
"e": 10906,
"s": 10870,
"text": "convolutional cell / reduction cell"
},
{
"code": null,
"e": 10911,
"s": 10906,
"text": "node"
},
{
"code": null,
"e": 11228,
"s": 10911,
"text": "A child model consists of several blocks. Each block consists of N convolutional cells and 1 reduction cell. Each convolutional/reduction cell comprises B nodes. And each node consists of standard convolutional operations (we’ll see this later). (N and B are hyperparameters that can be tuned by you, the architect.)"
},
{
"code": null,
"e": 11387,
"s": 11228,
"text": "Below is a child model with 3 blocks. Each block consists of N=3 convolutional cells and 1 reduction cell. The operations within each cell are not shown here."
},
{
"code": null,
"e": 11473,
"s": 11387,
"text": "So how to generate this child model from micro search, you may ask? Continue reading!"
},
{
"code": null,
"e": 11514,
"s": 11473,
"text": "Generate a child model from micro search"
},
{
"code": null,
"e": 11715,
"s": 11514,
"text": "For this micro search tutorial, let’s build a child model that has 1 block, for simplicity’s sake. This block comprises N=3 convolutional cells and 1 reduction cell, and each cell comprises B=4 nodes."
},
{
"code": null,
"e": 11956,
"s": 11715,
"text": "Recall that what this means is simply to design one single architecture for a convolutional cell, then repeat it for 3 more times (2 more convolutional cells and 1 reduction cell). This means our generated child model should look like this:"
},
{
"code": null,
"e": 11994,
"s": 11956,
"text": "Let’s now build a convolutional cell!"
},
{
"code": null,
"e": 12171,
"s": 11994,
"text": "To explain how to build a convolutional cell, let’s assume we already have 2 convolutional cells. Notice that the last operations from each of these 2 cells are add operations."
},
{
"code": null,
"e": 12251,
"s": 12171,
"text": "Recall that a convolutional cell consists of 4 nodes. So where are these nodes?"
},
{
"code": null,
"e": 12269,
"s": 12251,
"text": "Node 1 and Node 2"
},
{
"code": null,
"e": 12442,
"s": 12269,
"text": "The two previous cells (red and blue) will be considered as Node 1 and Node 2 respectively. The other 2 nodes fall in this very convolutional cell that we are building now."
},
{
"code": null,
"e": 12592,
"s": 12442,
"text": "From this section onwards, you can safely disregard the ‘Convolutional cell’ labels you see on the image above and concentrate on the ‘Nodes’ labels:"
},
{
"code": null,
"e": 12605,
"s": 12592,
"text": "Node 1 — red"
},
{
"code": null,
"e": 12619,
"s": 12605,
"text": "Node 2 — blue"
},
{
"code": null,
"e": 12634,
"s": 12619,
"text": "Node 3 — green"
},
{
"code": null,
"e": 12650,
"s": 12634,
"text": "Node 4 — purple"
},
{
"code": null,
"e": 12980,
"s": 12650,
"text": "ErratumI̶f̶ ̶y̶o̶u̶’̶r̶e̶ ̶w̶o̶n̶d̶e̶r̶i̶n̶g̶ ̶i̶f̶ ̶t̶h̶e̶s̶e̶ ̶n̶o̶d̶e̶s̶ ̶w̶i̶l̶l̶ ̶c̶h̶a̶n̶g̶e̶ ̶f̶o̶r̶ ̶e̶v̶e̶r̶y̶ ̶c̶o̶n̶v̶o̶l̶u̶t̶i̶o̶n̶a̶l̶ ̶c̶e̶l̶l̶ ̶w̶e̶’̶r̶e̶ ̶b̶u̶i̶l̶d̶i̶n̶g̶,̶ ̶t̶h̶e̶ ̶a̶n̶s̶w̶e̶r̶ ̶i̶s̶ ̶y̶e̶s̶!̶ ̶E̶v̶e̶r̶y̶ ̶c̶e̶l̶l̶ ̶w̶i̶l̶l̶ ̶’̶a̶s̶s̶i̶g̶n̶’̶ ̶t̶h̶e̶ ̶n̶o̶d̶e̶s̶ ̶i̶n̶ ̶t̶h̶i̶s̶ ̶m̶a̶n̶n̶e̶r̶.̶"
},
{
"code": null,
"e": 12987,
"s": 12980,
"text": "Node 3"
},
{
"code": null,
"e": 13092,
"s": 12987,
"text": "Node 3 is where the building starts. The controller samples 4 decisions (or rather 2 sets of decisions):"
},
{
"code": null,
"e": 13114,
"s": 13092,
"text": "2 nodes to connect to"
},
{
"code": null,
"e": 13180,
"s": 13114,
"text": "the respective 2 operations to perform on the nodes to connect to"
},
{
"code": null,
"e": 13259,
"s": 13180,
"text": "With 4 decisions to make, the controller runs 4 time steps. Have a look below:"
},
{
"code": null,
"e": 13452,
"s": 13259,
"text": "From the above we see that the controller sampled Node2, Node 1, avg5×5, and sep5×5 from each of the four time steps. How does this translate to the architecture of the child model? Let’s see:"
},
{
"code": null,
"e": 13493,
"s": 13452,
"text": "From the above, we observe three things:"
},
{
"code": null,
"e": 13680,
"s": 13493,
"text": "The output from Node2 (blue) undergoes the avg5×5 operation.The output from Node 1 (red) undergoes a sep5×5 operation.Both the results from these two operations undergo an add operation."
},
{
"code": null,
"e": 13741,
"s": 13680,
"text": "The output from Node2 (blue) undergoes the avg5×5 operation."
},
{
"code": null,
"e": 13800,
"s": 13741,
"text": "The output from Node 1 (red) undergoes a sep5×5 operation."
},
{
"code": null,
"e": 13869,
"s": 13800,
"text": "Both the results from these two operations undergo an add operation."
},
{
"code": null,
"e": 14000,
"s": 13869,
"text": "The output from this node is the tensor that undergoes the add operation. This explains why Nodes 1 and 2 end with add operations."
},
{
"code": null,
"e": 14007,
"s": 14000,
"text": "Node 4"
},
{
"code": null,
"e": 14180,
"s": 14007,
"text": "Now for Node 4. We repeat the same steps, but now the controller now has three nodes to choose from (Nodes 1, 2 and 3). Below, the controller generated 3, 1, id and avg3×3."
},
{
"code": null,
"e": 14223,
"s": 14180,
"text": "This translates to building the following:"
},
{
"code": null,
"e": 14243,
"s": 14223,
"text": "What just happened?"
},
{
"code": null,
"e": 14427,
"s": 14243,
"text": "The output from Node3 (green) undergoes an id operation.The output from Node 1 (red) undergoes an avg3×3 operation.Both the results from these two operations undergo an add operation."
},
{
"code": null,
"e": 14484,
"s": 14427,
"text": "The output from Node3 (green) undergoes an id operation."
},
{
"code": null,
"e": 14544,
"s": 14484,
"text": "The output from Node 1 (red) undergoes an avg3×3 operation."
},
{
"code": null,
"e": 14613,
"s": 14544,
"text": "Both the results from these two operations undergo an add operation."
},
{
"code": null,
"e": 14891,
"s": 14613,
"text": "And that’s it! All convolutional cells in the final child model will share the same architecture. Similarly, all reduction cells (whose architecture differ from that of convolutional cell by having stride 2 operations) in the final child model will share the same architecture."
},
{
"code": null,
"e": 14905,
"s": 14891,
"text": "[Back to top]"
},
{
"code": null,
"e": 15085,
"s": 14905,
"text": "Because this post mainly shows the macro and micro search strategies, I’ve left out many small details (especially on the concept of transfer learning). Let me briefly cover them:"
},
{
"code": null,
"e": 15424,
"s": 15085,
"text": "What’s so ‘efficient’ in ENAS? Answer: transfer learning. If a computation between two nodes has been done (trained) before, the weights from the convolutional filters and 1×1 convolutions (to maintain number of channel outputs; not mentioned in the previous sections) will be reused. This is what makes ENAS faster than its predecessors!"
},
{
"code": null,
"e": 15514,
"s": 15424,
"text": "It is possible that the controller samples a decision where no skip connection is needed."
},
{
"code": null,
"e": 15727,
"s": 15514,
"text": "There are 6 operations available for the controller: convolutions with filter sizes 3×3 and 5×5, depthwise-separable convolutions with filter sizes 3×3 and 5×5, max pooling and average pooling of kernel size 3×3."
},
{
"code": null,
"e": 15832,
"s": 15727,
"text": "Do read up on the concatenate operation at the end of each cell which ties up ‘loose ends’ of any nodes."
},
{
"code": null,
"e": 15920,
"s": 15832,
"text": "Do read up briefly on the policy gradient algorithm (REINFORCE) reinforcement learning."
},
{
"code": null,
"e": 15934,
"s": 15920,
"text": "[Back to top]"
},
{
"code": null,
"e": 15971,
"s": 15934,
"text": "Macro search (for an entire network)"
},
{
"code": null,
"e": 16012,
"s": 15971,
"text": "The final child model is as shown below."
},
{
"code": null,
"e": 16052,
"s": 16012,
"text": "Micro search (for a convolutional cell)"
},
{
"code": null,
"e": 16112,
"s": 16052,
"text": "Note that only part of the final child model is shown here."
},
{
"code": null,
"e": 16126,
"s": 16112,
"text": "[Back to top]"
},
{
"code": null,
"e": 16167,
"s": 16126,
"text": "TensorFlow implementation by the authors"
},
{
"code": null,
"e": 16188,
"s": 16167,
"text": "Keras implementation"
},
{
"code": null,
"e": 16211,
"s": 16188,
"text": "PyTorch implementation"
},
{
"code": null,
"e": 16225,
"s": 16211,
"text": "[Back to top]"
},
{
"code": null,
"e": 16284,
"s": 16225,
"text": "Efficient Neural Architecture Search via Parameter Sharing"
},
{
"code": null,
"e": 16339,
"s": 16284,
"text": "Neural Architecture Search with Reinforcement Learning"
},
{
"code": null,
"e": 16406,
"s": 16339,
"text": "Learning Transferable Architectures for Scalable Image Recognition"
},
{
"code": null,
"e": 16574,
"s": 16406,
"text": "That’s it! Remember to read the ENAS paper Efficient Neural Architecture Search via Parameter Sharing. If you have any questions, please highlight and leave a comment."
},
{
"code": null,
"e": 16582,
"s": 16574,
"text": "General"
},
{
"code": null,
"e": 16633,
"s": 16582,
"text": "Counting No. of Parameters in Deep Learning Models"
},
{
"code": null,
"e": 16648,
"s": 16633,
"text": "Related to NLP"
},
{
"code": null,
"e": 16675,
"s": 16648,
"text": "Animated RNN, LSTM and GRU"
},
{
"code": null,
"e": 16703,
"s": 16675,
"text": "Attn: Illustrated Attention"
},
{
"code": null,
"e": 16731,
"s": 16703,
"text": "Illustrated: Self-Attention"
},
{
"code": null,
"e": 16768,
"s": 16731,
"text": "Line-by-Line Word2Vec Implementation"
},
{
"code": null,
"e": 16795,
"s": 16768,
"text": "Related to Computer Vision"
},
{
"code": null,
"e": 16838,
"s": 16795,
"text": "Breaking down Mean Average Precision (mAP)"
},
{
"code": null,
"e": 16851,
"s": 16838,
"text": "Optimisation"
},
{
"code": null,
"e": 16927,
"s": 16851,
"text": "Step-by-Step Tutorial on Linear Regression with Stochastic Gradient Descent"
},
{
"code": null,
"e": 16985,
"s": 16927,
"text": "10 Gradient Descent Optimisation Algorithms + Cheat Sheet"
}
] |
Scraping the web with Selenium on Google Cloud Composer (Airflow) | by Julian Smidek | Towards Data Science | There are already a lot of different resources available on creating web-scrapers using Python which are usually based on either a combination of the well known Python packages urllib+beautifulsoup4 or Selenium. When you are faced with the challenge to scrape a javascript-heavy web page or a level of interaction with the content is required that can not be achieved by simply sending URL requests, then Selenium is very likely your preferred choice. I don’t want to go into the details here on how you can set-up your scraping script and the best practices on how to run it in a reliable way. I just want to refer to this and this resources that I found are particularly helpful.
The problem that we want to solve in this post is: How can I, as a Data Analyst/Data Scientist, set up an orchestrated and fully managed process to facilitate a Selenium scraper with a minimum of dev-ops required? The main use case for such a set up is a managed and scheduled solution to run all your scraping jobs in the cloud.
The tools we are going to use are:
Google Cloud Composer to schedule jobs and orchestrate workflows
Selenium as a framework to scrape websites
Google Kubernetes Engine to deploy a Selenium remote driver as containerized application in the cloud
At HousingAnywhere we were already using Google Cloud Composer for a number of different tasks. Cloud Composer is quite an amazing tool to easily manage, schedule and monitor workflows as directed acyclic graphs (DAGs). It is based on the open-source framework Apache Airflow and using pure Python, which makes it ideal for everyone working in the data field. The entry barrier to deploy Airflow on your own is relatively high if you are not coming from DevOps which led to some cloud providers to provide managed deployments of Airflow — Google’s Cloud Composer being one of them.
When deploying Selenium for webscraping, we’re actually using the so-called Selenium Webdriver. This WebDriver is a framework that allows you to control a browser using code (Java, .Net, PHP, Python, Perl, Ruby). For most use-cases you would simply download a browser that can directly interact with the WebDriver framework, for example Mozilla Geckodriver or ChromeDriver. The scraping script will initiate a browser instance on your local and execute all actions as specified. In our use case things are a bit more complicated because we want to run the script on a recurring schedule without using any local resources. To be able to deploy and run web scraping scripts in the cloud we need to use a Selenium Remote WebDriver (a.k.a Selenium Grid) instead of the Selenium WebDriver.
The idea behind Selenium Grid is to provide a framework that allows you to run parallel scraping instances by running web browsers on a single or multiple machines . In this case, we can make use of the provided standalone browsers (keep in mind that each of the available browsers, Firefox, Chrome and Opera are a different image) which are already wrapped up as a Docker image.
Cloud Composer runs Apache Airflow on top of a Google Kubernetes Engine (GKE) cluster. Furthermore, it is fully integrated with other Google Cloud products. The creation of a new Cloud Composer environment also comes along with a functional UI and a Cloud Storage bucket. All DAGs, plugins, logs and other required files are stored in this bucket.
You can deploy a docker image for the Firefox standalone browser using the selenium-firefox.yaml file below and apply the specified configuration on your resource by running:
kubectl apply -f selenium-firefox.yaml
The configuration file describes what kind of object you want to create, it’s metadata as well as specs.
We can create new connection in the Admin UI of Airflow and access the connection details later in our Plugin. The connection details are either specified in the yaml file or can be found on your Kubernetes cluster.
After setting up the connections we can access the connection in our scraping script (Airflow Plugin) where we connect to the remote browser.
Thank you Massimo Belloni for technical consultancy and advice in realizing the project and this article. | [
{
"code": null,
"e": 853,
"s": 171,
"text": "There are already a lot of different resources available on creating web-scrapers using Python which are usually based on either a combination of the well known Python packages urllib+beautifulsoup4 or Selenium. When you are faced with the challenge to scrape a javascript-heavy web page or a level of interaction with the content is required that can not be achieved by simply sending URL requests, then Selenium is very likely your preferred choice. I don’t want to go into the details here on how you can set-up your scraping script and the best practices on how to run it in a reliable way. I just want to refer to this and this resources that I found are particularly helpful."
},
{
"code": null,
"e": 1183,
"s": 853,
"text": "The problem that we want to solve in this post is: How can I, as a Data Analyst/Data Scientist, set up an orchestrated and fully managed process to facilitate a Selenium scraper with a minimum of dev-ops required? The main use case for such a set up is a managed and scheduled solution to run all your scraping jobs in the cloud."
},
{
"code": null,
"e": 1218,
"s": 1183,
"text": "The tools we are going to use are:"
},
{
"code": null,
"e": 1283,
"s": 1218,
"text": "Google Cloud Composer to schedule jobs and orchestrate workflows"
},
{
"code": null,
"e": 1326,
"s": 1283,
"text": "Selenium as a framework to scrape websites"
},
{
"code": null,
"e": 1428,
"s": 1326,
"text": "Google Kubernetes Engine to deploy a Selenium remote driver as containerized application in the cloud"
},
{
"code": null,
"e": 2010,
"s": 1428,
"text": "At HousingAnywhere we were already using Google Cloud Composer for a number of different tasks. Cloud Composer is quite an amazing tool to easily manage, schedule and monitor workflows as directed acyclic graphs (DAGs). It is based on the open-source framework Apache Airflow and using pure Python, which makes it ideal for everyone working in the data field. The entry barrier to deploy Airflow on your own is relatively high if you are not coming from DevOps which led to some cloud providers to provide managed deployments of Airflow — Google’s Cloud Composer being one of them."
},
{
"code": null,
"e": 2795,
"s": 2010,
"text": "When deploying Selenium for webscraping, we’re actually using the so-called Selenium Webdriver. This WebDriver is a framework that allows you to control a browser using code (Java, .Net, PHP, Python, Perl, Ruby). For most use-cases you would simply download a browser that can directly interact with the WebDriver framework, for example Mozilla Geckodriver or ChromeDriver. The scraping script will initiate a browser instance on your local and execute all actions as specified. In our use case things are a bit more complicated because we want to run the script on a recurring schedule without using any local resources. To be able to deploy and run web scraping scripts in the cloud we need to use a Selenium Remote WebDriver (a.k.a Selenium Grid) instead of the Selenium WebDriver."
},
{
"code": null,
"e": 3175,
"s": 2795,
"text": "The idea behind Selenium Grid is to provide a framework that allows you to run parallel scraping instances by running web browsers on a single or multiple machines . In this case, we can make use of the provided standalone browsers (keep in mind that each of the available browsers, Firefox, Chrome and Opera are a different image) which are already wrapped up as a Docker image."
},
{
"code": null,
"e": 3523,
"s": 3175,
"text": "Cloud Composer runs Apache Airflow on top of a Google Kubernetes Engine (GKE) cluster. Furthermore, it is fully integrated with other Google Cloud products. The creation of a new Cloud Composer environment also comes along with a functional UI and a Cloud Storage bucket. All DAGs, plugins, logs and other required files are stored in this bucket."
},
{
"code": null,
"e": 3698,
"s": 3523,
"text": "You can deploy a docker image for the Firefox standalone browser using the selenium-firefox.yaml file below and apply the specified configuration on your resource by running:"
},
{
"code": null,
"e": 3737,
"s": 3698,
"text": "kubectl apply -f selenium-firefox.yaml"
},
{
"code": null,
"e": 3842,
"s": 3737,
"text": "The configuration file describes what kind of object you want to create, it’s metadata as well as specs."
},
{
"code": null,
"e": 4058,
"s": 3842,
"text": "We can create new connection in the Admin UI of Airflow and access the connection details later in our Plugin. The connection details are either specified in the yaml file or can be found on your Kubernetes cluster."
},
{
"code": null,
"e": 4200,
"s": 4058,
"text": "After setting up the connections we can access the connection in our scraping script (Airflow Plugin) where we connect to the remote browser."
}
] |
Use Flask and SQLalchemy, not Flask-SQLAlchemy! | by Edward Krueger | Towards Data Science | By: Edward Krueger Data Scientist and Instructor and Douglas Franklin Teaching Assistant and Technical Writer.
In this article, we will cover using Flask with SQLAlchemy and some reasons to avoid Flask-SQLAlchemy. Additionally, we’ll demonstrate the benefits of having SQLAlchemy models and database connections that exist independently of an app.
SQLAlchemy is a Python SQL toolkit and Object Relational Mapper (ORM) that allows app developers to use SQL for smooth and fault-tolerant transactional database operations. The ORM translates Python classes to tables for relational databases and automatically converts Pythonic SQLAlchemy Expression Language to SQL statements. This conversion allows developers to write SQL queries with Python syntax. SQLAlchemy also abstracts database connections and provides connection maintenance automatically. Together these features make SQLAlchemy a fantastic package for loading and querying databases.
Flask is a microframework that allows you to build web apps in Python. Flask is easy to get started with as a beginner because there is little boilerplate code for getting a simple app up and running.
For example, here is a valid “Hello, world!” Flask web app:
from flask import Flaskapp = Flask(__name__)@app.route('/')def hello_world(): return "Hello, World!"if __name__ == '__main__': app.run()
Flask-SQLAlchemy is an extension for Flask that aims to simplify using SQLAlchemy with Flask by providing defaults and helpers to accomplish common tasks. One of the most sought after helpers being the handling of a database connection across the app. However, ensuring your database connection session is available throughout your app can be accomplished with base SQLAlchemy and does not require Flask-SQLAlchemy.
Flask-SQLAlchemy’s purpose is to handle the return of connections to prevent issues with worker threading. These issues arise when an app user switches from one route to another. Below is a common error that occurs when a threading problem is present in a Flask app.
sqlite3.ProgrammingError: SQLite objects created in a thread can only be used in that same thread. The object was created in thread id 12345 and this is thread id 54321.
This is often caused by a session or database connection being unavailable to part of your app. This error effectively breaks your app and must be resolved to continue development.
We opt to avoid the Flask-SQLALchemy default behaviors that prevent this error and instead use SQLAlchemy features to handle these issues. This is because Flask-SQLALchemy has disadvantages when compared with SQLAlchemy.
One of which is that Flask-SQLAlchemy has its own API. This adds complexity by having its different methods for ORM queries and models separate from the SQLAlchemy API.
Another disadvantage is that Flask-SQLAlchemy makes using the database outside of a Flask context difficult. This is because, with Flask-SQLAlchemy, the database connection, models, and app are all located within the app.py file. Having models within the app file, we have limited ability to interact with the database outside of the app. This makes loading data outside of your app difficult. Additionally, this makes it hard to retrieve data outside of the Flask context.
Flask and SQLAlchemy work well together if used correctly. Therefore, you don’t have to hybridize Flask and SQLAlchemy into Flask-SQLalchemy!
Ideally, you should only have to define your database models once! With a separate database.py and models.py file, we can establish our database connection and classes for its tables a single time, then call them later as needed. This separation of components is much more difficult with Flask-SQLAlchemy as you would have to create the database with the app itself.
Here is a file that defines our database connection using SQLAlchemy.
Notice that we import the ‘Base’ class in the database.py file above into the models.py file below to use declarative_base().
This file creates the model or schema for the table ‘Records’ in our database.
Using SQLAlcehmy’s declarative_base() allows you to write just one model per table that app uses. That model is then used in Python outside of the app and in the database.
Having these separate Python files is good because you can use the same model to query or load data outside of an app. Additionally, you’ll have one version of each model and database connection, which simplifies development.
These models and database connections can be used to reference the same models or databases in data pipelines, report generation, or anywhere else they are needed.
The load script alone is a great reason to use SQLAlchemy. Instead of using the app to load data, this functionality allows the loading of a database with a separate Python file.
Here is an example Python file that reads data from a CSV and inserts that data into a database.
Notice that we import the models, our custom session SessionLocal, and our engine that we’ve defined in other Python files.
This separate load.py file allows us to insert data into the database without ever running the app.
The declarative_base() base class contains a MetaData object where newly defined Table objects are collected. This MetaData object is accessed when we call the line models.Base.metadata.create_all()to create all of our tables.
SQLAlchemy includes a helper object that helps with the establishment of user-defined Session scopes. With the scoped_session function, SQLAlchemy can handle worker threading issues.
The sessionmaker is a factory for initializing new Session objects by requesting a connection from the engine’s connection pool and attaching a connection to the new Session object.
Initializing a new session object is also referred to as “checking out” a connection. The database stores a list of these connections/processes. So when you begin a new session, you are starting a new process within the database too.
A scoped_session is the registry of all these created session objects where the key/identity of the registry is some form of a thread-safe id.
We define SessionLocal in the database.py file above by calling the session factory, sessionmaker, and passing it some parameters.
The`scopefunc’ is an optional argument passed to scoped_session that serves as an identity getter function that returns a key to lookup or to register a new session. Adding `_app_ctx_stack.__ident_func__` is one of two functions:
If greenlet is installed, it uses the getcurrent (from greenlet import getcurrent)Otherwise, it uses get_ident (from threading import get_ident), which returns the thread id.
If greenlet is installed, it uses the getcurrent (from greenlet import getcurrent)
Otherwise, it uses get_ident (from threading import get_ident), which returns the thread id.
By default scopefunc is get_ident . So for simple applications, you can just do:
db_session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine))
This new SessionLocal allows different sections of the application to call upon a global scoped_session, so that all app routes can share the same session without passing the session to the route explicitly. The SessionLocal we've established in our registry will remain, until we explicitly tell our registry to dispose of it, by calling scoped_session.remove():
Here we can see the call to scoped_session with our custom session, SessionLocal, passed as an argument.
Additionally, scoped sessions give us access to a query_property. So if you style used by flask_sqlalchemy you can use this with SQLAlchemy:
Base = declarative_base()Base.query = db_session.query_property()
The method db_session.close() only ends the transaction for the local session object, but does not end the connection with the database and does not automatically return the connection to the pool.
By adding a db_session.remove() we ensure our connection is closed properly.
The db_session.remove() method first runs app.db_session.close() and afterward returns the connection to the connection pool. Therefore we have terminated that process locally and at the remote database. If the database doesn't have these connections closed, there is a maximum number of connections that can be reached. The database will eventually kill idle processes like stale connections; however, it can take hours before that happens. SQLAlchemy has some pool options to prevent this, but removing the connections when they are no longer needed is best!
As we have seen, SQLAlchmy has the tools to handle errors that developers turn to Flask-SQLAlchemy to avoid. With the proper implementation of sessionmaker and scoped_session, your Flask app should not have any threading issues that arise when connecting to a database across your routes.
So when struggling with threading and database sessions, use Flask and SQLAlchemy, not Flask-SQLAlchemy!
Special thanks to Seth Kaufman for help writing our Flask app, be sure to check out the repository on GitHub. | [
{
"code": null,
"e": 282,
"s": 171,
"text": "By: Edward Krueger Data Scientist and Instructor and Douglas Franklin Teaching Assistant and Technical Writer."
},
{
"code": null,
"e": 519,
"s": 282,
"text": "In this article, we will cover using Flask with SQLAlchemy and some reasons to avoid Flask-SQLAlchemy. Additionally, we’ll demonstrate the benefits of having SQLAlchemy models and database connections that exist independently of an app."
},
{
"code": null,
"e": 1116,
"s": 519,
"text": "SQLAlchemy is a Python SQL toolkit and Object Relational Mapper (ORM) that allows app developers to use SQL for smooth and fault-tolerant transactional database operations. The ORM translates Python classes to tables for relational databases and automatically converts Pythonic SQLAlchemy Expression Language to SQL statements. This conversion allows developers to write SQL queries with Python syntax. SQLAlchemy also abstracts database connections and provides connection maintenance automatically. Together these features make SQLAlchemy a fantastic package for loading and querying databases."
},
{
"code": null,
"e": 1317,
"s": 1116,
"text": "Flask is a microframework that allows you to build web apps in Python. Flask is easy to get started with as a beginner because there is little boilerplate code for getting a simple app up and running."
},
{
"code": null,
"e": 1377,
"s": 1317,
"text": "For example, here is a valid “Hello, world!” Flask web app:"
},
{
"code": null,
"e": 1520,
"s": 1377,
"text": "from flask import Flaskapp = Flask(__name__)@app.route('/')def hello_world(): return \"Hello, World!\"if __name__ == '__main__': app.run()"
},
{
"code": null,
"e": 1936,
"s": 1520,
"text": "Flask-SQLAlchemy is an extension for Flask that aims to simplify using SQLAlchemy with Flask by providing defaults and helpers to accomplish common tasks. One of the most sought after helpers being the handling of a database connection across the app. However, ensuring your database connection session is available throughout your app can be accomplished with base SQLAlchemy and does not require Flask-SQLAlchemy."
},
{
"code": null,
"e": 2203,
"s": 1936,
"text": "Flask-SQLAlchemy’s purpose is to handle the return of connections to prevent issues with worker threading. These issues arise when an app user switches from one route to another. Below is a common error that occurs when a threading problem is present in a Flask app."
},
{
"code": null,
"e": 2373,
"s": 2203,
"text": "sqlite3.ProgrammingError: SQLite objects created in a thread can only be used in that same thread. The object was created in thread id 12345 and this is thread id 54321."
},
{
"code": null,
"e": 2554,
"s": 2373,
"text": "This is often caused by a session or database connection being unavailable to part of your app. This error effectively breaks your app and must be resolved to continue development."
},
{
"code": null,
"e": 2775,
"s": 2554,
"text": "We opt to avoid the Flask-SQLALchemy default behaviors that prevent this error and instead use SQLAlchemy features to handle these issues. This is because Flask-SQLALchemy has disadvantages when compared with SQLAlchemy."
},
{
"code": null,
"e": 2944,
"s": 2775,
"text": "One of which is that Flask-SQLAlchemy has its own API. This adds complexity by having its different methods for ORM queries and models separate from the SQLAlchemy API."
},
{
"code": null,
"e": 3418,
"s": 2944,
"text": "Another disadvantage is that Flask-SQLAlchemy makes using the database outside of a Flask context difficult. This is because, with Flask-SQLAlchemy, the database connection, models, and app are all located within the app.py file. Having models within the app file, we have limited ability to interact with the database outside of the app. This makes loading data outside of your app difficult. Additionally, this makes it hard to retrieve data outside of the Flask context."
},
{
"code": null,
"e": 3560,
"s": 3418,
"text": "Flask and SQLAlchemy work well together if used correctly. Therefore, you don’t have to hybridize Flask and SQLAlchemy into Flask-SQLalchemy!"
},
{
"code": null,
"e": 3927,
"s": 3560,
"text": "Ideally, you should only have to define your database models once! With a separate database.py and models.py file, we can establish our database connection and classes for its tables a single time, then call them later as needed. This separation of components is much more difficult with Flask-SQLAlchemy as you would have to create the database with the app itself."
},
{
"code": null,
"e": 3997,
"s": 3927,
"text": "Here is a file that defines our database connection using SQLAlchemy."
},
{
"code": null,
"e": 4123,
"s": 3997,
"text": "Notice that we import the ‘Base’ class in the database.py file above into the models.py file below to use declarative_base()."
},
{
"code": null,
"e": 4202,
"s": 4123,
"text": "This file creates the model or schema for the table ‘Records’ in our database."
},
{
"code": null,
"e": 4374,
"s": 4202,
"text": "Using SQLAlcehmy’s declarative_base() allows you to write just one model per table that app uses. That model is then used in Python outside of the app and in the database."
},
{
"code": null,
"e": 4600,
"s": 4374,
"text": "Having these separate Python files is good because you can use the same model to query or load data outside of an app. Additionally, you’ll have one version of each model and database connection, which simplifies development."
},
{
"code": null,
"e": 4764,
"s": 4600,
"text": "These models and database connections can be used to reference the same models or databases in data pipelines, report generation, or anywhere else they are needed."
},
{
"code": null,
"e": 4943,
"s": 4764,
"text": "The load script alone is a great reason to use SQLAlchemy. Instead of using the app to load data, this functionality allows the loading of a database with a separate Python file."
},
{
"code": null,
"e": 5040,
"s": 4943,
"text": "Here is an example Python file that reads data from a CSV and inserts that data into a database."
},
{
"code": null,
"e": 5164,
"s": 5040,
"text": "Notice that we import the models, our custom session SessionLocal, and our engine that we’ve defined in other Python files."
},
{
"code": null,
"e": 5264,
"s": 5164,
"text": "This separate load.py file allows us to insert data into the database without ever running the app."
},
{
"code": null,
"e": 5491,
"s": 5264,
"text": "The declarative_base() base class contains a MetaData object where newly defined Table objects are collected. This MetaData object is accessed when we call the line models.Base.metadata.create_all()to create all of our tables."
},
{
"code": null,
"e": 5674,
"s": 5491,
"text": "SQLAlchemy includes a helper object that helps with the establishment of user-defined Session scopes. With the scoped_session function, SQLAlchemy can handle worker threading issues."
},
{
"code": null,
"e": 5856,
"s": 5674,
"text": "The sessionmaker is a factory for initializing new Session objects by requesting a connection from the engine’s connection pool and attaching a connection to the new Session object."
},
{
"code": null,
"e": 6090,
"s": 5856,
"text": "Initializing a new session object is also referred to as “checking out” a connection. The database stores a list of these connections/processes. So when you begin a new session, you are starting a new process within the database too."
},
{
"code": null,
"e": 6233,
"s": 6090,
"text": "A scoped_session is the registry of all these created session objects where the key/identity of the registry is some form of a thread-safe id."
},
{
"code": null,
"e": 6364,
"s": 6233,
"text": "We define SessionLocal in the database.py file above by calling the session factory, sessionmaker, and passing it some parameters."
},
{
"code": null,
"e": 6594,
"s": 6364,
"text": "The`scopefunc’ is an optional argument passed to scoped_session that serves as an identity getter function that returns a key to lookup or to register a new session. Adding `_app_ctx_stack.__ident_func__` is one of two functions:"
},
{
"code": null,
"e": 6769,
"s": 6594,
"text": "If greenlet is installed, it uses the getcurrent (from greenlet import getcurrent)Otherwise, it uses get_ident (from threading import get_ident), which returns the thread id."
},
{
"code": null,
"e": 6852,
"s": 6769,
"text": "If greenlet is installed, it uses the getcurrent (from greenlet import getcurrent)"
},
{
"code": null,
"e": 6945,
"s": 6852,
"text": "Otherwise, it uses get_ident (from threading import get_ident), which returns the thread id."
},
{
"code": null,
"e": 7026,
"s": 6945,
"text": "By default scopefunc is get_ident . So for simple applications, you can just do:"
},
{
"code": null,
"e": 7116,
"s": 7026,
"text": "db_session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine))"
},
{
"code": null,
"e": 7480,
"s": 7116,
"text": "This new SessionLocal allows different sections of the application to call upon a global scoped_session, so that all app routes can share the same session without passing the session to the route explicitly. The SessionLocal we've established in our registry will remain, until we explicitly tell our registry to dispose of it, by calling scoped_session.remove():"
},
{
"code": null,
"e": 7585,
"s": 7480,
"text": "Here we can see the call to scoped_session with our custom session, SessionLocal, passed as an argument."
},
{
"code": null,
"e": 7726,
"s": 7585,
"text": "Additionally, scoped sessions give us access to a query_property. So if you style used by flask_sqlalchemy you can use this with SQLAlchemy:"
},
{
"code": null,
"e": 7792,
"s": 7726,
"text": "Base = declarative_base()Base.query = db_session.query_property()"
},
{
"code": null,
"e": 7990,
"s": 7792,
"text": "The method db_session.close() only ends the transaction for the local session object, but does not end the connection with the database and does not automatically return the connection to the pool."
},
{
"code": null,
"e": 8067,
"s": 7990,
"text": "By adding a db_session.remove() we ensure our connection is closed properly."
},
{
"code": null,
"e": 8628,
"s": 8067,
"text": "The db_session.remove() method first runs app.db_session.close() and afterward returns the connection to the connection pool. Therefore we have terminated that process locally and at the remote database. If the database doesn't have these connections closed, there is a maximum number of connections that can be reached. The database will eventually kill idle processes like stale connections; however, it can take hours before that happens. SQLAlchemy has some pool options to prevent this, but removing the connections when they are no longer needed is best!"
},
{
"code": null,
"e": 8917,
"s": 8628,
"text": "As we have seen, SQLAlchmy has the tools to handle errors that developers turn to Flask-SQLAlchemy to avoid. With the proper implementation of sessionmaker and scoped_session, your Flask app should not have any threading issues that arise when connecting to a database across your routes."
},
{
"code": null,
"e": 9022,
"s": 8917,
"text": "So when struggling with threading and database sessions, use Flask and SQLAlchemy, not Flask-SQLAlchemy!"
}
] |
Assembly - MOVS Instruction | The MOVS instruction is used to copy a data item (byte, word or doubleword) from the source string to the destination string. The source string is pointed by DS:SI and the destination string is pointed by ES:DI.
The following example explains the concept −
section .text
global _start ;must be declared for using gcc
_start: ;tell linker entry point
mov ecx, len
mov esi, s1
mov edi, s2
cld
rep movsb
mov edx,20 ;message length
mov ecx,s2 ;message to write
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
s1 db 'Hello, world!',0 ;string 1
len equ $-s1
section .bss
s2 resb 20 ;destination
When the above code is compiled and executed, it produces the following result −
Hello, world!
46 Lectures
2 hours
Frahaan Hussain
23 Lectures
12 hours
Uplatz
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2297,
"s": 2085,
"text": "The MOVS instruction is used to copy a data item (byte, word or doubleword) from the source string to the destination string. The source string is pointed by DS:SI and the destination string is pointed by ES:DI."
},
{
"code": null,
"e": 2342,
"s": 2297,
"text": "The following example explains the concept −"
},
{
"code": null,
"e": 2944,
"s": 2342,
"text": "section\t.text\n global _start ;must be declared for using gcc\n\t\n_start:\t ;tell linker entry point\n mov\tecx, len\n mov\tesi, s1\n mov\tedi, s2\n cld\n rep\tmovsb\n\t\n mov\tedx,20\t ;message length\n mov\tecx,s2\t ;message to write\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\ns1 db 'Hello, world!',0 ;string 1\nlen equ $-s1\n\nsection\t .bss\ns2 resb\t20 ;destination"
},
{
"code": null,
"e": 3025,
"s": 2944,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 3040,
"s": 3025,
"text": "Hello, world!\n"
},
{
"code": null,
"e": 3073,
"s": 3040,
"text": "\n 46 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3090,
"s": 3073,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3124,
"s": 3090,
"text": "\n 23 Lectures \n 12 hours \n"
},
{
"code": null,
"e": 3132,
"s": 3124,
"text": " Uplatz"
},
{
"code": null,
"e": 3139,
"s": 3132,
"text": " Print"
},
{
"code": null,
"e": 3150,
"s": 3139,
"text": " Add Notes"
}
] |
How to set the number of ticks in plt.colorbar in Matplotlib? | To set the number of ticks in a colorbar, we can take the following steps−
Create random data using numpy
Display the data as an image, i.e., on a 2D regular raster.
Make a colorbar using colorbar() method with an image scalar mappable object.
Set the ticks and tick labels of the colorbar using set_ticks() and set_ticklabels() methods.
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
data = np.random.rand(4, 4)
im = plt.imshow(data, cmap="copper")
cbar = plt.colorbar(im)
cbar.set_ticks([0.2, 0.4, 0.6, 0.8])
cbar.set_ticklabels(["A", "B", "C", "D"])
plt.show() | [
{
"code": null,
"e": 1137,
"s": 1062,
"text": "To set the number of ticks in a colorbar, we can take the following steps−"
},
{
"code": null,
"e": 1168,
"s": 1137,
"text": "Create random data using numpy"
},
{
"code": null,
"e": 1228,
"s": 1168,
"text": "Display the data as an image, i.e., on a 2D regular raster."
},
{
"code": null,
"e": 1306,
"s": 1228,
"text": "Make a colorbar using colorbar() method with an image scalar mappable object."
},
{
"code": null,
"e": 1400,
"s": 1306,
"text": "Set the ticks and tick labels of the colorbar using set_ticks() and set_ticklabels() methods."
},
{
"code": null,
"e": 1442,
"s": 1400,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 1764,
"s": 1442,
"text": "import numpy as np\nfrom matplotlib import pyplot as plt\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\ndata = np.random.rand(4, 4)\nim = plt.imshow(data, cmap=\"copper\")\ncbar = plt.colorbar(im)\ncbar.set_ticks([0.2, 0.4, 0.6, 0.8])\ncbar.set_ticklabels([\"A\", \"B\", \"C\", \"D\"])\nplt.show()"
}
] |
How to download NGS data from the NCBI database | Towards Data Science | The Sequence Read Archive, or SRA, is NCBI’s database of storing Next Generation Sequence DNA data from sequencing experiments on any species, including humans. For those new to bioinformatics, it can be unclear how to access the data from this massive resource. It’s most likely you will be trying to access data from a research article you’ve just read, and the authors will have provide a Data Availability Statement that includes an accession number. This guide will assume you have the accession number ready. Bioinformatics software runs primarily on Unix based operating systems, and this is the case for the toolkit needed to download SRA data. You will need a computer running Linux or MacOS. This guide is specifically for MacOS, but the commands for MacOS and Linux are mostly the same, though they might require some minor tweaks between operating systems. Finally, NGS data is typically massive so you will need a decent amount of free storage on your machine. Depending on the species the dataset came from, full analysis of the NGS data can use upwards of 100Gb of memory. Just downloading a singe file should required no more than 50Gb though. Let’s start with downloading the software required for the job.
The SRA Toolkit contains all the programs we need to download and manipulate the data from SRA. To download it, navigate over to NCBI’s sra-tools GitHub page and download the appropriate file for your operating system. In your Downloads folder, double click the .tar file and navigate into the newly created folder. The programs we will be using for downloading the SRA data are located in the bin folder. We need to get the pathname of that bin folder and navigate into it on the command line. To do this, right click the bin folder, hold down the option key, and select ‘Copy “bin” as pathname’.
Now, open terminal and type in the following command, replacing <path/to/bin> by pasting in the pathname copied earlier:
cd <path/to/bin>
To check everything is in working order, run the following command:
./fastq-dump — stdout SRR390728 | head -n 8
You should get the following output:
@SRR390728.1 1 length=72CATTCTTCACGTAGTTCTCGAGCCTTGGTTTTCAGCGATGGAGAATGACTTTGACAAGCTGAGAGAAGNTNC+SRR390728.1 1 length=72;;;;;;;;;;;;;;;;;;;;;;;;;;;9;;665142;;;;;;;;;;;;;;;;;;;;;;;;;;;;;96&&&&(@SRR390728.2 2 length=72AAGTAGGTCTCGTCTGTGTTTTCTACGAGCTTGTGTTCCAGCTGACCCACTCCCTGGGTGGGGGGACTGGGT+SRR390728.2 2 length=72;;;;;;;;;;;;;;;;;4;;;;3;393.1+4&&5&&;;;;;;;;;;;;;;;;;;;;;<9;<;;;;;464262
We are now ready to download some data.
The first thing we need to do is find the Run number of the data, which is different to the accession number listed in the research article. To get the Run number, navigate to the NCBI SRA webpage, paste in your accession number from the research article and search. From the list, click the sample you are interested in, and under Runs, copy the number beginning with SRR followed by 6 or 7 digits. There is a lot of different accession type numbers on this page, but you have to select the right one to use in the next step.
Back to the command line, we are going to use the prefetch command to download the data plus any necessary files associated with it. To download the data run the following command, where <SRR0000000> is your Run number from above.
./prefetch <SRR0000000>
The file will download to the bin folder, so take a look to make sure it’s there after the download is complete and before moving on to the next step. Downloading could take a while depending on your internet speed and the size of the file being downloaded.
The prefetch program will download a .sra file, which is not a very useful file format. We need to convert this file into the standard NGS file format of FASTQ to do any work with it. We will use the fastq-dump tool to convert the data. There are quite a few options you can use with fastq-dump but if you are not sure which one to use, you can safely ignore them all for now. The --split-files option is likely the most useful one, it splits paired-end reads into separate files. To convert the .sra file into .fastq, make sure the file is in the bin folder and run the following command, where [options] are any relevant options and <SRR0000000> is the SRR number of your .sra file:
./fastq-dump [options] <SRR0000000>
The final FASTQ file will be dumped into the bin folder. This process could take a while depending on file size. After the conversion, we can visualise some of the bases in the file by using the head command piped into the less command.
head -10000 <filename> | less
You can go on to do any further processing with your FASTQ file now, including mapping to reference and variant analysis. | [
{
"code": null,
"e": 1396,
"s": 172,
"text": "The Sequence Read Archive, or SRA, is NCBI’s database of storing Next Generation Sequence DNA data from sequencing experiments on any species, including humans. For those new to bioinformatics, it can be unclear how to access the data from this massive resource. It’s most likely you will be trying to access data from a research article you’ve just read, and the authors will have provide a Data Availability Statement that includes an accession number. This guide will assume you have the accession number ready. Bioinformatics software runs primarily on Unix based operating systems, and this is the case for the toolkit needed to download SRA data. You will need a computer running Linux or MacOS. This guide is specifically for MacOS, but the commands for MacOS and Linux are mostly the same, though they might require some minor tweaks between operating systems. Finally, NGS data is typically massive so you will need a decent amount of free storage on your machine. Depending on the species the dataset came from, full analysis of the NGS data can use upwards of 100Gb of memory. Just downloading a singe file should required no more than 50Gb though. Let’s start with downloading the software required for the job."
},
{
"code": null,
"e": 1994,
"s": 1396,
"text": "The SRA Toolkit contains all the programs we need to download and manipulate the data from SRA. To download it, navigate over to NCBI’s sra-tools GitHub page and download the appropriate file for your operating system. In your Downloads folder, double click the .tar file and navigate into the newly created folder. The programs we will be using for downloading the SRA data are located in the bin folder. We need to get the pathname of that bin folder and navigate into it on the command line. To do this, right click the bin folder, hold down the option key, and select ‘Copy “bin” as pathname’."
},
{
"code": null,
"e": 2115,
"s": 1994,
"text": "Now, open terminal and type in the following command, replacing <path/to/bin> by pasting in the pathname copied earlier:"
},
{
"code": null,
"e": 2132,
"s": 2115,
"text": "cd <path/to/bin>"
},
{
"code": null,
"e": 2200,
"s": 2132,
"text": "To check everything is in working order, run the following command:"
},
{
"code": null,
"e": 2244,
"s": 2200,
"text": "./fastq-dump — stdout SRR390728 | head -n 8"
},
{
"code": null,
"e": 2281,
"s": 2244,
"text": "You should get the following output:"
},
{
"code": null,
"e": 2666,
"s": 2281,
"text": "@SRR390728.1 1 length=72CATTCTTCACGTAGTTCTCGAGCCTTGGTTTTCAGCGATGGAGAATGACTTTGACAAGCTGAGAGAAGNTNC+SRR390728.1 1 length=72;;;;;;;;;;;;;;;;;;;;;;;;;;;9;;665142;;;;;;;;;;;;;;;;;;;;;;;;;;;;;96&&&&(@SRR390728.2 2 length=72AAGTAGGTCTCGTCTGTGTTTTCTACGAGCTTGTGTTCCAGCTGACCCACTCCCTGGGTGGGGGGACTGGGT+SRR390728.2 2 length=72;;;;;;;;;;;;;;;;;4;;;;3;393.1+4&&5&&;;;;;;;;;;;;;;;;;;;;;<9;<;;;;;464262"
},
{
"code": null,
"e": 2706,
"s": 2666,
"text": "We are now ready to download some data."
},
{
"code": null,
"e": 3233,
"s": 2706,
"text": "The first thing we need to do is find the Run number of the data, which is different to the accession number listed in the research article. To get the Run number, navigate to the NCBI SRA webpage, paste in your accession number from the research article and search. From the list, click the sample you are interested in, and under Runs, copy the number beginning with SRR followed by 6 or 7 digits. There is a lot of different accession type numbers on this page, but you have to select the right one to use in the next step."
},
{
"code": null,
"e": 3464,
"s": 3233,
"text": "Back to the command line, we are going to use the prefetch command to download the data plus any necessary files associated with it. To download the data run the following command, where <SRR0000000> is your Run number from above."
},
{
"code": null,
"e": 3488,
"s": 3464,
"text": "./prefetch <SRR0000000>"
},
{
"code": null,
"e": 3746,
"s": 3488,
"text": "The file will download to the bin folder, so take a look to make sure it’s there after the download is complete and before moving on to the next step. Downloading could take a while depending on your internet speed and the size of the file being downloaded."
},
{
"code": null,
"e": 4431,
"s": 3746,
"text": "The prefetch program will download a .sra file, which is not a very useful file format. We need to convert this file into the standard NGS file format of FASTQ to do any work with it. We will use the fastq-dump tool to convert the data. There are quite a few options you can use with fastq-dump but if you are not sure which one to use, you can safely ignore them all for now. The --split-files option is likely the most useful one, it splits paired-end reads into separate files. To convert the .sra file into .fastq, make sure the file is in the bin folder and run the following command, where [options] are any relevant options and <SRR0000000> is the SRR number of your .sra file:"
},
{
"code": null,
"e": 4467,
"s": 4431,
"text": "./fastq-dump [options] <SRR0000000>"
},
{
"code": null,
"e": 4704,
"s": 4467,
"text": "The final FASTQ file will be dumped into the bin folder. This process could take a while depending on file size. After the conversion, we can visualise some of the bases in the file by using the head command piped into the less command."
},
{
"code": null,
"e": 4734,
"s": 4704,
"text": "head -10000 <filename> | less"
}
] |
Triangular Numbers | 26 Mar, 2021
A number is termed as triangular number if we can represent it in the form of triangular grid of points such that the points form an equilateral triangle and each row contains as many points as the row number, i.e., the first row has one point, second row has two points, third row has three points and so on. The starting triangular numbers are 1, 3 (1+2), 6 (1+2+3), 10 (1+2+3+4).
How to check if a number is Triangular? The idea is based on the fact that n’th triangular number can be written as sum of n natural numbers, that is n*(n+1)/2. The reason for this is simple, base line of triangular grid has n dots, line above base has (n-1) dots and so on. Method 1 (Simple) We start with 1 and check if the number is equal to 1. If it is not, we add 2 to make it 3 and recheck with the number. We repeat this procedure until the sum remains less than or equal to the number that is to be checked for being triangular.Following is the implementations to check if a number is triangular number.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to check if a number is a triangular number// using simple approach.#include <iostream>using namespace std; // Returns true if 'num' is triangular, else falsebool isTriangular(int num){ // Base case if (num < 0) return false; // A Triangular number must be sum of first n // natural numbers int sum = 0; for (int n=1; sum<=num; n++) { sum = sum + n; if (sum==num) return true; } return false;} // Driver codeint main(){ int n = 55; if (isTriangular(n)) cout << "The number is a triangular number"; else cout << "The number is NOT a triangular number"; return 0;}
// Java program to check if a// number is a triangular number// using simple approachclass GFG{ // Returns true if 'num' is // triangular, else false static boolean isTriangular(int num) { // Base case if (num < 0) return false; // A Triangular number must be // sum of first n natural numbers int sum = 0; for (int n = 1; sum <= num; n++) { sum = sum + n; if (sum == num) return true; } return false; } // Driver code public static void main (String[] args) { int n = 55; if (isTriangular(n)) System.out.print("The number " + "is a triangular number"); else System.out.print("The number" + " is NOT a triangular number"); }} // This code is contributed// by Anant Agarwal.
# Python3 program to check if a number is a# triangular number using simple approach. # Returns True if 'num' is triangular, else Falsedef isTriangular(num): # Base case if (num < 0): return False # A Triangular number must be # sum of first n natural numbers sum, n = 0, 1 while(sum <= num): sum = sum + n if (sum == num): return True n += 1 return False # Driver coden = 55if (isTriangular(n)): print("The number is a triangular number")else: print("The number is NOT a triangular number") # This code is contributed by Smitha Dinesh Semwal.
// C# program to check if a number is a// triangular number using simple approachusing System; class GFG { // Returns true if 'num' is // triangular, else false static bool isTriangular(int num) { // Base case if (num < 0) return false; // A Triangular number must be // sum of first n natural numbers int sum = 0; for (int n = 1; sum <= num; n++) { sum = sum + n; if (sum == num) return true; } return false; } // Driver code public static void Main () { int n = 55; if (isTriangular(n)) Console.WriteLine("The number " + "is a triangular number"); else Console.WriteLine("The number" + " is NOT a triangular number"); }} // This code is contributed by vt_m.
<?php// PHP program to check if a number is a// triangular number using simple approach. // Returns true if 'num' is triangular,// else falsefunction isTriangular( $num){ // Base case if ($num < 0) return false; // A Triangular number must be // sum of first n natural numbers $sum = 0; for ($n = 1; $sum <= $num; $n++) { $sum = $sum + $n; if ($sum == $num) return true; } return false;} // Driver code$n = 55;if (isTriangular($n)) echo "The number is a triangular number";else echo "The number is NOT a triangular number"; // This code is contributed by Rajput-Ji?>
<script>// javascript program to check if a number is a triangular number// using simple approach. // Returns true if 'num' is triangular, else falsefunction isTriangular(num){ // Base case if (num < 0) return false; // A Triangular number must be sum of first n // natural numbers let sum = 0; for (let n = 1; sum <= num; n++) { sum = sum + n; if (sum == num) return true; } return false;} // Driver codelet n = 55; if (isTriangular(n)) document.write( "The number is a triangular number"); else document.write( "The number is NOT a triangular number"); // This code is contributed by aashish1995 </script>
Output:
The number is a triangular number
Method 2 (Using Quadratic Equation Root Formula) We form a quadratic equation by equating the number to the formula of sum of first ‘n’ natural numbers, and if we get atleast one value of ‘n’ that is a natural number, we say that the number is a triangular number.
Let the input number be 'num'. We consider,
n*(n+1) = num
as,
n2 + n + (-2 * num) = 0
Below is the implementation of above idea.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to check if a number is a triangular number// using quadratic equation.#include <bits/stdc++.h>using namespace std; // Returns true if num is triangularbool isTriangular(int num){ if (num < 0) return false; // Considering the equation n*(n+1)/2 = num // The equation is : a(n^2) + bn + c = 0"; int c = (-2 * num); int b = 1, a = 1; int d = (b * b) - (4 * a * c); if (d < 0) return false; // Find roots of equation float root1 = ( -b + sqrt(d)) / (2 * a); float root2 = ( -b - sqrt(d)) / (2 * a); // checking if root1 is natural if (root1 > 0 && floor(root1) == root1) return true; // checking if root2 is natural if (root2 > 0 && floor(root2) == root2) return true; return false;} // Driver codeint main(){ int num = 55; if (isTriangular(num)) cout << "The number is a triangular number"; else cout << "The number is NOT a triangular number"; return 0;}
// Java program to check if a number is a// triangular number using quadratic equation.import java.io.*; class GFG { // Returns true if num is triangular static boolean isTriangular(int num) { if (num < 0) return false; // Considering the equation // n*(n+1)/2 = num // The equation is : // a(n^2) + bn + c = 0"; int c = (-2 * num); int b = 1, a = 1; int d = (b * b) - (4 * a * c); if (d < 0) return false; // Find roots of equation float root1 = ( -b + (float)Math.sqrt(d)) / (2 * a); float root2 = ( -b - (float)Math.sqrt(d)) / (2 * a); // checking if root1 is natural if (root1 > 0 && Math.floor(root1) == root1) return true; // checking if root2 is natural if (root2 > 0 && Math.floor(root2) == root2) return true; return false; } // Driver code public static void main (String[] args) { int num = 55; if (isTriangular(num)) System.out.println("The number is" + " a triangular number"); else System.out.println ("The number " + "is NOT a triangular number"); }} //This code is contributed by vt_m.
# Python3 program to check if a number is a# triangular number using quadratic equation.import math # Returns True if num is triangulardef isTriangular(num): if (num < 0): return False # Considering the equation n*(n+1)/2 = num # The equation is : a(n^2) + bn + c = 0 c = (-2 * num) b, a = 1, 1 d = (b * b) - (4 * a * c) if (d < 0): return False # Find roots of equation root1 = ( -b + math.sqrt(d)) / (2 * a) root2 = ( -b - math.sqrt(d)) / (2 * a) # checking if root1 is natural if (root1 > 0 and math.floor(root1) == root1): return True # checking if root2 is natural if (root2 > 0 and math.floor(root2) == root2): return True return False # Driver coden = 55if (isTriangular(n)): print("The number is a triangular number")else: print("The number is NOT a triangular number") # This code is contributed by Smitha Dinesh Semwal
// C# program to check if a number is a triangular// number using quadratic equation.using System; class GFG { // Returns true if num is triangular static bool isTriangular(int num) { if (num < 0) return false; // Considering the equation n*(n+1)/2 = num // The equation is : a(n^2) + bn + c = 0"; int c = (-2 * num); int b = 1, a = 1; int d = (b * b) - (4 * a * c); if (d < 0) return false; // Find roots of equation float root1 = ( -b + (float)Math.Sqrt(d)) / (2 * a); float root2 = ( -b - (float)Math.Sqrt(d)) / (2 * a); // checking if root1 is natural if (root1 > 0 && Math.Floor(root1) == root1) return true; // checking if root2 is natural if (root2 > 0 && Math.Floor(root2) == root2) return true; return false; } // Driver code public static void Main () { int num = 55; if (isTriangular(num)) Console.WriteLine("The number is a " + "triangular number"); else Console.WriteLine ("The number is NOT " + "a triangular number"); }} //This code is contributed by vt_m.
<?php// PHP program to check if a number is a// triangular number using quadratic equation. // Returns true if num is triangularfunction isTriangular($num){ if ($num < 0) return false; // Considering the equation // n*(n+1)/2 = num // The equation is : // a(n^2) + bn + c = 0"; $c = (-2 * $num); $b = 1; $a = 1; $d = ($b * $b) - (4 * $a * $c); if ($d < 0) return false; // Find roots of equation $root1 = (-$b + (float)sqrt($d)) / (2 * $a); $root2 = (-$b - (float)sqrt($d)) / (2 * $a); // checking if root1 is natural if ($root1 > 0 && floor($root1) == $root1) return true; // checking if root2 is natural if ($root2 > 0 && floor($root2) == $root2) return true; return false;} // Driver code$num = 55;if (isTriangular($num)) echo("The number is" . " a triangular number");else echo ("The number " . "is NOT a triangular number"); // This code is contributed// by Code_Mech.?>
<script>// javascript program to check if a number is a// triangular number using quadratic equation. // Returns true if num is triangular function isTriangular(num) { if (num < 0) return false; // Considering the equation // n*(n+1)/2 = num // The equation is : // a(n^2) + bn + c = 0"; var c = (-2 * num); var b = 1, a = 1; var d = (b * b) - (4 * a * c); if (d < 0) return false; // Find roots of equation var root1 = (-b + Math.sqrt(d)) / (2 * a); var root2 = (-b - Math.sqrt(d)) / (2 * a); // checking if root1 is natural if (root1 > 0 && Math.floor(root1) == root1) return true; // checking if root2 is natural if (root2 > 0 && Math.floor(root2) == root2) return true; return false; } // Driver code var num = 55; if (isTriangular(num)) document.write("The number is" + " a triangular number"); else document.write("The number " + "is NOT a triangular number"); // This code is contributed by Rajput-Ji</script>
Output:
The number is a triangular number
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Rajput-Ji
Code_Mech
aashish1995
series
triangle
triangular-number
Mathematical
Mathematical
series
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operators in C / C++
Find minimum number of coins that make a given value
Minimum number of jumps to reach end
Algorithm to solve Rubik's Cube
Modulo 10^9+7 (1000000007)
The Knight's tour problem | Backtracking-1
Modulo Operator (%) in C/C++ with Examples
Program for factorial of a number
Program to find sum of elements in a given array
Merge two sorted arrays with O(1) extra space | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n26 Mar, 2021"
},
{
"code": null,
"e": 436,
"s": 52,
"text": "A number is termed as triangular number if we can represent it in the form of triangular grid of points such that the points form an equilateral triangle and each row contains as many points as the row number, i.e., the first row has one point, second row has two points, third row has three points and so on. The starting triangular numbers are 1, 3 (1+2), 6 (1+2+3), 10 (1+2+3+4). "
},
{
"code": null,
"e": 1053,
"s": 438,
"text": "How to check if a number is Triangular? The idea is based on the fact that n’th triangular number can be written as sum of n natural numbers, that is n*(n+1)/2. The reason for this is simple, base line of triangular grid has n dots, line above base has (n-1) dots and so on. Method 1 (Simple) We start with 1 and check if the number is equal to 1. If it is not, we add 2 to make it 3 and recheck with the number. We repeat this procedure until the sum remains less than or equal to the number that is to be checked for being triangular.Following is the implementations to check if a number is triangular number. "
},
{
"code": null,
"e": 1057,
"s": 1053,
"text": "C++"
},
{
"code": null,
"e": 1062,
"s": 1057,
"text": "Java"
},
{
"code": null,
"e": 1070,
"s": 1062,
"text": "Python3"
},
{
"code": null,
"e": 1073,
"s": 1070,
"text": "C#"
},
{
"code": null,
"e": 1077,
"s": 1073,
"text": "PHP"
},
{
"code": null,
"e": 1088,
"s": 1077,
"text": "Javascript"
},
{
"code": "// C++ program to check if a number is a triangular number// using simple approach.#include <iostream>using namespace std; // Returns true if 'num' is triangular, else falsebool isTriangular(int num){ // Base case if (num < 0) return false; // A Triangular number must be sum of first n // natural numbers int sum = 0; for (int n=1; sum<=num; n++) { sum = sum + n; if (sum==num) return true; } return false;} // Driver codeint main(){ int n = 55; if (isTriangular(n)) cout << \"The number is a triangular number\"; else cout << \"The number is NOT a triangular number\"; return 0;}",
"e": 1754,
"s": 1088,
"text": null
},
{
"code": "// Java program to check if a// number is a triangular number// using simple approachclass GFG{ // Returns true if 'num' is // triangular, else false static boolean isTriangular(int num) { // Base case if (num < 0) return false; // A Triangular number must be // sum of first n natural numbers int sum = 0; for (int n = 1; sum <= num; n++) { sum = sum + n; if (sum == num) return true; } return false; } // Driver code public static void main (String[] args) { int n = 55; if (isTriangular(n)) System.out.print(\"The number \" + \"is a triangular number\"); else System.out.print(\"The number\" + \" is NOT a triangular number\"); }} // This code is contributed// by Anant Agarwal.",
"e": 2665,
"s": 1754,
"text": null
},
{
"code": "# Python3 program to check if a number is a# triangular number using simple approach. # Returns True if 'num' is triangular, else Falsedef isTriangular(num): # Base case if (num < 0): return False # A Triangular number must be # sum of first n natural numbers sum, n = 0, 1 while(sum <= num): sum = sum + n if (sum == num): return True n += 1 return False # Driver coden = 55if (isTriangular(n)): print(\"The number is a triangular number\")else: print(\"The number is NOT a triangular number\") # This code is contributed by Smitha Dinesh Semwal.",
"e": 3284,
"s": 2665,
"text": null
},
{
"code": "// C# program to check if a number is a// triangular number using simple approachusing System; class GFG { // Returns true if 'num' is // triangular, else false static bool isTriangular(int num) { // Base case if (num < 0) return false; // A Triangular number must be // sum of first n natural numbers int sum = 0; for (int n = 1; sum <= num; n++) { sum = sum + n; if (sum == num) return true; } return false; } // Driver code public static void Main () { int n = 55; if (isTriangular(n)) Console.WriteLine(\"The number \" + \"is a triangular number\"); else Console.WriteLine(\"The number\" + \" is NOT a triangular number\"); }} // This code is contributed by vt_m.",
"e": 4189,
"s": 3284,
"text": null
},
{
"code": "<?php// PHP program to check if a number is a// triangular number using simple approach. // Returns true if 'num' is triangular,// else falsefunction isTriangular( $num){ // Base case if ($num < 0) return false; // A Triangular number must be // sum of first n natural numbers $sum = 0; for ($n = 1; $sum <= $num; $n++) { $sum = $sum + $n; if ($sum == $num) return true; } return false;} // Driver code$n = 55;if (isTriangular($n)) echo \"The number is a triangular number\";else echo \"The number is NOT a triangular number\"; // This code is contributed by Rajput-Ji?>",
"e": 4832,
"s": 4189,
"text": null
},
{
"code": "<script>// javascript program to check if a number is a triangular number// using simple approach. // Returns true if 'num' is triangular, else falsefunction isTriangular(num){ // Base case if (num < 0) return false; // A Triangular number must be sum of first n // natural numbers let sum = 0; for (let n = 1; sum <= num; n++) { sum = sum + n; if (sum == num) return true; } return false;} // Driver codelet n = 55; if (isTriangular(n)) document.write( \"The number is a triangular number\"); else document.write( \"The number is NOT a triangular number\"); // This code is contributed by aashish1995 </script>",
"e": 5527,
"s": 4832,
"text": null
},
{
"code": null,
"e": 5537,
"s": 5527,
"text": "Output: "
},
{
"code": null,
"e": 5573,
"s": 5537,
"text": " The number is a triangular number "
},
{
"code": null,
"e": 5843,
"s": 5573,
"text": " Method 2 (Using Quadratic Equation Root Formula) We form a quadratic equation by equating the number to the formula of sum of first ‘n’ natural numbers, and if we get atleast one value of ‘n’ that is a natural number, we say that the number is a triangular number. "
},
{
"code": null,
"e": 5934,
"s": 5843,
"text": "Let the input number be 'num'. We consider,\n\nn*(n+1) = num\n\nas,\n\n n2 + n + (-2 * num) = 0 "
},
{
"code": null,
"e": 5978,
"s": 5934,
"text": "Below is the implementation of above idea. "
},
{
"code": null,
"e": 5982,
"s": 5978,
"text": "C++"
},
{
"code": null,
"e": 5987,
"s": 5982,
"text": "Java"
},
{
"code": null,
"e": 5995,
"s": 5987,
"text": "Python3"
},
{
"code": null,
"e": 5998,
"s": 5995,
"text": "C#"
},
{
"code": null,
"e": 6002,
"s": 5998,
"text": "PHP"
},
{
"code": null,
"e": 6013,
"s": 6002,
"text": "Javascript"
},
{
"code": "// C++ program to check if a number is a triangular number// using quadratic equation.#include <bits/stdc++.h>using namespace std; // Returns true if num is triangularbool isTriangular(int num){ if (num < 0) return false; // Considering the equation n*(n+1)/2 = num // The equation is : a(n^2) + bn + c = 0\"; int c = (-2 * num); int b = 1, a = 1; int d = (b * b) - (4 * a * c); if (d < 0) return false; // Find roots of equation float root1 = ( -b + sqrt(d)) / (2 * a); float root2 = ( -b - sqrt(d)) / (2 * a); // checking if root1 is natural if (root1 > 0 && floor(root1) == root1) return true; // checking if root2 is natural if (root2 > 0 && floor(root2) == root2) return true; return false;} // Driver codeint main(){ int num = 55; if (isTriangular(num)) cout << \"The number is a triangular number\"; else cout << \"The number is NOT a triangular number\"; return 0;}",
"e": 6989,
"s": 6013,
"text": null
},
{
"code": "// Java program to check if a number is a// triangular number using quadratic equation.import java.io.*; class GFG { // Returns true if num is triangular static boolean isTriangular(int num) { if (num < 0) return false; // Considering the equation // n*(n+1)/2 = num // The equation is : // a(n^2) + bn + c = 0\"; int c = (-2 * num); int b = 1, a = 1; int d = (b * b) - (4 * a * c); if (d < 0) return false; // Find roots of equation float root1 = ( -b + (float)Math.sqrt(d)) / (2 * a); float root2 = ( -b - (float)Math.sqrt(d)) / (2 * a); // checking if root1 is natural if (root1 > 0 && Math.floor(root1) == root1) return true; // checking if root2 is natural if (root2 > 0 && Math.floor(root2) == root2) return true; return false; } // Driver code public static void main (String[] args) { int num = 55; if (isTriangular(num)) System.out.println(\"The number is\" + \" a triangular number\"); else System.out.println (\"The number \" + \"is NOT a triangular number\"); }} //This code is contributed by vt_m.",
"e": 8384,
"s": 6989,
"text": null
},
{
"code": "# Python3 program to check if a number is a# triangular number using quadratic equation.import math # Returns True if num is triangulardef isTriangular(num): if (num < 0): return False # Considering the equation n*(n+1)/2 = num # The equation is : a(n^2) + bn + c = 0 c = (-2 * num) b, a = 1, 1 d = (b * b) - (4 * a * c) if (d < 0): return False # Find roots of equation root1 = ( -b + math.sqrt(d)) / (2 * a) root2 = ( -b - math.sqrt(d)) / (2 * a) # checking if root1 is natural if (root1 > 0 and math.floor(root1) == root1): return True # checking if root2 is natural if (root2 > 0 and math.floor(root2) == root2): return True return False # Driver coden = 55if (isTriangular(n)): print(\"The number is a triangular number\")else: print(\"The number is NOT a triangular number\") # This code is contributed by Smitha Dinesh Semwal",
"e": 9300,
"s": 8384,
"text": null
},
{
"code": "// C# program to check if a number is a triangular// number using quadratic equation.using System; class GFG { // Returns true if num is triangular static bool isTriangular(int num) { if (num < 0) return false; // Considering the equation n*(n+1)/2 = num // The equation is : a(n^2) + bn + c = 0\"; int c = (-2 * num); int b = 1, a = 1; int d = (b * b) - (4 * a * c); if (d < 0) return false; // Find roots of equation float root1 = ( -b + (float)Math.Sqrt(d)) / (2 * a); float root2 = ( -b - (float)Math.Sqrt(d)) / (2 * a); // checking if root1 is natural if (root1 > 0 && Math.Floor(root1) == root1) return true; // checking if root2 is natural if (root2 > 0 && Math.Floor(root2) == root2) return true; return false; } // Driver code public static void Main () { int num = 55; if (isTriangular(num)) Console.WriteLine(\"The number is a \" + \"triangular number\"); else Console.WriteLine (\"The number is NOT \" + \"a triangular number\"); }} //This code is contributed by vt_m.",
"e": 10706,
"s": 9300,
"text": null
},
{
"code": "<?php// PHP program to check if a number is a// triangular number using quadratic equation. // Returns true if num is triangularfunction isTriangular($num){ if ($num < 0) return false; // Considering the equation // n*(n+1)/2 = num // The equation is : // a(n^2) + bn + c = 0\"; $c = (-2 * $num); $b = 1; $a = 1; $d = ($b * $b) - (4 * $a * $c); if ($d < 0) return false; // Find roots of equation $root1 = (-$b + (float)sqrt($d)) / (2 * $a); $root2 = (-$b - (float)sqrt($d)) / (2 * $a); // checking if root1 is natural if ($root1 > 0 && floor($root1) == $root1) return true; // checking if root2 is natural if ($root2 > 0 && floor($root2) == $root2) return true; return false;} // Driver code$num = 55;if (isTriangular($num)) echo(\"The number is\" . \" a triangular number\");else echo (\"The number \" . \"is NOT a triangular number\"); // This code is contributed// by Code_Mech.?>",
"e": 11699,
"s": 10706,
"text": null
},
{
"code": "<script>// javascript program to check if a number is a// triangular number using quadratic equation. // Returns true if num is triangular function isTriangular(num) { if (num < 0) return false; // Considering the equation // n*(n+1)/2 = num // The equation is : // a(n^2) + bn + c = 0\"; var c = (-2 * num); var b = 1, a = 1; var d = (b * b) - (4 * a * c); if (d < 0) return false; // Find roots of equation var root1 = (-b + Math.sqrt(d)) / (2 * a); var root2 = (-b - Math.sqrt(d)) / (2 * a); // checking if root1 is natural if (root1 > 0 && Math.floor(root1) == root1) return true; // checking if root2 is natural if (root2 > 0 && Math.floor(root2) == root2) return true; return false; } // Driver code var num = 55; if (isTriangular(num)) document.write(\"The number is\" + \" a triangular number\"); else document.write(\"The number \" + \"is NOT a triangular number\"); // This code is contributed by Rajput-Ji</script>",
"e": 12833,
"s": 11699,
"text": null
},
{
"code": null,
"e": 12842,
"s": 12833,
"text": "Output: "
},
{
"code": null,
"e": 12878,
"s": 12842,
"text": " The number is a triangular number "
},
{
"code": null,
"e": 13003,
"s": 12878,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 13013,
"s": 13003,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 13023,
"s": 13013,
"text": "Code_Mech"
},
{
"code": null,
"e": 13035,
"s": 13023,
"text": "aashish1995"
},
{
"code": null,
"e": 13042,
"s": 13035,
"text": "series"
},
{
"code": null,
"e": 13051,
"s": 13042,
"text": "triangle"
},
{
"code": null,
"e": 13069,
"s": 13051,
"text": "triangular-number"
},
{
"code": null,
"e": 13082,
"s": 13069,
"text": "Mathematical"
},
{
"code": null,
"e": 13095,
"s": 13082,
"text": "Mathematical"
},
{
"code": null,
"e": 13102,
"s": 13095,
"text": "series"
},
{
"code": null,
"e": 13200,
"s": 13102,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 13221,
"s": 13200,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 13274,
"s": 13221,
"text": "Find minimum number of coins that make a given value"
},
{
"code": null,
"e": 13311,
"s": 13274,
"text": "Minimum number of jumps to reach end"
},
{
"code": null,
"e": 13343,
"s": 13311,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 13370,
"s": 13343,
"text": "Modulo 10^9+7 (1000000007)"
},
{
"code": null,
"e": 13413,
"s": 13370,
"text": "The Knight's tour problem | Backtracking-1"
},
{
"code": null,
"e": 13456,
"s": 13413,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 13490,
"s": 13456,
"text": "Program for factorial of a number"
},
{
"code": null,
"e": 13539,
"s": 13490,
"text": "Program to find sum of elements in a given array"
}
] |
Increment a given date in JavaScript | 17 May, 2019
Given a date, the task is to increment it. To increment a date in javascript, we’re going to discuss few techniques. First few methods to know:
JavaScript getDate() methodThis method returns the day of the month (from 1 to 31) for the defined date.Syntax:Date.getDate()
Return value:It returns a number, from 1 to 31, denoting the day of the month
Date.getDate()
Return value:It returns a number, from 1 to 31, denoting the day of the month
JavaScript setDate() methodThis method sets the day of month to the date object.Syntax:Date.setDate(day)
Parameters:day:This parameter is required. It specifies the integer defining the day of a month. Values expected are 1-31 but less than 1 and greater than 31 values are used appropriately for previous and next month.Return value:It returns, representing the number of milliseconds between the date object and midnight January 1 1970.
Date.setDate(day)
Parameters:
day:This parameter is required. It specifies the integer defining the day of a month. Values expected are 1-31 but less than 1 and greater than 31 values are used appropriately for previous and next month.
Return value:It returns, representing the number of milliseconds between the date object and midnight January 1 1970.
JavaScript getTime() methodThis method returns the number of milliseconds between midnight of January 1, 1970 and the specified date.Syntax:Date.getTime()
Return value:It returns a number, representing the number of milliseconds since midnight January 1, 1970.
Date.getTime()
Return value:It returns a number, representing the number of milliseconds since midnight January 1, 1970.
JavaScript setTime() methodThis method set the date and time by adding/subtracting a defines number of milliseconds to/from midnight January 1, 1970.Syntax:Date.setTime(millisec)
Parameters:millisec:This parameter is required. It specifies the number of milliseconds to be added/subtracted, midnight January 1, 1970Return value:It returns, representing the number of milliseconds between the date object and midnight January 1 1970.
JavaScript setTime() methodThis method set the date and time by adding/subtracting a defines number of milliseconds to/from midnight January 1, 1970.Syntax:
Date.setTime(millisec)
Parameters:
millisec:This parameter is required. It specifies the number of milliseconds to be added/subtracted, midnight January 1, 1970
Return value:It returns, representing the number of milliseconds between the date object and midnight January 1 1970.
Example 1:This example increments 1 day to the 16th may by using setDate() and getDate() method.
<!DOCTYPE html><html> <head> <title> JavaScript | Incrementing a date. </title></head> <body style="text-align:center;" id="body"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 15px; font-weight: bold;"> </p> <button onclick="gfg_Run()"> Increment by 1 day </button> <p id="GFG_DOWN" style="color:green; font-size: 20px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var today = new Date(); el_up.innerHTML = "Today's date = " + today; function gfg_Run() { var tomorrow = new Date(); tomorrow.setDate(today.getDate() + 1); el_down.innerHTML = tomorrow; } </script></body> </html>
Output:
Before clicking on the button:
After clicking on the button:
Example 2:This example increments 10 day to the 16th may by using setTime() and getTime() method.
<!DOCTYPE html><html> <head> <title> JavaScript | Incrementing a date. </title></head> <body style="text-align:center;" id="body"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 15px; font-weight: bold;"> </p> <button onclick="gfg_Run()"> Increment by days </button> <p id="GFG_DOWN" style="color:green; font-size: 20px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var today = new Date(); var days = 10; el_up.innerHTML = "Today's date = " + today; function gfg_Run() { var tomorrow = new Date(); tomorrow.setTime(today.getTime() + days * 86400000); el_down.innerHTML = tomorrow; } </script></body> </html>
Output:
Before clicking on the button:
After clicking on the button:
javascript-date
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 May, 2019"
},
{
"code": null,
"e": 172,
"s": 28,
"text": "Given a date, the task is to increment it. To increment a date in javascript, we’re going to discuss few techniques. First few methods to know:"
},
{
"code": null,
"e": 376,
"s": 172,
"text": "JavaScript getDate() methodThis method returns the day of the month (from 1 to 31) for the defined date.Syntax:Date.getDate()\nReturn value:It returns a number, from 1 to 31, denoting the day of the month"
},
{
"code": null,
"e": 392,
"s": 376,
"text": "Date.getDate()\n"
},
{
"code": null,
"e": 470,
"s": 392,
"text": "Return value:It returns a number, from 1 to 31, denoting the day of the month"
},
{
"code": null,
"e": 909,
"s": 470,
"text": "JavaScript setDate() methodThis method sets the day of month to the date object.Syntax:Date.setDate(day)\nParameters:day:This parameter is required. It specifies the integer defining the day of a month. Values expected are 1-31 but less than 1 and greater than 31 values are used appropriately for previous and next month.Return value:It returns, representing the number of milliseconds between the date object and midnight January 1 1970."
},
{
"code": null,
"e": 928,
"s": 909,
"text": "Date.setDate(day)\n"
},
{
"code": null,
"e": 940,
"s": 928,
"text": "Parameters:"
},
{
"code": null,
"e": 1146,
"s": 940,
"text": "day:This parameter is required. It specifies the integer defining the day of a month. Values expected are 1-31 but less than 1 and greater than 31 values are used appropriately for previous and next month."
},
{
"code": null,
"e": 1264,
"s": 1146,
"text": "Return value:It returns, representing the number of milliseconds between the date object and midnight January 1 1970."
},
{
"code": null,
"e": 1525,
"s": 1264,
"text": "JavaScript getTime() methodThis method returns the number of milliseconds between midnight of January 1, 1970 and the specified date.Syntax:Date.getTime()\nReturn value:It returns a number, representing the number of milliseconds since midnight January 1, 1970."
},
{
"code": null,
"e": 1541,
"s": 1525,
"text": "Date.getTime()\n"
},
{
"code": null,
"e": 1647,
"s": 1541,
"text": "Return value:It returns a number, representing the number of milliseconds since midnight January 1, 1970."
},
{
"code": null,
"e": 2080,
"s": 1647,
"text": "JavaScript setTime() methodThis method set the date and time by adding/subtracting a defines number of milliseconds to/from midnight January 1, 1970.Syntax:Date.setTime(millisec)\nParameters:millisec:This parameter is required. It specifies the number of milliseconds to be added/subtracted, midnight January 1, 1970Return value:It returns, representing the number of milliseconds between the date object and midnight January 1 1970."
},
{
"code": null,
"e": 2237,
"s": 2080,
"text": "JavaScript setTime() methodThis method set the date and time by adding/subtracting a defines number of milliseconds to/from midnight January 1, 1970.Syntax:"
},
{
"code": null,
"e": 2261,
"s": 2237,
"text": "Date.setTime(millisec)\n"
},
{
"code": null,
"e": 2273,
"s": 2261,
"text": "Parameters:"
},
{
"code": null,
"e": 2399,
"s": 2273,
"text": "millisec:This parameter is required. It specifies the number of milliseconds to be added/subtracted, midnight January 1, 1970"
},
{
"code": null,
"e": 2517,
"s": 2399,
"text": "Return value:It returns, representing the number of milliseconds between the date object and midnight January 1 1970."
},
{
"code": null,
"e": 2614,
"s": 2517,
"text": "Example 1:This example increments 1 day to the 16th may by using setDate() and getDate() method."
},
{
"code": "<!DOCTYPE html><html> <head> <title> JavaScript | Incrementing a date. </title></head> <body style=\"text-align:center;\" id=\"body\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 15px; font-weight: bold;\"> </p> <button onclick=\"gfg_Run()\"> Increment by 1 day </button> <p id=\"GFG_DOWN\" style=\"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var today = new Date(); el_up.innerHTML = \"Today's date = \" + today; function gfg_Run() { var tomorrow = new Date(); tomorrow.setDate(today.getDate() + 1); el_down.innerHTML = tomorrow; } </script></body> </html>",
"e": 3523,
"s": 2614,
"text": null
},
{
"code": null,
"e": 3531,
"s": 3523,
"text": "Output:"
},
{
"code": null,
"e": 3562,
"s": 3531,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 3592,
"s": 3562,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 3690,
"s": 3592,
"text": "Example 2:This example increments 10 day to the 16th may by using setTime() and getTime() method."
},
{
"code": "<!DOCTYPE html><html> <head> <title> JavaScript | Incrementing a date. </title></head> <body style=\"text-align:center;\" id=\"body\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 15px; font-weight: bold;\"> </p> <button onclick=\"gfg_Run()\"> Increment by days </button> <p id=\"GFG_DOWN\" style=\"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var today = new Date(); var days = 10; el_up.innerHTML = \"Today's date = \" + today; function gfg_Run() { var tomorrow = new Date(); tomorrow.setTime(today.getTime() + days * 86400000); el_down.innerHTML = tomorrow; } </script></body> </html>",
"e": 4634,
"s": 3690,
"text": null
},
{
"code": null,
"e": 4642,
"s": 4634,
"text": "Output:"
},
{
"code": null,
"e": 4673,
"s": 4642,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 4703,
"s": 4673,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 4719,
"s": 4703,
"text": "javascript-date"
},
{
"code": null,
"e": 4730,
"s": 4719,
"text": "JavaScript"
},
{
"code": null,
"e": 4747,
"s": 4730,
"text": "Web Technologies"
}
] |
Liang-Barsky Algorithm | 18 Mar, 2019
The Liang-Barsky algorithm is a line clipping algorithm. This algorithm is more efficient than Cohen–Sutherland line clipping algorithm and can be extended to 3-Dimensional clipping. This algorithm is considered to be the faster parametric line-clipping algorithm. The following concepts are used in this clipping:
The parametric equation of the line.The inequalities describing the range of the clipping window which is used to determine the intersections between the line and the clip window.
The parametric equation of the line.
The inequalities describing the range of the clipping window which is used to determine the intersections between the line and the clip window.
The parametric equation of a line can be given by,
X = x1 + t(x2-x1)
Y = y1 + t(y2-y1)
Where, t is between 0 and 1.
Then, writing the point-clipping conditions in the parametric form:
xwmin <= x1 + t(x2-x1) <= xwmax
ywmin <= y1 + t(y2-y1) <= ywmax
The above 4 inequalities can be expressed as,
tpk <= qk
Where k = 1, 2, 3, 4 (correspond to the left, right, bottom, and top boundaries, respectively).
The p and q are defined as,
p1 = -(x2-x1), q1 = x1 - xwmin (Left Boundary)
p2 = (x2-x1), q2 = xwmax - x1 (Right Boundary)
p3 = -(y2-y1), q3 = y1 - ywmin (Bottom Boundary)
p4 = (y2-y1), q4 = ywmax - y1 (Top Boundary)
When the line is parallel to a view window boundary, the p value for that boundary is zero.When pk < 0, as t increase line goes from the outside to inside (entering).When pk > 0, line goes from inside to outside (exiting).When pk = 0 and qk < 0 then line is trivially invisible because it is outside view window.When pk = 0 and qk > 0 then the line is inside the corresponding window boundary.
Using the following conditions, the position of line can be determined:
Parameters t1 and t2 can be calculated that define the part of line that lies within the clip rectangle.When,
pk < 0, maximum(0, qk/pk) is taken.pk > 0, minimum(1, qk/pk) is taken.
pk < 0, maximum(0, qk/pk) is taken.
pk > 0, minimum(1, qk/pk) is taken.
If t1 > t2, the line is completely outside the clip window and it can be rejected. Otherwise, the endpoints of the clipped line are calculated from the two values of parameter t.
Algorithm –
Set tmin=0, tmax=1.Calculate the values of t (t(left), t(right), t(top), t(bottom)),(i) If t < tmin ignore that and move to the next edge.(ii) else separate the t values as entering or exiting values using the inner product.(iii) If t is entering value, set tmin = t; if t is existing value, set tmax = t.If tmin < tmax, draw a line from (x1 + tmin(x2-x1), y1 + tmin(y2-y1)) to (x1 + tmax(x2-x1), y1 + tmax(y2-y1))If the line crosses over the window, (x1 + tmin(x2-x1), y1 + tmin(y2-y1)) and (x1 + tmax(x2-x1), y1 + tmax(y2-y1)) are the intersection point of line and edge.
Set tmin=0, tmax=1.
Calculate the values of t (t(left), t(right), t(top), t(bottom)),(i) If t < tmin ignore that and move to the next edge.(ii) else separate the t values as entering or exiting values using the inner product.(iii) If t is entering value, set tmin = t; if t is existing value, set tmax = t.
If tmin < tmax, draw a line from (x1 + tmin(x2-x1), y1 + tmin(y2-y1)) to (x1 + tmax(x2-x1), y1 + tmax(y2-y1))
If the line crosses over the window, (x1 + tmin(x2-x1), y1 + tmin(y2-y1)) and (x1 + tmax(x2-x1), y1 + tmax(y2-y1)) are the intersection point of line and edge.
This algorithm is presented in the following code. Line intersection parameters are initialised to the values t1 = 0 and t2 = 1.
#include"graphics.h"#define ROUND(a) ((int)(a+0.5))int clipTest (float p,float q, float * tl, float * t2){float r ;int retVal = TRUE; //line entry pointif (p < 0.0) { r = q /p ; // line portion is outside the clipping edge if ( r > *t2 ) retVal = FALSE; else if (r > *t1 ) *tl = r; } else //line leaving pointif (p>0.0) { r = q/p ; // line portion is outside if ( r<*t1 ) retVal = FALSE; else i f (r<*t2) *t2 = r;} // p = 0, so line is parallel to this clipping edge else // Line is outside clipping edge if (q<0.0) retVal = FALSE; return ( retVal ) ;} void clipLine (dcPt winMin, dcPt winMax, wcPt2 pl , wcPt2 p2) { float t1 = 0.0, t2 = 1.0, dx = p2.x-p1.x, dy; // inside test wrt left edgeif(clipTest (-dx, p1.x - winMin.x, &t1, &t2)) // inside test wrt right edge if(clipTest (dx, winMax.x - p1.x, &t1, &t2)) { dy = p2.y - p1.y; // inside test wrt bottom edge if(clipTest (-dy, p1.y - winMin.y, &t1, &t2)) // inside test wrt top edge if(clipTest (dy, winMax.y - p1.y, &t1, &t2)) { if(t2 < 1.0) { p2.x = p1.x + t2*dx; p2.y = p1.y + t2*dy; } if(t1 > 0.0) { p1.x += t1*dx; p1.y += t1*dy; } lineDDA ( ROUND(p1.x), ROUND(p1.y), ROUND(p2.x), ROUND(p2.y) ); }} }
Reference: Computer Graphics by Donald Hearn, M.Pauline Baker
Storm_shadow
computer-graphics
Misc
Misc
Misc
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n18 Mar, 2019"
},
{
"code": null,
"e": 367,
"s": 52,
"text": "The Liang-Barsky algorithm is a line clipping algorithm. This algorithm is more efficient than Cohen–Sutherland line clipping algorithm and can be extended to 3-Dimensional clipping. This algorithm is considered to be the faster parametric line-clipping algorithm. The following concepts are used in this clipping:"
},
{
"code": null,
"e": 547,
"s": 367,
"text": "The parametric equation of the line.The inequalities describing the range of the clipping window which is used to determine the intersections between the line and the clip window."
},
{
"code": null,
"e": 584,
"s": 547,
"text": "The parametric equation of the line."
},
{
"code": null,
"e": 728,
"s": 584,
"text": "The inequalities describing the range of the clipping window which is used to determine the intersections between the line and the clip window."
},
{
"code": null,
"e": 779,
"s": 728,
"text": "The parametric equation of a line can be given by,"
},
{
"code": null,
"e": 815,
"s": 779,
"text": "X = x1 + t(x2-x1)\nY = y1 + t(y2-y1)"
},
{
"code": null,
"e": 844,
"s": 815,
"text": "Where, t is between 0 and 1."
},
{
"code": null,
"e": 912,
"s": 844,
"text": "Then, writing the point-clipping conditions in the parametric form:"
},
{
"code": null,
"e": 977,
"s": 912,
"text": "xwmin <= x1 + t(x2-x1) <= xwmax\nywmin <= y1 + t(y2-y1) <= ywmax "
},
{
"code": null,
"e": 1023,
"s": 977,
"text": "The above 4 inequalities can be expressed as,"
},
{
"code": null,
"e": 1034,
"s": 1023,
"text": "tpk <= qk "
},
{
"code": null,
"e": 1130,
"s": 1034,
"text": "Where k = 1, 2, 3, 4 (correspond to the left, right, bottom, and top boundaries, respectively)."
},
{
"code": null,
"e": 1158,
"s": 1130,
"text": "The p and q are defined as,"
},
{
"code": null,
"e": 1356,
"s": 1158,
"text": "p1 = -(x2-x1), q1 = x1 - xwmin (Left Boundary) \np2 = (x2-x1), q2 = xwmax - x1 (Right Boundary)\np3 = -(y2-y1), q3 = y1 - ywmin (Bottom Boundary) \np4 = (y2-y1), q4 = ywmax - y1 (Top Boundary) "
},
{
"code": null,
"e": 1750,
"s": 1356,
"text": "When the line is parallel to a view window boundary, the p value for that boundary is zero.When pk < 0, as t increase line goes from the outside to inside (entering).When pk > 0, line goes from inside to outside (exiting).When pk = 0 and qk < 0 then line is trivially invisible because it is outside view window.When pk = 0 and qk > 0 then the line is inside the corresponding window boundary."
},
{
"code": null,
"e": 1822,
"s": 1750,
"text": "Using the following conditions, the position of line can be determined:"
},
{
"code": null,
"e": 1932,
"s": 1822,
"text": "Parameters t1 and t2 can be calculated that define the part of line that lies within the clip rectangle.When,"
},
{
"code": null,
"e": 2003,
"s": 1932,
"text": "pk < 0, maximum(0, qk/pk) is taken.pk > 0, minimum(1, qk/pk) is taken."
},
{
"code": null,
"e": 2039,
"s": 2003,
"text": "pk < 0, maximum(0, qk/pk) is taken."
},
{
"code": null,
"e": 2075,
"s": 2039,
"text": "pk > 0, minimum(1, qk/pk) is taken."
},
{
"code": null,
"e": 2254,
"s": 2075,
"text": "If t1 > t2, the line is completely outside the clip window and it can be rejected. Otherwise, the endpoints of the clipped line are calculated from the two values of parameter t."
},
{
"code": null,
"e": 2266,
"s": 2254,
"text": "Algorithm –"
},
{
"code": null,
"e": 2840,
"s": 2266,
"text": "Set tmin=0, tmax=1.Calculate the values of t (t(left), t(right), t(top), t(bottom)),(i) If t < tmin ignore that and move to the next edge.(ii) else separate the t values as entering or exiting values using the inner product.(iii) If t is entering value, set tmin = t; if t is existing value, set tmax = t.If tmin < tmax, draw a line from (x1 + tmin(x2-x1), y1 + tmin(y2-y1)) to (x1 + tmax(x2-x1), y1 + tmax(y2-y1))If the line crosses over the window, (x1 + tmin(x2-x1), y1 + tmin(y2-y1)) and (x1 + tmax(x2-x1), y1 + tmax(y2-y1)) are the intersection point of line and edge."
},
{
"code": null,
"e": 2860,
"s": 2840,
"text": "Set tmin=0, tmax=1."
},
{
"code": null,
"e": 3147,
"s": 2860,
"text": "Calculate the values of t (t(left), t(right), t(top), t(bottom)),(i) If t < tmin ignore that and move to the next edge.(ii) else separate the t values as entering or exiting values using the inner product.(iii) If t is entering value, set tmin = t; if t is existing value, set tmax = t."
},
{
"code": null,
"e": 3257,
"s": 3147,
"text": "If tmin < tmax, draw a line from (x1 + tmin(x2-x1), y1 + tmin(y2-y1)) to (x1 + tmax(x2-x1), y1 + tmax(y2-y1))"
},
{
"code": null,
"e": 3417,
"s": 3257,
"text": "If the line crosses over the window, (x1 + tmin(x2-x1), y1 + tmin(y2-y1)) and (x1 + tmax(x2-x1), y1 + tmax(y2-y1)) are the intersection point of line and edge."
},
{
"code": null,
"e": 3546,
"s": 3417,
"text": "This algorithm is presented in the following code. Line intersection parameters are initialised to the values t1 = 0 and t2 = 1."
},
{
"code": "#include\"graphics.h\"#define ROUND(a) ((int)(a+0.5))int clipTest (float p,float q, float * tl, float * t2){float r ;int retVal = TRUE; //line entry pointif (p < 0.0) { r = q /p ; // line portion is outside the clipping edge if ( r > *t2 ) retVal = FALSE; else if (r > *t1 ) *tl = r; } else //line leaving pointif (p>0.0) { r = q/p ; // line portion is outside if ( r<*t1 ) retVal = FALSE; else i f (r<*t2) *t2 = r;} // p = 0, so line is parallel to this clipping edge else // Line is outside clipping edge if (q<0.0) retVal = FALSE; return ( retVal ) ;} void clipLine (dcPt winMin, dcPt winMax, wcPt2 pl , wcPt2 p2) { float t1 = 0.0, t2 = 1.0, dx = p2.x-p1.x, dy; // inside test wrt left edgeif(clipTest (-dx, p1.x - winMin.x, &t1, &t2)) // inside test wrt right edge if(clipTest (dx, winMax.x - p1.x, &t1, &t2)) { dy = p2.y - p1.y; // inside test wrt bottom edge if(clipTest (-dy, p1.y - winMin.y, &t1, &t2)) // inside test wrt top edge if(clipTest (dy, winMax.y - p1.y, &t1, &t2)) { if(t2 < 1.0) { p2.x = p1.x + t2*dx; p2.y = p1.y + t2*dy; } if(t1 > 0.0) { p1.x += t1*dx; p1.y += t1*dy; } lineDDA ( ROUND(p1.x), ROUND(p1.y), ROUND(p2.x), ROUND(p2.y) ); }} } ",
"e": 5118,
"s": 3546,
"text": null
},
{
"code": null,
"e": 5180,
"s": 5118,
"text": "Reference: Computer Graphics by Donald Hearn, M.Pauline Baker"
},
{
"code": null,
"e": 5193,
"s": 5180,
"text": "Storm_shadow"
},
{
"code": null,
"e": 5211,
"s": 5193,
"text": "computer-graphics"
},
{
"code": null,
"e": 5216,
"s": 5211,
"text": "Misc"
},
{
"code": null,
"e": 5221,
"s": 5216,
"text": "Misc"
},
{
"code": null,
"e": 5226,
"s": 5221,
"text": "Misc"
}
] |
Are static local variables allowed in Java? | 11 May, 2020
Unlike C/C++, static local variables are not allowed in Java. For example, following Java program fails in compilation with error “Static local variables are not allowed”
class Test { public static void main(String args[]) { System.out.println(fun()); } static int fun() { static int x= 10; //Error: Static local variables are not allowed return x--; }}
In Java, a static variable is a class variable (for whole class). So if we have static local variable (a variable with scope limited to function), it violates the purpose of static. Hence compiler does not allow static local variable.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
KarthickManickam
java-basics
Java-Output
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n11 May, 2020"
},
{
"code": null,
"e": 223,
"s": 52,
"text": "Unlike C/C++, static local variables are not allowed in Java. For example, following Java program fails in compilation with error “Static local variables are not allowed”"
},
{
"code": "class Test { public static void main(String args[]) { System.out.println(fun()); } static int fun() { static int x= 10; //Error: Static local variables are not allowed return x--; }} ",
"e": 433,
"s": 223,
"text": null
},
{
"code": null,
"e": 668,
"s": 433,
"text": "In Java, a static variable is a class variable (for whole class). So if we have static local variable (a variable with scope limited to function), it violates the purpose of static. Hence compiler does not allow static local variable."
},
{
"code": null,
"e": 793,
"s": 668,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 810,
"s": 793,
"text": "KarthickManickam"
},
{
"code": null,
"e": 822,
"s": 810,
"text": "java-basics"
},
{
"code": null,
"e": 834,
"s": 822,
"text": "Java-Output"
},
{
"code": null,
"e": 839,
"s": 834,
"text": "Java"
},
{
"code": null,
"e": 844,
"s": 839,
"text": "Java"
}
] |
How to bind the Escape key to close a window in Tkinter? | Tkinter Events are very useful for making an application interactive and functional. It provides a way to interact with the internal functionality of the application and helps them to rise whenever we perform a Click or Keypress event.
In order to schedule the events in tkinter, we generally use the bind('Button', callback) method. We can bind any key to perform certain tasks or events in the application. To bind the Esc key such that it will close the application window, we have to pass the Key and a callback event as the parameter in the bind(key, callback) method.
# Import the required libraries
from tkinter import *
from tkinter import ttk
# Create an instance of tkinter frame
win = Tk()
# Set the size of the tkinter window
win.geometry("700x350")
# Define the style for combobox widget
style = ttk.Style()
style.theme_use('xpnative')
# Define an event to close the window
def close_win(e):
win.destroy()
# Add a label widget
label = ttk.Label(win, text="Eat, Sleep, Code and Repeat", font=('Times New Roman italic', 18), background="black", foreground="white")
label.place(relx=.5, rely=.5, anchor=CENTER)
ttk.Label(win, text="Now Press the ESC Key to close this window", font=('Aerial 11')).pack(pady=10)
# Bind the ESC key with the callback function
win.bind('<Escape>', lambda e: close_win(e))
win.mainloop()
Running the above code will display a window which can be closed immediately by pressing the "Esc" Key.
Now press the <Esc> key to close the window. | [
{
"code": null,
"e": 1423,
"s": 1187,
"text": "Tkinter Events are very useful for making an application interactive and functional. It provides a way to interact with the internal functionality of the application and helps them to rise whenever we perform a Click or Keypress event."
},
{
"code": null,
"e": 1761,
"s": 1423,
"text": "In order to schedule the events in tkinter, we generally use the bind('Button', callback) method. We can bind any key to perform certain tasks or events in the application. To bind the Esc key such that it will close the application window, we have to pass the Key and a callback event as the parameter in the bind(key, callback) method."
},
{
"code": null,
"e": 2523,
"s": 1761,
"text": "# Import the required libraries\nfrom tkinter import *\nfrom tkinter import ttk\n\n# Create an instance of tkinter frame\nwin = Tk()\n\n# Set the size of the tkinter window\nwin.geometry(\"700x350\")\n\n# Define the style for combobox widget\nstyle = ttk.Style()\nstyle.theme_use('xpnative')\n\n# Define an event to close the window\ndef close_win(e):\n win.destroy()\n# Add a label widget\nlabel = ttk.Label(win, text=\"Eat, Sleep, Code and Repeat\", font=('Times New Roman italic', 18), background=\"black\", foreground=\"white\")\nlabel.place(relx=.5, rely=.5, anchor=CENTER)\nttk.Label(win, text=\"Now Press the ESC Key to close this window\", font=('Aerial 11')).pack(pady=10)\n\n# Bind the ESC key with the callback function\nwin.bind('<Escape>', lambda e: close_win(e))\n\nwin.mainloop()"
},
{
"code": null,
"e": 2627,
"s": 2523,
"text": "Running the above code will display a window which can be closed immediately by pressing the \"Esc\" Key."
},
{
"code": null,
"e": 2672,
"s": 2627,
"text": "Now press the <Esc> key to close the window."
}
] |
Python Program to Concatenate Two Dictionaries Into One | When it is required to concatenate two dictionaries into a single entity, the ‘update’ method can be used.
A dictionary is a ‘key-value’ pair.
Below is a demonstration for the same −
Live Demo
my_dict_1 = {'J':12,'W':22}
my_dict_2 = {'M':67}
print("The first dictionary is :")
print(my_dict_1)
print("The second dictionary is :")
print(my_dict_2)
my_dict_1.update(my_dict_2)
print("The concatenated dictionary is :")
print(my_dict_1)
The first dictionary is :
{'J': 12, 'W': 22}
The second dictionary is :
{'M': 67}
The concatenated dictionary is :
{'J': 12, 'W': 22, 'M': 67}
Two dictionaries are defined, and are displayed on the console.
The ‘update’ method is called on the first dictionary by passing second dictionary as parameter.
This would help concatenate the dictionary.
This is displayed on the console. | [
{
"code": null,
"e": 1294,
"s": 1187,
"text": "When it is required to concatenate two dictionaries into a single entity, the ‘update’ method can be used."
},
{
"code": null,
"e": 1330,
"s": 1294,
"text": "A dictionary is a ‘key-value’ pair."
},
{
"code": null,
"e": 1370,
"s": 1330,
"text": "Below is a demonstration for the same −"
},
{
"code": null,
"e": 1381,
"s": 1370,
"text": " Live Demo"
},
{
"code": null,
"e": 1622,
"s": 1381,
"text": "my_dict_1 = {'J':12,'W':22}\nmy_dict_2 = {'M':67}\nprint(\"The first dictionary is :\")\nprint(my_dict_1)\nprint(\"The second dictionary is :\")\nprint(my_dict_2)\nmy_dict_1.update(my_dict_2)\nprint(\"The concatenated dictionary is :\")\nprint(my_dict_1)"
},
{
"code": null,
"e": 1765,
"s": 1622,
"text": "The first dictionary is :\n{'J': 12, 'W': 22}\nThe second dictionary is :\n{'M': 67}\nThe concatenated dictionary is :\n{'J': 12, 'W': 22, 'M': 67}"
},
{
"code": null,
"e": 1830,
"s": 1765,
"text": "Two dictionaries are defined, and are displayed on the console. "
},
{
"code": null,
"e": 1928,
"s": 1830,
"text": "The ‘update’ method is called on the first dictionary by passing second dictionary as parameter. "
},
{
"code": null,
"e": 1973,
"s": 1928,
"text": "This would help concatenate the dictionary. "
},
{
"code": null,
"e": 2007,
"s": 1973,
"text": "This is displayed on the console."
}
] |
throw and throws in Java | 26 Jan, 2021
throw
The throw keyword in Java is used to explicitly throw an exception from a method or any block of code. We can throw either checked or unchecked exception. The throw keyword is mainly used to throw custom exceptions.
Syntax:
throw Instance
Example:
throw new ArithmeticException("/ by zero");
But this exception i.e, Instance must be of type Throwable or a subclass of Throwable. For example Exception is a sub-class of Throwable and user defined exceptions typically extend Exception class. Unlike C++, data types such as int, char, floats or non-throwable classes cannot be used as exceptions.
The flow of execution of the program stops immediately after the throw statement is executed and the nearest enclosing try block is checked to see if it has a catch statement that matches the type of exception. If it finds a match, controlled is transferred to that statement otherwise next enclosing try block is checked and so on. If no matching catch is found then the default exception handler will halt the program.
Java
// Java program that demonstrates the use of throwclass ThrowExcep{ static void fun() { try { throw new NullPointerException("demo"); } catch(NullPointerException e) { System.out.println("Caught inside fun()."); throw e; // rethrowing the exception } } public static void main(String args[]) { try { fun(); } catch(NullPointerException e) { System.out.println("Caught in main."); } }}
Output:
Caught inside fun().
Caught in main.
Another Example:
Java
// Java program that demonstrates the use of throwclass Test{ public static void main(String[] args) { System.out.println(1/0); }}
Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
throws
throws is a keyword in Java which is used in the signature of method to indicate that this method might throw one of the listed type exceptions. The caller to these methods has to handle the exception using a try-catch block.
Syntax:
type method_name(parameters) throws exception_list
exception_list is a comma separated list of all the
exceptions which a method might throw.
In a program, if there is a chance of raising an exception then compiler always warn us about it and compulsorily we should handle that checked exception, Otherwise we will get compile time error saying unreported exception XXX must be caught or declared to be thrown. To prevent this compile time error we can handle the exception in two ways:
By using try catchBy using throws keyword
By using try catch
By using throws keyword
We can use throws keyword to delegate the responsibility of exception handling to the caller (It may be a method or JVM) then caller method is responsible to handle that exception.
Java
// Java program to illustrate error in case// of unhandled exceptionclass tst{ public static void main(String[] args) { Thread.sleep(10000); System.out.println("Hello Geeks"); }}
Output:
error: unreported exception InterruptedException; must be caught or declared to be thrown
Explanation: In the above program, we are getting compile time error because there is a chance of exception if the main thread is going to sleep, other threads get the chance to execute main() method which will cause InterruptedException.
Java
// Java program to illustrate throwsclass tst{ public static void main(String[] args)throws InterruptedException { Thread.sleep(10000); System.out.println("Hello Geeks"); }}
Output:
Hello Geeks
Explanation: In the above program, by using throws keyword we handled the InterruptedException and we will get the output as Hello Geeks
Another Example:
Java
// Java program to demonstrate working of throwsclass ThrowsExecp{ static void fun() throws IllegalAccessException { System.out.println("Inside fun(). "); throw new IllegalAccessException("demo"); } public static void main(String args[]) { try { fun(); } catch(IllegalAccessException e) { System.out.println("caught in main."); } }}
Output:
Inside fun().
caught in main.
Important points to remember about throws keyword:
throws keyword is required only for checked exception and usage of throws keyword for unchecked exception is meaningless.
throws keyword is required only to convince compiler and usage of throws keyword does not prevent abnormal termination of program.
By the help of throws keyword we can provide information to the caller of the method about the exception.
Reference: Java – The complete Reference by Herbert Schildt
This article is contributed by Pratik Agarwal and Bishal Dubey. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
arnab_nath
aadarsh baid
Exception Handling
Java-Exception Handling
Java-Exceptions
Java
School Programming
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Split() String method in Java with examples
Arrays.sort() in Java with examples
Reverse a string in Java
How to iterate any Map in Java
Stream In Java
Python Dictionary
Reverse a string in Java
Arrays in C/C++
Introduction To PYTHON
Inheritance in C++ | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n26 Jan, 2021"
},
{
"code": null,
"e": 58,
"s": 52,
"text": "throw"
},
{
"code": null,
"e": 275,
"s": 58,
"text": "The throw keyword in Java is used to explicitly throw an exception from a method or any block of code. We can throw either checked or unchecked exception. The throw keyword is mainly used to throw custom exceptions. "
},
{
"code": null,
"e": 284,
"s": 275,
"text": "Syntax: "
},
{
"code": null,
"e": 352,
"s": 284,
"text": "throw Instance\nExample:\nthrow new ArithmeticException(\"/ by zero\");"
},
{
"code": null,
"e": 655,
"s": 352,
"text": "But this exception i.e, Instance must be of type Throwable or a subclass of Throwable. For example Exception is a sub-class of Throwable and user defined exceptions typically extend Exception class. Unlike C++, data types such as int, char, floats or non-throwable classes cannot be used as exceptions."
},
{
"code": null,
"e": 1077,
"s": 655,
"text": "The flow of execution of the program stops immediately after the throw statement is executed and the nearest enclosing try block is checked to see if it has a catch statement that matches the type of exception. If it finds a match, controlled is transferred to that statement otherwise next enclosing try block is checked and so on. If no matching catch is found then the default exception handler will halt the program. "
},
{
"code": null,
"e": 1082,
"s": 1077,
"text": "Java"
},
{
"code": "// Java program that demonstrates the use of throwclass ThrowExcep{ static void fun() { try { throw new NullPointerException(\"demo\"); } catch(NullPointerException e) { System.out.println(\"Caught inside fun().\"); throw e; // rethrowing the exception } } public static void main(String args[]) { try { fun(); } catch(NullPointerException e) { System.out.println(\"Caught in main.\"); } }}",
"e": 1625,
"s": 1082,
"text": null
},
{
"code": null,
"e": 1634,
"s": 1625,
"text": "Output: "
},
{
"code": null,
"e": 1671,
"s": 1634,
"text": "Caught inside fun().\nCaught in main."
},
{
"code": null,
"e": 1689,
"s": 1671,
"text": "Another Example: "
},
{
"code": null,
"e": 1694,
"s": 1689,
"text": "Java"
},
{
"code": "// Java program that demonstrates the use of throwclass Test{ public static void main(String[] args) { System.out.println(1/0); }}",
"e": 1841,
"s": 1694,
"text": null
},
{
"code": null,
"e": 1850,
"s": 1841,
"text": "Output: "
},
{
"code": null,
"e": 1918,
"s": 1850,
"text": "Exception in thread \"main\" java.lang.ArithmeticException: / by zero"
},
{
"code": null,
"e": 1925,
"s": 1918,
"text": "throws"
},
{
"code": null,
"e": 2152,
"s": 1925,
"text": "throws is a keyword in Java which is used in the signature of method to indicate that this method might throw one of the listed type exceptions. The caller to these methods has to handle the exception using a try-catch block. "
},
{
"code": null,
"e": 2162,
"s": 2152,
"text": "Syntax: "
},
{
"code": null,
"e": 2305,
"s": 2162,
"text": "type method_name(parameters) throws exception_list\nexception_list is a comma separated list of all the \nexceptions which a method might throw."
},
{
"code": null,
"e": 2651,
"s": 2305,
"text": "In a program, if there is a chance of raising an exception then compiler always warn us about it and compulsorily we should handle that checked exception, Otherwise we will get compile time error saying unreported exception XXX must be caught or declared to be thrown. To prevent this compile time error we can handle the exception in two ways: "
},
{
"code": null,
"e": 2693,
"s": 2651,
"text": "By using try catchBy using throws keyword"
},
{
"code": null,
"e": 2712,
"s": 2693,
"text": "By using try catch"
},
{
"code": null,
"e": 2736,
"s": 2712,
"text": "By using throws keyword"
},
{
"code": null,
"e": 2919,
"s": 2736,
"text": "We can use throws keyword to delegate the responsibility of exception handling to the caller (It may be a method or JVM) then caller method is responsible to handle that exception. "
},
{
"code": null,
"e": 2924,
"s": 2919,
"text": "Java"
},
{
"code": "// Java program to illustrate error in case// of unhandled exceptionclass tst{ public static void main(String[] args) { Thread.sleep(10000); System.out.println(\"Hello Geeks\"); }}",
"e": 3126,
"s": 2924,
"text": null
},
{
"code": null,
"e": 3135,
"s": 3126,
"text": "Output: "
},
{
"code": null,
"e": 3225,
"s": 3135,
"text": "error: unreported exception InterruptedException; must be caught or declared to be thrown"
},
{
"code": null,
"e": 3465,
"s": 3225,
"text": "Explanation: In the above program, we are getting compile time error because there is a chance of exception if the main thread is going to sleep, other threads get the chance to execute main() method which will cause InterruptedException. "
},
{
"code": null,
"e": 3470,
"s": 3465,
"text": "Java"
},
{
"code": "// Java program to illustrate throwsclass tst{ public static void main(String[] args)throws InterruptedException { Thread.sleep(10000); System.out.println(\"Hello Geeks\"); }}",
"e": 3667,
"s": 3470,
"text": null
},
{
"code": null,
"e": 3676,
"s": 3667,
"text": "Output: "
},
{
"code": null,
"e": 3688,
"s": 3676,
"text": "Hello Geeks"
},
{
"code": null,
"e": 3825,
"s": 3688,
"text": "Explanation: In the above program, by using throws keyword we handled the InterruptedException and we will get the output as Hello Geeks"
},
{
"code": null,
"e": 3844,
"s": 3825,
"text": "Another Example: "
},
{
"code": null,
"e": 3849,
"s": 3844,
"text": "Java"
},
{
"code": "// Java program to demonstrate working of throwsclass ThrowsExecp{ static void fun() throws IllegalAccessException { System.out.println(\"Inside fun(). \"); throw new IllegalAccessException(\"demo\"); } public static void main(String args[]) { try { fun(); } catch(IllegalAccessException e) { System.out.println(\"caught in main.\"); } }}",
"e": 4278,
"s": 3849,
"text": null
},
{
"code": null,
"e": 4287,
"s": 4278,
"text": "Output: "
},
{
"code": null,
"e": 4317,
"s": 4287,
"text": "Inside fun().\ncaught in main."
},
{
"code": null,
"e": 4369,
"s": 4317,
"text": "Important points to remember about throws keyword: "
},
{
"code": null,
"e": 4491,
"s": 4369,
"text": "throws keyword is required only for checked exception and usage of throws keyword for unchecked exception is meaningless."
},
{
"code": null,
"e": 4622,
"s": 4491,
"text": "throws keyword is required only to convince compiler and usage of throws keyword does not prevent abnormal termination of program."
},
{
"code": null,
"e": 4728,
"s": 4622,
"text": "By the help of throws keyword we can provide information to the caller of the method about the exception."
},
{
"code": null,
"e": 4788,
"s": 4728,
"text": "Reference: Java – The complete Reference by Herbert Schildt"
},
{
"code": null,
"e": 5232,
"s": 4788,
"text": "This article is contributed by Pratik Agarwal and Bishal Dubey. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 5243,
"s": 5232,
"text": "arnab_nath"
},
{
"code": null,
"e": 5256,
"s": 5243,
"text": "aadarsh baid"
},
{
"code": null,
"e": 5275,
"s": 5256,
"text": "Exception Handling"
},
{
"code": null,
"e": 5299,
"s": 5275,
"text": "Java-Exception Handling"
},
{
"code": null,
"e": 5315,
"s": 5299,
"text": "Java-Exceptions"
},
{
"code": null,
"e": 5320,
"s": 5315,
"text": "Java"
},
{
"code": null,
"e": 5339,
"s": 5320,
"text": "School Programming"
},
{
"code": null,
"e": 5344,
"s": 5339,
"text": "Java"
},
{
"code": null,
"e": 5442,
"s": 5344,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5486,
"s": 5442,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 5522,
"s": 5486,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 5547,
"s": 5522,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 5578,
"s": 5547,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 5593,
"s": 5578,
"text": "Stream In Java"
},
{
"code": null,
"e": 5611,
"s": 5593,
"text": "Python Dictionary"
},
{
"code": null,
"e": 5636,
"s": 5611,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 5652,
"s": 5636,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 5675,
"s": 5652,
"text": "Introduction To PYTHON"
}
] |
Overview of Benchmark Testing in Golang | 25 Aug, 2020
In automation testing, most of the frameworks support only one among functionality testing and benchmark testing. But the Golang testing package provides many functionalities for a different type of testing including benchmark testing.
B is a type(struct) passed to Benchmark functions to manage benchmark timing and to specify the number of iterations to run. Basically benchmark test suite of the testing package gives the benchmark reports likes time consumed, number of iteration/request(i.e. execution of function) of the tested function.
Syntax:
func BenchmarkXxx(*testing.B)
All of the benchmark function is executed by go test command. BenchmarkResult contains the results of a benchmark run.
type BenchmarkResult struct {
N int // The number of iterations.
T time.Duration // The total time taken.
Bytes int64 // Bytes processed in one iteration.
MemAllocs uint64 // The total number of memory allocations; added in Go 1.1
MemBytes uint64 // The total number of bytes allocated; added in Go 1.1
// Extra records additional metrics reported by ReportMetric.
Extra map[string]float64 // Go 1.13
}
Example:
File: main.go
Go
package main // function which return "geeks"func ReturnGeeks() string{ return "geeks";} // main function of packagefunc main() { ReturnGeeks()}
Test file: pkg_test.go
Go
package main import ( "testing") // function to Benchmark ReturnGeeks()func BenchmarkGeeks(b *testing.B) { for i := 0; i < b.N; i++ { ReturnGeeks() }}
Command:
go test -bench=.
where -bench=. is flag need to run the default benchmark test. You can manipulate different flags while testing.
Output:
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Parse JSON in Golang?
Constants- Go Language
Go Variables
Loops in Go Language
Time Durations in Golang
Structures in Golang
Strings in Golang
How to iterate over an Array using for loop in Golang?
time.Parse() Function in Golang With Examples
Golang | Goroutine vs Thread | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n25 Aug, 2020"
},
{
"code": null,
"e": 264,
"s": 28,
"text": "In automation testing, most of the frameworks support only one among functionality testing and benchmark testing. But the Golang testing package provides many functionalities for a different type of testing including benchmark testing."
},
{
"code": null,
"e": 572,
"s": 264,
"text": "B is a type(struct) passed to Benchmark functions to manage benchmark timing and to specify the number of iterations to run. Basically benchmark test suite of the testing package gives the benchmark reports likes time consumed, number of iteration/request(i.e. execution of function) of the tested function."
},
{
"code": null,
"e": 580,
"s": 572,
"text": "Syntax:"
},
{
"code": null,
"e": 611,
"s": 580,
"text": "func BenchmarkXxx(*testing.B)\n"
},
{
"code": null,
"e": 730,
"s": 611,
"text": "All of the benchmark function is executed by go test command. BenchmarkResult contains the results of a benchmark run."
},
{
"code": null,
"e": 1216,
"s": 730,
"text": "type BenchmarkResult struct {\n N int // The number of iterations.\n T time.Duration // The total time taken.\n Bytes int64 // Bytes processed in one iteration.\n MemAllocs uint64 // The total number of memory allocations; added in Go 1.1\n MemBytes uint64 // The total number of bytes allocated; added in Go 1.1\n\n // Extra records additional metrics reported by ReportMetric.\n Extra map[string]float64 // Go 1.13\n}\n"
},
{
"code": null,
"e": 1225,
"s": 1216,
"text": "Example:"
},
{
"code": null,
"e": 1239,
"s": 1225,
"text": "File: main.go"
},
{
"code": null,
"e": 1242,
"s": 1239,
"text": "Go"
},
{
"code": "package main // function which return \"geeks\"func ReturnGeeks() string{ return \"geeks\";} // main function of packagefunc main() { ReturnGeeks()}",
"e": 1395,
"s": 1242,
"text": null
},
{
"code": null,
"e": 1418,
"s": 1395,
"text": "Test file: pkg_test.go"
},
{
"code": null,
"e": 1421,
"s": 1418,
"text": "Go"
},
{
"code": "package main import ( \"testing\") // function to Benchmark ReturnGeeks()func BenchmarkGeeks(b *testing.B) { for i := 0; i < b.N; i++ { ReturnGeeks() }}",
"e": 1590,
"s": 1421,
"text": null
},
{
"code": null,
"e": 1600,
"s": 1590,
"text": "Command: "
},
{
"code": null,
"e": 1618,
"s": 1600,
"text": "go test -bench=.\n"
},
{
"code": null,
"e": 1731,
"s": 1618,
"text": "where -bench=. is flag need to run the default benchmark test. You can manipulate different flags while testing."
},
{
"code": null,
"e": 1739,
"s": 1731,
"text": "Output:"
},
{
"code": null,
"e": 1751,
"s": 1739,
"text": "Go Language"
},
{
"code": null,
"e": 1849,
"s": 1751,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1878,
"s": 1849,
"text": "How to Parse JSON in Golang?"
},
{
"code": null,
"e": 1901,
"s": 1878,
"text": "Constants- Go Language"
},
{
"code": null,
"e": 1914,
"s": 1901,
"text": "Go Variables"
},
{
"code": null,
"e": 1935,
"s": 1914,
"text": "Loops in Go Language"
},
{
"code": null,
"e": 1960,
"s": 1935,
"text": "Time Durations in Golang"
},
{
"code": null,
"e": 1981,
"s": 1960,
"text": "Structures in Golang"
},
{
"code": null,
"e": 1999,
"s": 1981,
"text": "Strings in Golang"
},
{
"code": null,
"e": 2054,
"s": 1999,
"text": "How to iterate over an Array using for loop in Golang?"
},
{
"code": null,
"e": 2100,
"s": 2054,
"text": "time.Parse() Function in Golang With Examples"
}
] |
HTML | DOM Input Radio checked Property | 17 Oct, 2019
The DOM Input Radio checked Property in HTML DOM is used to set or return the checked state of an Input Radio Button. This Property is used to reflect the HTML checked attribute.
Syntax:
It returns the checked property.radioObject.checked
radioObject.checked
It is used to set the checked property:radioObject.checked = true|false
radioObject.checked = true|false
Property Values:
true: It specifies that a radio button is checked.
false: It has a Default Value. It specify that the radio button is not checked.
Return value: It returns a Boolean value which represents that the radio button is checked or not.
Example-1: This Example illustrates how to return the Property.
<!DOCTYPE html><html> <head> <style> body { text-align: center; } h1 { color: green; } </style></head> <body> <h1> GeeksforGeeks </h1> <h2> HTML DOM Input Radio Checked Property </h2> <form id="myGeeks"> Radio Button: <input type="radio" checked=true id="radioID" value="Geeks_radio" name="Geek_radio" disabled> <br> <br> </form> <button onclick="GFG()"> Click! </button> <p id="GFG" style="font-size:25px; color:green;"> </p> <script> function GFG() { // Accessing input element // type="radio" var x = document.getElementById( "radioID").defaultChecked; document.getElementById( "GFG").innerHTML = x; } </script> </body> </html>
Output:Before Clicking On Button:
After Clicking On Button:
Example-2: This Example illustrates how to set the Property.
<!DOCTYPE html><html> <head> <style> body { text-align: center; } h1 { color: green; } </style></head> <body> <h1>GeeksforGeeks</h1> <h2>HTML DOM Input Radio Checked Property</h2> <form id="myGeeks"> Radio Button: <input type="radio" id="radioID" value="Geeks_radio" name="Geek_radio" checked> <br> <br> </form> <button onclick="GFG()"> check </button> <button onclick="uncheck()"> uncheck </button> <p id="GFG" style="font-size:25px; color:green;"> </p> <script> function GFG() { // Accessing input element // type="radio" document.getElementById( "radioID").checked = "true"; } function uncheck() { document.getElementById( "radioID").checked = false; } </script> </body> </html>
Output:Before Clicking On check Button:
After Clicking On check Button:
After Clicking On uncheck button:
Supported Browsers: The browser supported by DOM input Radio checked property are listed below:
Google Chrome
Internet Explorer 10.0 +
Firefox
Opera
Safari
shubham_singh
HTML-DOM
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
REST API (Introduction)
CSS to put icon inside an input element in a form
Types of CSS (Cascading Style Sheet)
Design a Tribute Page using HTML & CSS
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n17 Oct, 2019"
},
{
"code": null,
"e": 232,
"s": 53,
"text": "The DOM Input Radio checked Property in HTML DOM is used to set or return the checked state of an Input Radio Button. This Property is used to reflect the HTML checked attribute."
},
{
"code": null,
"e": 240,
"s": 232,
"text": "Syntax:"
},
{
"code": null,
"e": 292,
"s": 240,
"text": "It returns the checked property.radioObject.checked"
},
{
"code": null,
"e": 312,
"s": 292,
"text": "radioObject.checked"
},
{
"code": null,
"e": 384,
"s": 312,
"text": "It is used to set the checked property:radioObject.checked = true|false"
},
{
"code": null,
"e": 417,
"s": 384,
"text": "radioObject.checked = true|false"
},
{
"code": null,
"e": 434,
"s": 417,
"text": "Property Values:"
},
{
"code": null,
"e": 485,
"s": 434,
"text": "true: It specifies that a radio button is checked."
},
{
"code": null,
"e": 565,
"s": 485,
"text": "false: It has a Default Value. It specify that the radio button is not checked."
},
{
"code": null,
"e": 664,
"s": 565,
"text": "Return value: It returns a Boolean value which represents that the radio button is checked or not."
},
{
"code": null,
"e": 728,
"s": 664,
"text": "Example-1: This Example illustrates how to return the Property."
},
{
"code": "<!DOCTYPE html><html> <head> <style> body { text-align: center; } h1 { color: green; } </style></head> <body> <h1> GeeksforGeeks </h1> <h2> HTML DOM Input Radio Checked Property </h2> <form id=\"myGeeks\"> Radio Button: <input type=\"radio\" checked=true id=\"radioID\" value=\"Geeks_radio\" name=\"Geek_radio\" disabled> <br> <br> </form> <button onclick=\"GFG()\"> Click! </button> <p id=\"GFG\" style=\"font-size:25px; color:green;\"> </p> <script> function GFG() { // Accessing input element // type=\"radio\" var x = document.getElementById( \"radioID\").defaultChecked; document.getElementById( \"GFG\").innerHTML = x; } </script> </body> </html>",
"e": 1721,
"s": 728,
"text": null
},
{
"code": null,
"e": 1755,
"s": 1721,
"text": "Output:Before Clicking On Button:"
},
{
"code": null,
"e": 1781,
"s": 1755,
"text": "After Clicking On Button:"
},
{
"code": null,
"e": 1842,
"s": 1781,
"text": "Example-2: This Example illustrates how to set the Property."
},
{
"code": "<!DOCTYPE html><html> <head> <style> body { text-align: center; } h1 { color: green; } </style></head> <body> <h1>GeeksforGeeks</h1> <h2>HTML DOM Input Radio Checked Property</h2> <form id=\"myGeeks\"> Radio Button: <input type=\"radio\" id=\"radioID\" value=\"Geeks_radio\" name=\"Geek_radio\" checked> <br> <br> </form> <button onclick=\"GFG()\"> check </button> <button onclick=\"uncheck()\"> uncheck </button> <p id=\"GFG\" style=\"font-size:25px; color:green;\"> </p> <script> function GFG() { // Accessing input element // type=\"radio\" document.getElementById( \"radioID\").checked = \"true\"; } function uncheck() { document.getElementById( \"radioID\").checked = false; } </script> </body> </html>",
"e": 2858,
"s": 1842,
"text": null
},
{
"code": null,
"e": 2898,
"s": 2858,
"text": "Output:Before Clicking On check Button:"
},
{
"code": null,
"e": 2930,
"s": 2898,
"text": "After Clicking On check Button:"
},
{
"code": null,
"e": 2964,
"s": 2930,
"text": "After Clicking On uncheck button:"
},
{
"code": null,
"e": 3060,
"s": 2964,
"text": "Supported Browsers: The browser supported by DOM input Radio checked property are listed below:"
},
{
"code": null,
"e": 3074,
"s": 3060,
"text": "Google Chrome"
},
{
"code": null,
"e": 3099,
"s": 3074,
"text": "Internet Explorer 10.0 +"
},
{
"code": null,
"e": 3107,
"s": 3099,
"text": "Firefox"
},
{
"code": null,
"e": 3113,
"s": 3107,
"text": "Opera"
},
{
"code": null,
"e": 3120,
"s": 3113,
"text": "Safari"
},
{
"code": null,
"e": 3134,
"s": 3120,
"text": "shubham_singh"
},
{
"code": null,
"e": 3143,
"s": 3134,
"text": "HTML-DOM"
},
{
"code": null,
"e": 3148,
"s": 3143,
"text": "HTML"
},
{
"code": null,
"e": 3165,
"s": 3148,
"text": "Web Technologies"
},
{
"code": null,
"e": 3170,
"s": 3165,
"text": "HTML"
},
{
"code": null,
"e": 3268,
"s": 3170,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3316,
"s": 3268,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 3340,
"s": 3316,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 3390,
"s": 3340,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 3427,
"s": 3390,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 3466,
"s": 3427,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 3499,
"s": 3466,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 3560,
"s": 3499,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3603,
"s": 3560,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 3675,
"s": 3603,
"text": "Differences between Functional Components and Class Components in React"
}
] |
Tournament Tree (Winner Tree) and Binary Heap | 17 Jun, 2022
Given a team of N players. How many minimum games are required to find the second-best player?
We can use adversary arguments based on the tournament tree (Binary Heap). A Tournament tree is a form of min (max) heap which is a complete binary tree. Every external node represents a player and the internal node represents the winner.
In a tournament tree, every internal node contains the winner and every leaf node contains one player. There will be N – 1 internal node in a binary tree with N leaf (external) nodes.
For details see this post (put n = 2 in the equation given in the post). It is obvious that to select the best player among N players, (N – 1) players are to be eliminated, i.e. we need a minimum of (N – 1) games (comparisons). Mathematically we can prove it. In a binary tree, I = E – 1, where I is a number of internal nodes and E is a number of external nodes. It means to find the maximum or minimum element of an array, we need N – 1 (internal nodes) comparisons.
Second Best Player The information explored during best player selection can be used to minimize the number of comparisons in tracing the next best players. For example, we can pick the second-best player in (N + log2N – 2) comparisons. The following diagram displays a tournament tree (winner tree) as a max heap. Note that the concept of the loser tree is different.
The above tree contains 4 leaf nodes that represent players and have 3 levels 0, 1, and 2. Initially, 2 games are conducted at level 2, one between 5 and 3 and another one between 7 and 8. In the next move, one more game is conducted between 5 and 8 to conclude the final winner. Overall we need 3 comparisons.
For the second-best player we need to trace the candidates who participated with the final winner, which leads to 7 as the second-best.
Median of Sorted Arrays Tournament tree can effectively be used to find the median of sorted arrays. Assume, given M sorted arrays of equal size L (for simplicity). We can attach all these sorted arrays to the tournament tree, one array per leaf. We need a tree of height CEIL (log2M) to have at least M external nodes. Consider an example. Given 3 (M = 3) sorted integer arrays of maximum size 5 elements.
{ 2, 5, 7, 11, 15 } ---- Array1
{1, 3, 4} ---- Array2
{6, 8, 12, 13, 14} ---- Array3
What should be the height of the tournament tree? We need to construct a tournament tree of height log23 .= 1.585 = 2 rounded to the next integer. A binary tree of height 2 will have 4 leaves to which we can attach the arrays as shown in the below figure.
After the first tournament, the tree appears as below,
We can observe that the winner is from Array2. Hence the next element from Array2 will dive in and games will be played along the winner path of the previous tournament.
Note that infinity is used as a sentinel element. Based on data being held in nodes, we can select the sentinel character. For example, we usually store the pointers in nodes rather than keys, so NULL can serve as a sentinel. If any of the array exhausts we will fill the corresponding leaf and upcoming internal nodes with sentinel. After the second tournament, the tree appears as below,
The next winner is from Array1, so the next element of the Array1 array which is 5 will dive into the next round, and the next tournament played along the path of 2. The tournaments can be continued till we get the median element which is (5+3+5)/2 = 7th element.
Note that there are even better algorithms for finding the median of the union of sorted arrays, for details see the related links given below.
In general with M sorted lists of size L1, L2 ... Lm requires time complexity of O((L1 + L2 + ... + Lm) * logM) to merge all the arrays and O(m*logM) time to find median, where m is median position.
elect the smallest one million elements from one billion unsorted elements: As a simple solution, we can sort a billion numbers and select the first one million. On a limited memory system sorting a billion elements and picking the first one million seems to be impractical. We can use the tournament tree approach. At any time only elements of a tree are in memory.
Split the large array (perhaps stored on disk) into smaller size arrays of size one million each (or even smaller that can be sorted by the machine). Sort these 1000 small size arrays and store them on disk as individual files. Construct a tournament tree that can have at least 1000 leaf nodes (tree to be of height 10 since 29 < 1000 < 210, if the individual file size is even smaller we will need more leaf nodes). Every leaf node will have an engine that picks the next element from the sorted file stored on disk.
We can play the tournament tree game to extract the first one million elements. Total cost = sorting 1000 lists of one million each + tree construction + tournaments.
Application of Tournament Trees:
Used for sorting purposes.
Used to find the largest and smallest element
It may also be used in m-way merges
Applied in the Truck Loading problem
Implementation:
We need to build the tree in a bottom-up manner. All the leaf nodes were filled first. Start at the left extreme of the tree and fill along the breadth (i.e. from 2k-1 to 2k – 1 where k is the depth of the tree) and play the game. After practicing with a few examples it will be easy to write code. Implementation is discussed in the below code Second minimum element using minimum comparisons
Related Posts : Find the smallest and second smallest element in an array. Second minimum element using minimum comparisons — by Venki.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
guptavivek0503
hardikkoriintern
Advanced Data Structure
Heap
Heap
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n17 Jun, 2022"
},
{
"code": null,
"e": 149,
"s": 52,
"text": "Given a team of N players. How many minimum games are required to find the second-best player? "
},
{
"code": null,
"e": 389,
"s": 149,
"text": "We can use adversary arguments based on the tournament tree (Binary Heap). A Tournament tree is a form of min (max) heap which is a complete binary tree. Every external node represents a player and the internal node represents the winner. "
},
{
"code": null,
"e": 574,
"s": 389,
"text": "In a tournament tree, every internal node contains the winner and every leaf node contains one player. There will be N – 1 internal node in a binary tree with N leaf (external) nodes. "
},
{
"code": null,
"e": 1044,
"s": 574,
"text": "For details see this post (put n = 2 in the equation given in the post). It is obvious that to select the best player among N players, (N – 1) players are to be eliminated, i.e. we need a minimum of (N – 1) games (comparisons). Mathematically we can prove it. In a binary tree, I = E – 1, where I is a number of internal nodes and E is a number of external nodes. It means to find the maximum or minimum element of an array, we need N – 1 (internal nodes) comparisons. "
},
{
"code": null,
"e": 1415,
"s": 1044,
"text": "Second Best Player The information explored during best player selection can be used to minimize the number of comparisons in tracing the next best players. For example, we can pick the second-best player in (N + log2N – 2) comparisons. The following diagram displays a tournament tree (winner tree) as a max heap. Note that the concept of the loser tree is different. "
},
{
"code": null,
"e": 1729,
"s": 1417,
"text": "The above tree contains 4 leaf nodes that represent players and have 3 levels 0, 1, and 2. Initially, 2 games are conducted at level 2, one between 5 and 3 and another one between 7 and 8. In the next move, one more game is conducted between 5 and 8 to conclude the final winner. Overall we need 3 comparisons. "
},
{
"code": null,
"e": 1866,
"s": 1729,
"text": "For the second-best player we need to trace the candidates who participated with the final winner, which leads to 7 as the second-best. "
},
{
"code": null,
"e": 2273,
"s": 1866,
"text": "Median of Sorted Arrays Tournament tree can effectively be used to find the median of sorted arrays. Assume, given M sorted arrays of equal size L (for simplicity). We can attach all these sorted arrays to the tournament tree, one array per leaf. We need a tree of height CEIL (log2M) to have at least M external nodes. Consider an example. Given 3 (M = 3) sorted integer arrays of maximum size 5 elements."
},
{
"code": null,
"e": 2358,
"s": 2273,
"text": "{ 2, 5, 7, 11, 15 } ---- Array1\n{1, 3, 4} ---- Array2\n{6, 8, 12, 13, 14} ---- Array3"
},
{
"code": null,
"e": 2614,
"s": 2358,
"text": "What should be the height of the tournament tree? We need to construct a tournament tree of height log23 .= 1.585 = 2 rounded to the next integer. A binary tree of height 2 will have 4 leaves to which we can attach the arrays as shown in the below figure."
},
{
"code": null,
"e": 2672,
"s": 2617,
"text": "After the first tournament, the tree appears as below,"
},
{
"code": null,
"e": 2843,
"s": 2672,
"text": "We can observe that the winner is from Array2. Hence the next element from Array2 will dive in and games will be played along the winner path of the previous tournament. "
},
{
"code": null,
"e": 3234,
"s": 2843,
"text": "Note that infinity is used as a sentinel element. Based on data being held in nodes, we can select the sentinel character. For example, we usually store the pointers in nodes rather than keys, so NULL can serve as a sentinel. If any of the array exhausts we will fill the corresponding leaf and upcoming internal nodes with sentinel. After the second tournament, the tree appears as below, "
},
{
"code": null,
"e": 3501,
"s": 3236,
"text": "The next winner is from Array1, so the next element of the Array1 array which is 5 will dive into the next round, and the next tournament played along the path of 2. The tournaments can be continued till we get the median element which is (5+3+5)/2 = 7th element. "
},
{
"code": null,
"e": 3646,
"s": 3501,
"text": "Note that there are even better algorithms for finding the median of the union of sorted arrays, for details see the related links given below. "
},
{
"code": null,
"e": 3846,
"s": 3646,
"text": "In general with M sorted lists of size L1, L2 ... Lm requires time complexity of O((L1 + L2 + ... + Lm) * logM) to merge all the arrays and O(m*logM) time to find median, where m is median position. "
},
{
"code": null,
"e": 4214,
"s": 3846,
"text": "elect the smallest one million elements from one billion unsorted elements: As a simple solution, we can sort a billion numbers and select the first one million. On a limited memory system sorting a billion elements and picking the first one million seems to be impractical. We can use the tournament tree approach. At any time only elements of a tree are in memory. "
},
{
"code": null,
"e": 4734,
"s": 4214,
"text": "Split the large array (perhaps stored on disk) into smaller size arrays of size one million each (or even smaller that can be sorted by the machine). Sort these 1000 small size arrays and store them on disk as individual files. Construct a tournament tree that can have at least 1000 leaf nodes (tree to be of height 10 since 29 < 1000 < 210, if the individual file size is even smaller we will need more leaf nodes). Every leaf node will have an engine that picks the next element from the sorted file stored on disk. "
},
{
"code": null,
"e": 4901,
"s": 4734,
"text": "We can play the tournament tree game to extract the first one million elements. Total cost = sorting 1000 lists of one million each + tree construction + tournaments."
},
{
"code": null,
"e": 4934,
"s": 4901,
"text": "Application of Tournament Trees:"
},
{
"code": null,
"e": 4961,
"s": 4934,
"text": "Used for sorting purposes."
},
{
"code": null,
"e": 5008,
"s": 4961,
"text": "Used to find the largest and smallest element "
},
{
"code": null,
"e": 5044,
"s": 5008,
"text": "It may also be used in m-way merges"
},
{
"code": null,
"e": 5081,
"s": 5044,
"text": "Applied in the Truck Loading problem"
},
{
"code": null,
"e": 5098,
"s": 5081,
"text": "Implementation: "
},
{
"code": null,
"e": 5492,
"s": 5098,
"text": "We need to build the tree in a bottom-up manner. All the leaf nodes were filled first. Start at the left extreme of the tree and fill along the breadth (i.e. from 2k-1 to 2k – 1 where k is the depth of the tree) and play the game. After practicing with a few examples it will be easy to write code. Implementation is discussed in the below code Second minimum element using minimum comparisons"
},
{
"code": null,
"e": 5629,
"s": 5492,
"text": "Related Posts : Find the smallest and second smallest element in an array. Second minimum element using minimum comparisons — by Venki. "
},
{
"code": null,
"e": 5754,
"s": 5629,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 5769,
"s": 5754,
"text": "guptavivek0503"
},
{
"code": null,
"e": 5786,
"s": 5769,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 5810,
"s": 5786,
"text": "Advanced Data Structure"
},
{
"code": null,
"e": 5815,
"s": 5810,
"text": "Heap"
},
{
"code": null,
"e": 5820,
"s": 5815,
"text": "Heap"
}
] |
Postman - Authorization | In Postman, authorization is done to verify the eligibility of a user to access a resource in the server. There could be multiple APIs in a project, but their access can be restricted only for certain authorized users.
The process of authorization is applied for the APIs which are required to be secured. This authorization is done for identification and to verify, if the user is entitled to access a server resource.
This is done within the Authorization tab in Postman, as shown below −
In the TYPE dropdown, there are various types of Authorization options, which are as shown below −
Let us now create a POST request with the APIs from GitHub Developer having an endpoint https://www.api.github.com/user/repos. In the Postman, click the Body tab and select the option raw and then choose the JSON format.
Add the below request body −
{
"name" : "Tutorialspoint"
}
Then, click on Send.
The Response code obtained is 401 Unauthorized. This means, we need to pass authorization to use this resource. To authorize, select any option from the TYPE dropdown within the Authorization tab.
Let us discuss some of the important authorization types namely Bearer Token and Basic Authentication.
For Bearer Token Authorization, we have to choose the option Bearer Token from the TYPE dropdown. After this, the Token field gets displayed which needs to be provided in order to complete the Authorization.
Step 1 − To get the Token for the GitHub API, first login to the GitHub account by clicking on the link given herewith − https://github.com/login .
Step 2 − After logging in, click on the upper right corner of the screen and select the Settings option.
Now, select the option Developer settings.
Next, click on Personal access tokens.
Now, click on the Generate new token button.
Provide a Note and select option repo. Then, click on Generate Token at the bottom of the page.
Finally, a Token gets generated.
Copy the Token and paste it within the Token field under the Authorization tab in Postman. Then, click on Send.
Please note − Here, the Token is unique to a particular GitHub account and should not be shared.
Response
The Response code is 201 Created which means that the request is successful.
For Basic Authentication Authorization, we have to choose the option Basic Auth from the TYPE dropdown, so that the Username and Password fields get displayed.
First we shall send a GET request for an endpoint (https://postman-echo.com/basic-auth) with the option No Auth selected from the TYPE dropdown.
Please note − The username for the above endpoint is postman and password is password.
The Response Code obtained is 401 Unauthorized. This means that Authorization did not pass for this API.
Now, let us select the option Basic Auth as the Authorization type, following which the Username and Password fields get displayed.
Enter the postman for the Username and password for the Password field. Then, click on Send.
The Response code obtained is now 200 OK, which means that our request has been sent successfully.
No Auth
We can also carry out Basic Authentication using the request Header. First, we have to choose the option as No Auth from the Authorization tab. Then in the Headers tab, we have to add a key − value pair.
We shall have the key as Authorization and the value is the username and password of the user in the format as basic < encoded credential >.
The endpoint used in our example is − https://postman-echo.com/basic-auth. To encode the username and password, we shall take the help of the third party application having the URL − https://www.base64encode.org
Please note − The username for our endpoint here is postman and password is password. Enter postman − password in the edit box and click on Encode. The encoded value gets populated at the bottom.
We shall add the encoded Username and Password received as cG9zdG1hbjpwYXNzd29yZA== in the Header in the format -basic cG9zdG1hbjpwYXNzd29yZA ==. Then, click on Send.
No Auth selected from the TYPE dropdown.
The Response code obtained is 200 OK, which means that our request has been sent successfully.
To add Authorization for a Collection, following the steps given below −
Step 1 − Click on the three dots beside the Collection name in Postman and select the option Edit.
Step 2 − The EDIT COLLECTION pop-up comes up. Move to the Authorization tab and then select any option from the TYPE dropdown. Click on Update. | [
{
"code": null,
"e": 2461,
"s": 2242,
"text": "In Postman, authorization is done to verify the eligibility of a user to access a resource in the server. There could be multiple APIs in a project, but their access can be restricted only for certain authorized users."
},
{
"code": null,
"e": 2662,
"s": 2461,
"text": "The process of authorization is applied for the APIs which are required to be secured. This authorization is done for identification and to verify, if the user is entitled to access a server resource."
},
{
"code": null,
"e": 2733,
"s": 2662,
"text": "This is done within the Authorization tab in Postman, as shown below −"
},
{
"code": null,
"e": 2832,
"s": 2733,
"text": "In the TYPE dropdown, there are various types of Authorization options, which are as shown below −"
},
{
"code": null,
"e": 3053,
"s": 2832,
"text": "Let us now create a POST request with the APIs from GitHub Developer having an endpoint https://www.api.github.com/user/repos. In the Postman, click the Body tab and select the option raw and then choose the JSON format."
},
{
"code": null,
"e": 3082,
"s": 3053,
"text": "Add the below request body −"
},
{
"code": null,
"e": 3114,
"s": 3082,
"text": "{\n\t\"name\" : \"Tutorialspoint\"\n}\n"
},
{
"code": null,
"e": 3135,
"s": 3114,
"text": "Then, click on Send."
},
{
"code": null,
"e": 3332,
"s": 3135,
"text": "The Response code obtained is 401 Unauthorized. This means, we need to pass authorization to use this resource. To authorize, select any option from the TYPE dropdown within the Authorization tab."
},
{
"code": null,
"e": 3435,
"s": 3332,
"text": "Let us discuss some of the important authorization types namely Bearer Token and Basic Authentication."
},
{
"code": null,
"e": 3643,
"s": 3435,
"text": "For Bearer Token Authorization, we have to choose the option Bearer Token from the TYPE dropdown. After this, the Token field gets displayed which needs to be provided in order to complete the Authorization."
},
{
"code": null,
"e": 3791,
"s": 3643,
"text": "Step 1 − To get the Token for the GitHub API, first login to the GitHub account by clicking on the link given herewith − https://github.com/login ."
},
{
"code": null,
"e": 3896,
"s": 3791,
"text": "Step 2 − After logging in, click on the upper right corner of the screen and select the Settings option."
},
{
"code": null,
"e": 3939,
"s": 3896,
"text": "Now, select the option Developer settings."
},
{
"code": null,
"e": 3978,
"s": 3939,
"text": "Next, click on Personal access tokens."
},
{
"code": null,
"e": 4023,
"s": 3978,
"text": "Now, click on the Generate new token button."
},
{
"code": null,
"e": 4119,
"s": 4023,
"text": "Provide a Note and select option repo. Then, click on Generate Token at the bottom of the page."
},
{
"code": null,
"e": 4152,
"s": 4119,
"text": "Finally, a Token gets generated."
},
{
"code": null,
"e": 4264,
"s": 4152,
"text": "Copy the Token and paste it within the Token field under the Authorization tab in Postman. Then, click on Send."
},
{
"code": null,
"e": 4361,
"s": 4264,
"text": "Please note − Here, the Token is unique to a particular GitHub account and should not be shared."
},
{
"code": null,
"e": 4370,
"s": 4361,
"text": "Response"
},
{
"code": null,
"e": 4447,
"s": 4370,
"text": "The Response code is 201 Created which means that the request is successful."
},
{
"code": null,
"e": 4607,
"s": 4447,
"text": "For Basic Authentication Authorization, we have to choose the option Basic Auth from the TYPE dropdown, so that the Username and Password fields get displayed."
},
{
"code": null,
"e": 4752,
"s": 4607,
"text": "First we shall send a GET request for an endpoint (https://postman-echo.com/basic-auth) with the option No Auth selected from the TYPE dropdown."
},
{
"code": null,
"e": 4839,
"s": 4752,
"text": "Please note − The username for the above endpoint is postman and password is password."
},
{
"code": null,
"e": 4944,
"s": 4839,
"text": "The Response Code obtained is 401 Unauthorized. This means that Authorization did not pass for this API."
},
{
"code": null,
"e": 5076,
"s": 4944,
"text": "Now, let us select the option Basic Auth as the Authorization type, following which the Username and Password fields get displayed."
},
{
"code": null,
"e": 5169,
"s": 5076,
"text": "Enter the postman for the Username and password for the Password field. Then, click on Send."
},
{
"code": null,
"e": 5268,
"s": 5169,
"text": "The Response code obtained is now 200 OK, which means that our request has been sent successfully."
},
{
"code": null,
"e": 5276,
"s": 5268,
"text": "No Auth"
},
{
"code": null,
"e": 5480,
"s": 5276,
"text": "We can also carry out Basic Authentication using the request Header. First, we have to choose the option as No Auth from the Authorization tab. Then in the Headers tab, we have to add a key − value pair."
},
{
"code": null,
"e": 5621,
"s": 5480,
"text": "We shall have the key as Authorization and the value is the username and password of the user in the format as basic < encoded credential >."
},
{
"code": null,
"e": 5833,
"s": 5621,
"text": "The endpoint used in our example is − https://postman-echo.com/basic-auth. To encode the username and password, we shall take the help of the third party application having the URL − https://www.base64encode.org"
},
{
"code": null,
"e": 6029,
"s": 5833,
"text": "Please note − The username for our endpoint here is postman and password is password. Enter postman − password in the edit box and click on Encode. The encoded value gets populated at the bottom."
},
{
"code": null,
"e": 6196,
"s": 6029,
"text": "We shall add the encoded Username and Password received as cG9zdG1hbjpwYXNzd29yZA== in the Header in the format -basic cG9zdG1hbjpwYXNzd29yZA ==. Then, click on Send."
},
{
"code": null,
"e": 6237,
"s": 6196,
"text": "No Auth selected from the TYPE dropdown."
},
{
"code": null,
"e": 6332,
"s": 6237,
"text": "The Response code obtained is 200 OK, which means that our request has been sent successfully."
},
{
"code": null,
"e": 6405,
"s": 6332,
"text": "To add Authorization for a Collection, following the steps given below −"
},
{
"code": null,
"e": 6504,
"s": 6405,
"text": "Step 1 − Click on the three dots beside the Collection name in Postman and select the option Edit."
}
] |
STD::array in C++ | 09 Jun, 2022
The array is a collection of homogeneous objects and this array container is defined for constant size arrays or (static size). This container wraps around fixed-size arrays and the information of its size are not lost when declared to a pointer. In order to utilize arrays, we need to include the array header:
#include <array>
Let’s see an example.
CPP
// CPP program to demonstrate working of array#include <algorithm>#include <array>#include <iostream>#include <iterator>#include <string>using namespace std; int main() { // construction uses aggregate initialization // double-braces required array<int, 5> ar1{{3, 4, 5, 1, 2}}; array<int, 5> ar2 = {1, 2, 3, 4, 5}; array<string, 2> ar3 = {{string("a"), "b"}}; cout << "Sizes of arrays are" << endl; cout << ar1.size() << endl; cout << ar2.size() << endl; cout << ar3.size() << endl; cout << "\nInitial ar1 : "; for (auto i : ar1) cout << i << ' '; // container operations are supported sort(ar1.begin(), ar1.end()); cout << "\nsorted ar1 : "; for (auto i : ar1) cout << i << ' '; // Filling ar2 with 10 ar2.fill(10); cout << "\nFilled ar2 : "; for (auto i : ar2) cout << i << ' '; // ranged for loop is supported cout << "\nar3 : "; for (auto &s : ar3) cout << s << ' '; return 0;}
Sizes of arrays are
5
5
2
Initial ar1 : 3 4 5 1 2
sorted ar1 : 1 2 3 4 5
Filled ar2 : 10 10 10 10 10
ar3 : a b
This C++ STL array is a kind of sequential container and is not used extremely in regular programming or in competitive programming but sometimes its member function provides an upper edge to it over the regular normal array that we use in our daily life. So, we are discussing some of the important member function that is used with such kind of array:
Member Functions for Array Template are as follows:
Syntax: array<object_type, arr_size> arr_name;
a) [ ] Operator : This is similar to the normal array, we use it to access the element store at index ‘i’ .
Ex:
C++
#include <iostream>#include <array>using namespace std; int main() { array <char , 3> arr={'G','f','G'}; cout<<arr[0] <<" "<<arr[2]; return 0;}
G G
b) front( ) and back( ) function: These methods are used to access the first and the last element of the array directly.
C++
#include <iostream>#include <array>using namespace std; int main() { array <int , 3> arr={'G','f','G'}; // ASCII val of 'G' =71 cout<<arr.front() <<" "<<arr.back(); return 0;}
71 71
c) swap( ) function: This swap function is used to swap the content of the two arrays.
Ex:
C++
#include <iostream>#include <array>using namespace std; int main() { array <int , 3> arr={'G','f','G'}; // ASCII val of 'G' =71 array <int , 3> arr1={'M','M','P'}; // ASCII val of 'M' = 77 and 'P' = 80 arr.swap(arr1); // now arr = {M,M,P} cout<<arr.front() <<" "<<arr.back(); return 0;}
77 80
d) empty( ) function: This function is used to check whether the declared STL array is empty or not, if it is empty then it returns true else false.
Ex:
C++
#include <iostream>#include <array>using namespace std; int main() { array <int , 3> arr={'G','f','G'}; // ASCII val of 'G' =71 array <int , 3> arr1={'M','M','P'}; // ASCII val of 'M' = 77 and 'P' = 80 bool x = arr.empty(); // false ( not empty) cout<<boolalpha<<(x); return 0;}
false
e) at( ) function: This function is used to access the element stored at a specific location, if we try to access the element which is out of bounds of the array size then it throws an exception.
Ex:
C++
#include <iostream>#include <array>using namespace std; int main() { array <int , 3> arr={'G','f','G'}; // ASCII val of 'G' =71 array <int , 3> arr1={'M','M','P'}; // ASCII val of 'M' = 77 and 'P' = 80 cout<< arr.at(2) <<" " << arr1.at(2); //cout<< arr.at(3); // exception{Abort signal from abort(3) (SIGABRT)} return 0;}
71 80
f) fill( ) function: This is specially used to initialize or fill all the indexes of the array with a similar value.
Ex:
C++
#include <iostream>#include <array>using namespace std; int main() { array <int , 5> arr; arr.fill(1); for(int i: arr) cout<<arr[i]<<" "; return 0;}
1 1 1 1 1
g) size( ) or max_size( ) and sizeof( ) function: Both size( ) or max_size( ) are used to get the maximum number of indexes in the array while sizeof( ) is used to get the total size of array in bytes.
C++
#include <iostream>#include <array>using namespace std; int main() { array <int , 10> arr; cout<<arr.size()<<'\n'; // total num of indexes cout<<arr.max_size()<<'\n'; // total num of indexes cout<<sizeof(arr); // total size of array return 0;}
10
10
40
h) data( ): This function returns the pointer to the first element of the array object. Because elements in the array are stored in contiguous memory locations. This data( ) function return us the base address of the string/char type object.
Ex:
C++
#include <iostream>#include <cstring>#include <array> using namespace std; int main (){ const char* str = "GeeksforGeeks"; array<char,13> arr; memcpy (arr.data(),str,13); cout << arr.data() << '\n'; return 0;}
GeeksforGeeks
I) cbegin( ) and cend( ): go to this gfg link : Click_me
rafiqshaheeen22
madhav_mohan
germanshephered48
simmytarika5
r_oh_it
cpp-array
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n09 Jun, 2022"
},
{
"code": null,
"e": 366,
"s": 52,
"text": "The array is a collection of homogeneous objects and this array container is defined for constant size arrays or (static size). This container wraps around fixed-size arrays and the information of its size are not lost when declared to a pointer. In order to utilize arrays, we need to include the array header: "
},
{
"code": null,
"e": 385,
"s": 366,
"text": " #include <array> "
},
{
"code": null,
"e": 410,
"s": 385,
"text": "Let’s see an example. "
},
{
"code": null,
"e": 414,
"s": 410,
"text": "CPP"
},
{
"code": "// CPP program to demonstrate working of array#include <algorithm>#include <array>#include <iostream>#include <iterator>#include <string>using namespace std; int main() { // construction uses aggregate initialization // double-braces required array<int, 5> ar1{{3, 4, 5, 1, 2}}; array<int, 5> ar2 = {1, 2, 3, 4, 5}; array<string, 2> ar3 = {{string(\"a\"), \"b\"}}; cout << \"Sizes of arrays are\" << endl; cout << ar1.size() << endl; cout << ar2.size() << endl; cout << ar3.size() << endl; cout << \"\\nInitial ar1 : \"; for (auto i : ar1) cout << i << ' '; // container operations are supported sort(ar1.begin(), ar1.end()); cout << \"\\nsorted ar1 : \"; for (auto i : ar1) cout << i << ' '; // Filling ar2 with 10 ar2.fill(10); cout << \"\\nFilled ar2 : \"; for (auto i : ar2) cout << i << ' '; // ranged for loop is supported cout << \"\\nar3 : \"; for (auto &s : ar3) cout << s << ' '; return 0;}",
"e": 1344,
"s": 414,
"text": null
},
{
"code": null,
"e": 1459,
"s": 1344,
"text": "Sizes of arrays are\n5\n5\n2\n\nInitial ar1 : 3 4 5 1 2 \nsorted ar1 : 1 2 3 4 5 \nFilled ar2 : 10 10 10 10 10 \nar3 : a b"
},
{
"code": null,
"e": 1815,
"s": 1461,
"text": "This C++ STL array is a kind of sequential container and is not used extremely in regular programming or in competitive programming but sometimes its member function provides an upper edge to it over the regular normal array that we use in our daily life. So, we are discussing some of the important member function that is used with such kind of array:"
},
{
"code": null,
"e": 1867,
"s": 1815,
"text": "Member Functions for Array Template are as follows:"
},
{
"code": null,
"e": 1933,
"s": 1867,
"text": "Syntax: array<object_type, arr_size> arr_name;"
},
{
"code": null,
"e": 2041,
"s": 1933,
"text": "a) [ ] Operator : This is similar to the normal array, we use it to access the element store at index ‘i’ ."
},
{
"code": null,
"e": 2048,
"s": 2041,
"text": "Ex: "
},
{
"code": null,
"e": 2052,
"s": 2048,
"text": "C++"
},
{
"code": "#include <iostream>#include <array>using namespace std; int main() { array <char , 3> arr={'G','f','G'}; cout<<arr[0] <<\" \"<<arr[2]; return 0;}",
"e": 2205,
"s": 2052,
"text": null
},
{
"code": null,
"e": 2209,
"s": 2205,
"text": "G G"
},
{
"code": null,
"e": 2330,
"s": 2209,
"text": "b) front( ) and back( ) function: These methods are used to access the first and the last element of the array directly."
},
{
"code": null,
"e": 2334,
"s": 2330,
"text": "C++"
},
{
"code": "#include <iostream>#include <array>using namespace std; int main() { array <int , 3> arr={'G','f','G'}; // ASCII val of 'G' =71 cout<<arr.front() <<\" \"<<arr.back(); return 0;}",
"e": 2520,
"s": 2334,
"text": null
},
{
"code": null,
"e": 2526,
"s": 2520,
"text": "71 71"
},
{
"code": null,
"e": 2613,
"s": 2526,
"text": "c) swap( ) function: This swap function is used to swap the content of the two arrays."
},
{
"code": null,
"e": 2618,
"s": 2613,
"text": "Ex: "
},
{
"code": null,
"e": 2622,
"s": 2618,
"text": "C++"
},
{
"code": "#include <iostream>#include <array>using namespace std; int main() { array <int , 3> arr={'G','f','G'}; // ASCII val of 'G' =71 array <int , 3> arr1={'M','M','P'}; // ASCII val of 'M' = 77 and 'P' = 80 arr.swap(arr1); // now arr = {M,M,P} cout<<arr.front() <<\" \"<<arr.back(); return 0;}",
"e": 2926,
"s": 2622,
"text": null
},
{
"code": null,
"e": 2932,
"s": 2926,
"text": "77 80"
},
{
"code": null,
"e": 3081,
"s": 2932,
"text": "d) empty( ) function: This function is used to check whether the declared STL array is empty or not, if it is empty then it returns true else false."
},
{
"code": null,
"e": 3086,
"s": 3081,
"text": "Ex: "
},
{
"code": null,
"e": 3090,
"s": 3086,
"text": "C++"
},
{
"code": "#include <iostream>#include <array>using namespace std; int main() { array <int , 3> arr={'G','f','G'}; // ASCII val of 'G' =71 array <int , 3> arr1={'M','M','P'}; // ASCII val of 'M' = 77 and 'P' = 80 bool x = arr.empty(); // false ( not empty) cout<<boolalpha<<(x); return 0;}",
"e": 3385,
"s": 3090,
"text": null
},
{
"code": null,
"e": 3391,
"s": 3385,
"text": "false"
},
{
"code": null,
"e": 3588,
"s": 3391,
"text": "e) at( ) function: This function is used to access the element stored at a specific location, if we try to access the element which is out of bounds of the array size then it throws an exception. "
},
{
"code": null,
"e": 3593,
"s": 3588,
"text": "Ex: "
},
{
"code": null,
"e": 3597,
"s": 3593,
"text": "C++"
},
{
"code": "#include <iostream>#include <array>using namespace std; int main() { array <int , 3> arr={'G','f','G'}; // ASCII val of 'G' =71 array <int , 3> arr1={'M','M','P'}; // ASCII val of 'M' = 77 and 'P' = 80 cout<< arr.at(2) <<\" \" << arr1.at(2); //cout<< arr.at(3); // exception{Abort signal from abort(3) (SIGABRT)} return 0;}",
"e": 3935,
"s": 3597,
"text": null
},
{
"code": null,
"e": 3941,
"s": 3935,
"text": "71 80"
},
{
"code": null,
"e": 4058,
"s": 3941,
"text": "f) fill( ) function: This is specially used to initialize or fill all the indexes of the array with a similar value."
},
{
"code": null,
"e": 4062,
"s": 4058,
"text": "Ex:"
},
{
"code": null,
"e": 4066,
"s": 4062,
"text": "C++"
},
{
"code": "#include <iostream>#include <array>using namespace std; int main() { array <int , 5> arr; arr.fill(1); for(int i: arr) cout<<arr[i]<<\" \"; return 0;}",
"e": 4233,
"s": 4066,
"text": null
},
{
"code": null,
"e": 4244,
"s": 4233,
"text": "1 1 1 1 1 "
},
{
"code": null,
"e": 4446,
"s": 4244,
"text": "g) size( ) or max_size( ) and sizeof( ) function: Both size( ) or max_size( ) are used to get the maximum number of indexes in the array while sizeof( ) is used to get the total size of array in bytes."
},
{
"code": null,
"e": 4450,
"s": 4446,
"text": "C++"
},
{
"code": "#include <iostream>#include <array>using namespace std; int main() { array <int , 10> arr; cout<<arr.size()<<'\\n'; // total num of indexes cout<<arr.max_size()<<'\\n'; // total num of indexes cout<<sizeof(arr); // total size of array return 0;}",
"e": 4712,
"s": 4450,
"text": null
},
{
"code": null,
"e": 4721,
"s": 4712,
"text": "10\n10\n40"
},
{
"code": null,
"e": 4963,
"s": 4721,
"text": "h) data( ): This function returns the pointer to the first element of the array object. Because elements in the array are stored in contiguous memory locations. This data( ) function return us the base address of the string/char type object."
},
{
"code": null,
"e": 4968,
"s": 4963,
"text": "Ex: "
},
{
"code": null,
"e": 4972,
"s": 4968,
"text": "C++"
},
{
"code": "#include <iostream>#include <cstring>#include <array> using namespace std; int main (){ const char* str = \"GeeksforGeeks\"; array<char,13> arr; memcpy (arr.data(),str,13); cout << arr.data() << '\\n'; return 0;}",
"e": 5187,
"s": 4972,
"text": null
},
{
"code": null,
"e": 5204,
"s": 5190,
"text": "GeeksforGeeks"
},
{
"code": null,
"e": 5264,
"s": 5206,
"text": "I) cbegin( ) and cend( ): go to this gfg link : Click_me"
},
{
"code": null,
"e": 5282,
"s": 5266,
"text": "rafiqshaheeen22"
},
{
"code": null,
"e": 5295,
"s": 5282,
"text": "madhav_mohan"
},
{
"code": null,
"e": 5313,
"s": 5295,
"text": "germanshephered48"
},
{
"code": null,
"e": 5326,
"s": 5313,
"text": "simmytarika5"
},
{
"code": null,
"e": 5334,
"s": 5326,
"text": "r_oh_it"
},
{
"code": null,
"e": 5344,
"s": 5334,
"text": "cpp-array"
},
{
"code": null,
"e": 5348,
"s": 5344,
"text": "STL"
},
{
"code": null,
"e": 5352,
"s": 5348,
"text": "C++"
},
{
"code": null,
"e": 5356,
"s": 5352,
"text": "STL"
},
{
"code": null,
"e": 5360,
"s": 5356,
"text": "CPP"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.