title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Creating a sorted merged list of two unsorted lists in Python
21 Nov, 2018 We need to take two lists in Python and merge them into one. Finally, we display the sorted list. Examples: Input : list1 = [25, 18, 9, 41, 26, 31] list2 = [25, 45, 3, 32, 15, 20] Output : [3, 9, 15, 18, 20, 25, 25, 26, 31, 32, 41, 45] Input : list1 = ["suraj", "anand", "gaurav", "aman", "kishore"] list2 = ["rohan", "ram", "mohan", "priya", "komal"] Output : ['aman', 'anand', 'gaurav', 'kishore', 'komal', 'mohan', 'priya', 'ram', 'rohan', 'suraj'] The plus operator “+” in Python helps us to merge two lists, be it a list of string or integers or mixture of both. Finally, we sort the list using the sort() function. # Python program to merge and sort two listdef Merge(list1, list2): final_list = list1 + list2 final_list.sort() return(final_list) # Driver Codelist1 = [25, 18, 9, 41, 26, 31]list2 = [25, 45, 3, 32, 15, 20]print(Merge(list1, list2)) Output: [3, 9, 15, 18, 20, 25, 25, 26, 31, 32, 41, 45] Python list-programs python-list Python python-list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Different ways to create Pandas Dataframe Enumerate() in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python 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": 52, "s": 24, "text": "\n21 Nov, 2018" }, { "code": null, "e": 150, "s": 52, "text": "We need to take two lists in Python and merge them into one. Finally, we display the sorted list." }, { "code": null, "e": 160, "s": 150, "text": "Examples:" }, { "code": null, "e": 509, "s": 160, "text": "Input : \nlist1 = [25, 18, 9, 41, 26, 31]\nlist2 = [25, 45, 3, 32, 15, 20]\nOutput :\n[3, 9, 15, 18, 20, 25, 25, 26, 31, 32, 41, 45]\n\nInput : \nlist1 = [\"suraj\", \"anand\", \"gaurav\", \"aman\", \"kishore\"]\nlist2 = [\"rohan\", \"ram\", \"mohan\", \"priya\", \"komal\"]\nOutput :\n['aman', 'anand', 'gaurav', 'kishore', 'komal', \n'mohan', 'priya', 'ram', 'rohan', 'suraj']\n" }, { "code": null, "e": 678, "s": 509, "text": "The plus operator “+” in Python helps us to merge two lists, be it a list of string or integers or mixture of both. Finally, we sort the list using the sort() function." }, { "code": "# Python program to merge and sort two listdef Merge(list1, list2): final_list = list1 + list2 final_list.sort() return(final_list) # Driver Codelist1 = [25, 18, 9, 41, 26, 31]list2 = [25, 45, 3, 32, 15, 20]print(Merge(list1, list2))", "e": 922, "s": 678, "text": null }, { "code": null, "e": 930, "s": 922, "text": "Output:" }, { "code": null, "e": 978, "s": 930, "text": "[3, 9, 15, 18, 20, 25, 25, 26, 31, 32, 41, 45]\n" }, { "code": null, "e": 999, "s": 978, "text": "Python list-programs" }, { "code": null, "e": 1011, "s": 999, "text": "python-list" }, { "code": null, "e": 1018, "s": 1011, "text": "Python" }, { "code": null, "e": 1030, "s": 1018, "text": "python-list" }, { "code": null, "e": 1128, "s": 1030, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1170, "s": 1128, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1192, "s": 1170, "text": "Enumerate() in Python" }, { "code": null, "e": 1218, "s": 1192, "text": "Python String | replace()" }, { "code": null, "e": 1250, "s": 1218, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1279, "s": 1250, "text": "*args and **kwargs in Python" }, { "code": null, "e": 1306, "s": 1279, "text": "Python Classes and Objects" }, { "code": null, "e": 1327, "s": 1306, "text": "Python OOPs Concepts" }, { "code": null, "e": 1350, "s": 1327, "text": "Introduction To PYTHON" }, { "code": null, "e": 1386, "s": 1350, "text": "Convert integer to string in Python" } ]
Find() function in MATLAB
21 Apr, 2021 The find() function in MATLAB is used to find the indices and values of non-zero elements or the elements which satisfy a given condition. The relational expression can be used in conjunction with find to find the indices of elements that meet the given condition. It returns a vector that contains the linear indices. Using liner index a multidimensional array can be accessed using a single subscript. MATLAB treats the array as a single column vector with each column appended to the bottom of the previous column. Example: For example consider the following 3×3 array A = 1 4 7 2 5 8 3 6 9 In this array all elements represents their linear index i.e. we can reference A(1,2) with A(4). Syntax: Below are various wasy to use the function: k = find(X): It returns the indices of all non zero elements. k = find(X, n): It returns the first n indices of non zero elements in X k = find(X, n, direction): direction can be ‘first’ or ‘last’. If direction is first, this function will return first n indices corresponding to non zero elements and if direction is last then this function will return last n indices corresponding to non zero elements [row, col] = find(): It is used to get row and column subscript for all non zero elements. [row, col, v] = find(): row and column will hold subscript for all non zero elements and v is a vector which will hold all the non zero elements. Note: k will be of same orientation as X if X is a vector and if X is a multidimensional array then k will be a column vector which will hold linear indices. Example 1: Below code will return the indices of non-zero elements in a 1-D array. MATLAB % Defining arrayA = [1 2 3 0] % Getting indices of non zero elementsfind(A) Output: Example 2: Below code will return the first 2 indices of elements where the element will be greater than 3. MATLAB % Defining arrayA = [1 2 0; 3 1 4; 5 6 7] % Getting first 2 indicesfind(A>3, 2) Output: Example 3: Below code will return the last 2 row and column indices of elements that are greater than 3. MATLAB % Defining arrayA = [1 2 0; 3 1 4; 5 6 7] % Getting row and column [row, col] = find(A>3, 2, 'last') Output: So, A(2, 3) and A(3, 3) are the last elements that are greater than 3. We got (2, 3) and (3, 3) as output not (3,2) and (3, 3) because MATLAB treats the array as a single column vector with each column appended to the bottom of the previous column. Example 4: Below code will return indices of all the zero elements. This code uses the negation operator (~) in conjunction with the find function. MATLAB % Defining arrayA = [1 2 3 0] % Getting indices of zero elementsfind(~A) Output: Picked MATLAB Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Convert Three Channels of Colored Image into Grayscale Image in MATLAB? How to Solve Histogram Equalization Numerical Problem in MATLAB? Adaptive Histogram Equalization in Image Processing Using MATLAB MRI Image Segmentation in MATLAB How to detect duplicate values and its indices within an array in MATLAB? Double Integral in MATLAB How to Normalize a Histogram in MATLAB? Classes and Object in MATLAB How to remove space in a string in MATLAB? Forward and Inverse Fourier Transform of an Image in MATLAB
[ { "code": null, "e": 54, "s": 26, "text": "\n21 Apr, 2021" }, { "code": null, "e": 373, "s": 54, "text": "The find() function in MATLAB is used to find the indices and values of non-zero elements or the elements which satisfy a given condition. The relational expression can be used in conjunction with find to find the indices of elements that meet the given condition. It returns a vector that contains the linear indices." }, { "code": null, "e": 572, "s": 373, "text": "Using liner index a multidimensional array can be accessed using a single subscript. MATLAB treats the array as a single column vector with each column appended to the bottom of the previous column." }, { "code": null, "e": 581, "s": 572, "text": "Example:" }, { "code": null, "e": 630, "s": 581, "text": "For example consider the following 3×3 array A =" }, { "code": null, "e": 636, "s": 630, "text": "1 4 7" }, { "code": null, "e": 642, "s": 636, "text": "2 5 8" }, { "code": null, "e": 648, "s": 642, "text": "3 6 9" }, { "code": null, "e": 745, "s": 648, "text": "In this array all elements represents their linear index i.e. we can reference A(1,2) with A(4)." }, { "code": null, "e": 753, "s": 745, "text": "Syntax:" }, { "code": null, "e": 797, "s": 753, "text": "Below are various wasy to use the function:" }, { "code": null, "e": 859, "s": 797, "text": "k = find(X): It returns the indices of all non zero elements." }, { "code": null, "e": 932, "s": 859, "text": "k = find(X, n): It returns the first n indices of non zero elements in X" }, { "code": null, "e": 1201, "s": 932, "text": "k = find(X, n, direction): direction can be ‘first’ or ‘last’. If direction is first, this function will return first n indices corresponding to non zero elements and if direction is last then this function will return last n indices corresponding to non zero elements" }, { "code": null, "e": 1292, "s": 1201, "text": "[row, col] = find(): It is used to get row and column subscript for all non zero elements." }, { "code": null, "e": 1438, "s": 1292, "text": "[row, col, v] = find(): row and column will hold subscript for all non zero elements and v is a vector which will hold all the non zero elements." }, { "code": null, "e": 1596, "s": 1438, "text": "Note: k will be of same orientation as X if X is a vector and if X is a multidimensional array then k will be a column vector which will hold linear indices." }, { "code": null, "e": 1679, "s": 1596, "text": "Example 1: Below code will return the indices of non-zero elements in a 1-D array." }, { "code": null, "e": 1686, "s": 1679, "text": "MATLAB" }, { "code": "% Defining arrayA = [1 2 3 0] % Getting indices of non zero elementsfind(A)", "e": 1763, "s": 1686, "text": null }, { "code": null, "e": 1771, "s": 1763, "text": "Output:" }, { "code": null, "e": 1879, "s": 1771, "text": "Example 2: Below code will return the first 2 indices of elements where the element will be greater than 3." }, { "code": null, "e": 1886, "s": 1879, "text": "MATLAB" }, { "code": "% Defining arrayA = [1 2 0; 3 1 4; 5 6 7] % Getting first 2 indicesfind(A>3, 2)", "e": 1967, "s": 1886, "text": null }, { "code": null, "e": 1975, "s": 1967, "text": "Output:" }, { "code": null, "e": 2080, "s": 1975, "text": "Example 3: Below code will return the last 2 row and column indices of elements that are greater than 3." }, { "code": null, "e": 2087, "s": 2080, "text": "MATLAB" }, { "code": "% Defining arrayA = [1 2 0; 3 1 4; 5 6 7] % Getting row and column [row, col] = find(A>3, 2, 'last')", "e": 2189, "s": 2087, "text": null }, { "code": null, "e": 2197, "s": 2189, "text": "Output:" }, { "code": null, "e": 2446, "s": 2197, "text": "So, A(2, 3) and A(3, 3) are the last elements that are greater than 3. We got (2, 3) and (3, 3) as output not (3,2) and (3, 3) because MATLAB treats the array as a single column vector with each column appended to the bottom of the previous column." }, { "code": null, "e": 2594, "s": 2446, "text": "Example 4: Below code will return indices of all the zero elements. This code uses the negation operator (~) in conjunction with the find function." }, { "code": null, "e": 2601, "s": 2594, "text": "MATLAB" }, { "code": "% Defining arrayA = [1 2 3 0] % Getting indices of zero elementsfind(~A)", "e": 2675, "s": 2601, "text": null }, { "code": null, "e": 2683, "s": 2675, "text": "Output:" }, { "code": null, "e": 2690, "s": 2683, "text": "Picked" }, { "code": null, "e": 2697, "s": 2690, "text": "MATLAB" }, { "code": null, "e": 2795, "s": 2697, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2874, "s": 2795, "text": "How to Convert Three Channels of Colored Image into Grayscale Image in MATLAB?" }, { "code": null, "e": 2939, "s": 2874, "text": "How to Solve Histogram Equalization Numerical Problem in MATLAB?" }, { "code": null, "e": 3004, "s": 2939, "text": "Adaptive Histogram Equalization in Image Processing Using MATLAB" }, { "code": null, "e": 3037, "s": 3004, "text": "MRI Image Segmentation in MATLAB" }, { "code": null, "e": 3111, "s": 3037, "text": "How to detect duplicate values and its indices within an array in MATLAB?" }, { "code": null, "e": 3137, "s": 3111, "text": "Double Integral in MATLAB" }, { "code": null, "e": 3177, "s": 3137, "text": "How to Normalize a Histogram in MATLAB?" }, { "code": null, "e": 3206, "s": 3177, "text": "Classes and Object in MATLAB" }, { "code": null, "e": 3249, "s": 3206, "text": "How to remove space in a string in MATLAB?" } ]
What are the microtask and macrotask within an event loop in JavaScript ?
21 Feb, 2022 Event Loop: An Event Loop in JavaScript is said to be a constantly running process which keeps a tab on the call stack. Its main function is to check whether the call stack is empty or not. If the call stack turns out to be empty, the event loop proceeds to execute all the callbacks waiting in the task queue. Inside the task queue, the tasks are broadly classified into two categories, namely micro-tasks and macro-tasks. Micro-tasks within an event loop: A micro-task is said to be a function which is executed after the function or program which created it exits and only if the JavaScript execution stack is empty, but before returning control to the event loop being used by the user agent to drive the script’s execution environment. A Micro-task is also capable of en-queuing other micro-tasks. Micro-tasks are often scheduled for things that are required to be completed immediately after the execution of the current script. On completion of one macro-task, the event loop moves on to the micro-task queue. The event loop does not move to the next task outside of the micro-task queue until the all the tasks inside the micro-task queue are completed. This implies that the micro-task queue has a higher priority. Once all the tasks inside the micro-task queue are finished, only then does the event loop shifts back to the macro-task queue. The primary reason for prioritizing the micro-task queue is to improve the user experience. The micro-task queue is processed after callbacks given that any other JavaScript is not under mid-execution. Micro-tasks include mutation observer callbacks as well as promise callbacks. In such a case wherein new micro-tasks are being added to the queue, these additional micro-tasks are added at the end of the micro-queue and these are also processed. This is because the event loop will keeps on calling micro-tasks until there are no more micro-tasks left in the queue, even if new tasks keep getting added. Another important reason for using micro-tasks is to ensure consistent ordering of tasks as well as simultaneously reducing the risk of delays caused by users. Syntax: Adding micro-tasks: queueMicrotask(() => { // Code to be run inside the micro-task }); The micro-task function itself takes no parameters, and does not return a value. Examples: process.nextTick, Promises, queueMicrotask, MutationObserver Macro-tasks within an event loop: Macro-task represents some discrete and independent work. These are always the execution of the JavaScript code and micro-task queue is empty. Macro-task queue is often considered the same as the task queue or the event queue. However, the macro-task queue works the same as the task queue. The only small difference between the two is that the task queue is used for synchronous statements whereas the macro-task queue is used for asynchronous statements. In JavaScript, no code is allowed to execute until an event has occurred. {It is worth mentioning that the execution of a JavaScript code execution is itself a macro-task.} The event is queued as a macro-task. When a (macro) task, present in the macro-task queue is being executed, new events may be registered and in turn created and added to the queue. Up on initialization, the JavaScript engine first pulls off the first task in the macro-task queue and executes the callback handler. The JavaScript engine then sends these asynchronous functions to the API module, and the module pushes them to the macro-task queue at the right time. Once inside the macro-task queue, each macro-task is required to wait for next round of event loop. In this way, the code is executed. All micro-tasks logged are processed in one fell swoop in a single macro-task execution cycle. In comparison, the macro-task queue has a lower priority. Macro-tasks include parsing HTML, generating DOM, executing main thread JavaScript code and other events such as page loading, input, network events, timer events, etc. Examples: setTimeout, setInterval, setImmediate, requestAnimationFrame, I/O, UI Rendering sumitgumber28 JavaScript-Misc Picked JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Difference Between PUT and PATCH Request How to append HTML code to a div using JavaScript ? Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Feb, 2022" }, { "code": null, "e": 452, "s": 28, "text": "Event Loop: An Event Loop in JavaScript is said to be a constantly running process which keeps a tab on the call stack. Its main function is to check whether the call stack is empty or not. If the call stack turns out to be empty, the event loop proceeds to execute all the callbacks waiting in the task queue. Inside the task queue, the tasks are broadly classified into two categories, namely micro-tasks and macro-tasks." }, { "code": null, "e": 831, "s": 452, "text": "Micro-tasks within an event loop: A micro-task is said to be a function which is executed after the function or program which created it exits and only if the JavaScript execution stack is empty, but before returning control to the event loop being used by the user agent to drive the script’s execution environment. A Micro-task is also capable of en-queuing other micro-tasks." }, { "code": null, "e": 1252, "s": 831, "text": "Micro-tasks are often scheduled for things that are required to be completed immediately after the execution of the current script. On completion of one macro-task, the event loop moves on to the micro-task queue. The event loop does not move to the next task outside of the micro-task queue until the all the tasks inside the micro-task queue are completed. This implies that the micro-task queue has a higher priority." }, { "code": null, "e": 1660, "s": 1252, "text": "Once all the tasks inside the micro-task queue are finished, only then does the event loop shifts back to the macro-task queue. The primary reason for prioritizing the micro-task queue is to improve the user experience. The micro-task queue is processed after callbacks given that any other JavaScript is not under mid-execution. Micro-tasks include mutation observer callbacks as well as promise callbacks." }, { "code": null, "e": 2146, "s": 1660, "text": "In such a case wherein new micro-tasks are being added to the queue, these additional micro-tasks are added at the end of the micro-queue and these are also processed. This is because the event loop will keeps on calling micro-tasks until there are no more micro-tasks left in the queue, even if new tasks keep getting added. Another important reason for using micro-tasks is to ensure consistent ordering of tasks as well as simultaneously reducing the risk of delays caused by users." }, { "code": null, "e": 2174, "s": 2146, "text": "Syntax: Adding micro-tasks:" }, { "code": null, "e": 2246, "s": 2174, "text": "queueMicrotask(() => {\n // Code to be run inside the micro-task \n});" }, { "code": null, "e": 2327, "s": 2246, "text": "The micro-task function itself takes no parameters, and does not return a value." }, { "code": null, "e": 2398, "s": 2327, "text": "Examples: process.nextTick, Promises, queueMicrotask, MutationObserver" }, { "code": null, "e": 2889, "s": 2398, "text": "Macro-tasks within an event loop: Macro-task represents some discrete and independent work. These are always the execution of the JavaScript code and micro-task queue is empty. Macro-task queue is often considered the same as the task queue or the event queue. However, the macro-task queue works the same as the task queue. The only small difference between the two is that the task queue is used for synchronous statements whereas the macro-task queue is used for asynchronous statements." }, { "code": null, "e": 3245, "s": 2889, "text": "In JavaScript, no code is allowed to execute until an event has occurred. {It is worth mentioning that the execution of a JavaScript code execution is itself a macro-task.} The event is queued as a macro-task. When a (macro) task, present in the macro-task queue is being executed, new events may be registered and in turn created and added to the queue. " }, { "code": null, "e": 3665, "s": 3245, "text": "Up on initialization, the JavaScript engine first pulls off the first task in the macro-task queue and executes the callback handler. The JavaScript engine then sends these asynchronous functions to the API module, and the module pushes them to the macro-task queue at the right time. Once inside the macro-task queue, each macro-task is required to wait for next round of event loop. In this way, the code is executed." }, { "code": null, "e": 3988, "s": 3665, "text": "All micro-tasks logged are processed in one fell swoop in a single macro-task execution cycle. In comparison, the macro-task queue has a lower priority. Macro-tasks include parsing HTML, generating DOM, executing main thread JavaScript code and other events such as page loading, input, network events, timer events, etc. " }, { "code": null, "e": 4078, "s": 3988, "text": "Examples: setTimeout, setInterval, setImmediate, requestAnimationFrame, I/O, UI Rendering" }, { "code": null, "e": 4092, "s": 4078, "text": "sumitgumber28" }, { "code": null, "e": 4108, "s": 4092, "text": "JavaScript-Misc" }, { "code": null, "e": 4115, "s": 4108, "text": "Picked" }, { "code": null, "e": 4126, "s": 4115, "text": "JavaScript" }, { "code": null, "e": 4143, "s": 4126, "text": "Web Technologies" }, { "code": null, "e": 4241, "s": 4143, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4302, "s": 4241, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 4374, "s": 4302, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 4414, "s": 4374, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 4455, "s": 4414, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 4507, "s": 4455, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 4540, "s": 4507, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 4602, "s": 4540, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 4663, "s": 4602, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 4713, "s": 4663, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
How to display count of notifications in Android app launcher icon?
This example demonstrate about How to display count of notifications in Android app launcher icon. 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" ?7gt; <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:onClick = "createNotification" android:text = "create notification" android:layout_centerInParent = "true" android:layout_width = "match_parent" android:layout_height = "wrap_content" /> </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 static android.app.Notification. BADGE_ICON_SMALL ; public class MainActivity extends AppCompatActivity { static int count = 0 ; public static final String NOTIFICATION_CHANNEL_ID = "10001" ; private final static String default_notification_channel_id = "default" ; @Override protected void onResume () { super .onResume() ; count = 0 ; } @Override protected void onCreate (Bundle savedInstanceState) { super .onCreate(savedInstanceState) ; setContentView(R.layout. activity_main ) ; } public void createNotification (View view) { count ++ ; 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(getApplicationContext() , default_notification_channel_id ) ; mBuilder.setContentTitle( "My Notification" ) ; mBuilder.setContentIntent(pendingIntent) ; mBuilder.setContentText( "Notification Listener Service Example" ) ; mBuilder.setSmallIcon(R.drawable. ic_launcher_foreground ) ; mBuilder.setAutoCancel( true ) ; mBuilder.setBadgeIconType( BADGE_ICON_SMALL ) ; mBuilder.setNumber( count ) ; 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 4 − Add the following code to AndroidManifest.xml <? xml version = "1.0" encoding = "utf-8" ?> <manifest xmlns: android = "http://schemas.android.com/apk/res/android" package = "app.tutorialspoint.com.notifyme" > <uses-permission android :name = "android.permission.VIBRATE" /> <uses-permission android :name = "android.permission.RECEIVE_BOOT_COMPLETED" /> <application android :allowBacku p= "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": 1286, "s": 1187, "text": "This example demonstrate about How to display count of notifications in Android app launcher icon." }, { "code": null, "e": 1415, "s": 1286, "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": 1480, "s": 1415, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2059, "s": 1480, "text": "<? xml version = \"1.0\" encoding = \"utf-8\" ?7gt;\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:onClick = \"createNotification\"\n android:text = \"create notification\"\n android:layout_centerInParent = \"true\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\" />\n</RelativeLayout>" }, { "code": null, "e": 2112, "s": 2059, "text": "Step 3 − Add the following code to src/MainActivity." }, { "code": null, "e": 4688, "s": 2112, "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 static android.app.Notification. BADGE_ICON_SMALL ;\npublic class MainActivity extends AppCompatActivity {\n static int count = 0 ;\n public static final String NOTIFICATION_CHANNEL_ID = \"10001\" ;\n private final static String default_notification_channel_id = \"default\" ;\n @Override\n protected void onResume () {\n super .onResume() ;\n count = 0 ;\n }\n @Override\n protected void onCreate (Bundle savedInstanceState) {\n super .onCreate(savedInstanceState) ;\n setContentView(R.layout. activity_main ) ;\n }\n public void createNotification (View view) {\n count ++ ;\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(getApplicationContext() , default_notification_channel_id ) ;\n mBuilder.setContentTitle( \"My Notification\" ) ;\n mBuilder.setContentIntent(pendingIntent) ;\n mBuilder.setContentText( \"Notification Listener Service Example\" ) ;\n mBuilder.setSmallIcon(R.drawable. ic_launcher_foreground ) ;\n mBuilder.setAutoCancel( true ) ;\n mBuilder.setBadgeIconType( BADGE_ICON_SMALL ) ;\n mBuilder.setNumber( count ) ;\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": 4743, "s": 4688, "text": "Step 4 − Add the following code to AndroidManifest.xml" }, { "code": null, "e": 5625, "s": 4743, "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 <uses-permission android :name = \"android.permission.RECEIVE_BOOT_COMPLETED\" />\n <application\n android :allowBacku p= \"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": 5970, "s": 5625, "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": 6012, "s": 5970, "text": "Click here to download the project code" } ]
Lodash _.sumBy() Method
05 Sep, 2020 Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc. The _.sumBy() method is used to compute the sum from the original array by iterating over each element in the array by using the Iteratee function. It is almost the same as _.sum() method. Syntax: _.sumBy(array, [iteratee = _.identity]) Parameters: This method accepts two parameters as mentioned above and described below: array: This parameter holds the array to iterate over. [iteratee = _.identity]: This parameter holds the iteratee invoked per element. Return Value: This method returns the sum. Example 1: Here, const _ = require(‘lodash’) is used to import the lodash library into the file. Javascript // Requiring the lodash library const _ = require("lodash"); // Original array var arr = [{ 'n': 4 }, { 'n': 2 }, { 'n': 6 }]; // Use of _.sumBy() // method let gfg = _.sumBy(arr, function(o) { return o.n; }); // Printing the output console.log(gfg); Output: 12 Example 2: Javascript // Requiring the lodash library const _ = require("lodash"); // Original array var arr = [{ 'n': 10 }, { 'n': 5 }, { 'n': 3 }, { 'n': 12 }]; // Use of _.sumBy() // method let gfg = _.sumBy(arr, 'n'); // Printing the output console.log(gfg); Output: 30 JavaScript-Lodash JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Remove elements from a JavaScript Array Difference Between PUT and PATCH Request Roadmap to Learn JavaScript For Beginners JavaScript | Promises Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Sep, 2020" }, { "code": null, "e": 168, "s": 28, "text": "Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc." }, { "code": null, "e": 357, "s": 168, "text": "The _.sumBy() method is used to compute the sum from the original array by iterating over each element in the array by using the Iteratee function. It is almost the same as _.sum() method." }, { "code": null, "e": 365, "s": 357, "text": "Syntax:" }, { "code": null, "e": 405, "s": 365, "text": "_.sumBy(array, [iteratee = _.identity])" }, { "code": null, "e": 492, "s": 405, "text": "Parameters: This method accepts two parameters as mentioned above and described below:" }, { "code": null, "e": 547, "s": 492, "text": "array: This parameter holds the array to iterate over." }, { "code": null, "e": 628, "s": 547, "text": "[iteratee = _.identity]: This parameter holds the iteratee invoked per element." }, { "code": null, "e": 671, "s": 628, "text": "Return Value: This method returns the sum." }, { "code": null, "e": 768, "s": 671, "text": "Example 1: Here, const _ = require(‘lodash’) is used to import the lodash library into the file." }, { "code": null, "e": 779, "s": 768, "text": "Javascript" }, { "code": "// Requiring the lodash library const _ = require(\"lodash\"); // Original array var arr = [{ 'n': 4 }, { 'n': 2 }, { 'n': 6 }]; // Use of _.sumBy() // method let gfg = _.sumBy(arr, function(o) { return o.n; }); // Printing the output console.log(gfg);", "e": 1050, "s": 779, "text": null }, { "code": null, "e": 1058, "s": 1050, "text": "Output:" }, { "code": null, "e": 1061, "s": 1058, "text": "12" }, { "code": null, "e": 1074, "s": 1061, "text": "Example 2: " }, { "code": null, "e": 1085, "s": 1074, "text": "Javascript" }, { "code": "// Requiring the lodash library const _ = require(\"lodash\"); // Original array var arr = [{ 'n': 10 }, { 'n': 5 }, { 'n': 3 }, { 'n': 12 }]; // Use of _.sumBy() // method let gfg = _.sumBy(arr, 'n'); // Printing the output console.log(gfg);", "e": 1346, "s": 1085, "text": null }, { "code": null, "e": 1354, "s": 1346, "text": "Output:" }, { "code": null, "e": 1357, "s": 1354, "text": "30" }, { "code": null, "e": 1375, "s": 1357, "text": "JavaScript-Lodash" }, { "code": null, "e": 1386, "s": 1375, "text": "JavaScript" }, { "code": null, "e": 1403, "s": 1386, "text": "Web Technologies" }, { "code": null, "e": 1501, "s": 1403, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1562, "s": 1501, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1602, "s": 1562, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 1643, "s": 1602, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 1685, "s": 1643, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 1707, "s": 1685, "text": "JavaScript | Promises" }, { "code": null, "e": 1740, "s": 1707, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 1802, "s": 1740, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 1863, "s": 1802, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1913, "s": 1863, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Introduction to Perl
11 Sep, 2019 Perl is a general-purpose, high level interpreted and dynamic programming language. It was developed by Larry Wall, in 1987. There is no official Full form of the Perl, but still, the most used expansion is “Practical Extraction and Reporting Language“. Some of the programmers also refer Perl as the “Pathologically Eclectic Rubbish Lister” Or “Practically Everything Really Likable“. The acronym “Practical Extraction and Reporting Language” is used widely because Perl was originally developed for the text processing like extracting the required information from a specified text file and for converting the text file into a different form. Perl supports both the procedural and Object-Oriented programming. Perl is a lot similar to C syntactically and is easy for the users who have knowledge of C, C++. Evolution of Perl: It all started when Larry Wall was working on a task to generate the reports from a lot of text files which have cross-references. Then he started to use awk for this task but soon he found that it is not sufficient for this task. So instead of writing a utility for this task, he wrote a new language i.e. Perl and also wrote the interpreter for it. He wrote the language Perl in C and some of the concepts are taken from awk, sed, and LISP etc. At the beginning level, Perl was developed only for the system management and text handling but in later versions, Perl got the ability to handle regular expressions, and network sockets etc. In present Perl is popular for its ability to handling the Regex(Regular Expressions). The first version of Perl was 1.0 which released on December 18, 1987. The latest version of Perl is 5.28. Perl 6 is different from Perl 5 because it is a fully object-oriented reimplementation of Perl 5. Why Perl? Perl has many reasons for being popular and in demand. Few of the reasons are mentioned below: Easy to start: Perl is a high-level language so it is closer to other popular programming languages like C, C++ and thus, becomes easy to learn for anyone. Text-Processing: As the acronym “Practical Extraction and Reporting Language” suggest that Perl has the high text manipulation abilities by which it can generate reports from different text files easily. Also, it can convert the files into some another form. Contained best Features: Perl contains the features of different languages like C, sed, awk, and sh etc. which makes the Perl more useful and productive. System Administration: Due to having the different scripting languages capabilities Perl make the task of system administration very easy. Instead of becoming dependent on many languages, just use Perl to complete out the whole task of system administration. In Spite of this Perl also used in web programming, web automation, GUI programming etc. Web and Perl: Perl can be embedded into web servers to increase its processing power and it has the DBI package, which makes web-database integration very easy. Beginning with Perl Programming: Finding a Interpreter: There are various online IDEs which can be used to run Perl programs without installing. Windows: There are various IDEs to run Perl programs or scripts: Padre, Eclipse with EPIC plugin etc. Programming in Perl Since the Perl is a lot similar to other widely used languages syntactically, it is easier to code and learn in Perl. Programs can be written in Perl in any of the widely used text editors like Notepad++, gedit etc. After writing the program save the file with the extension .pl or .PL To run the program use perl file_name.pl on the command line. Example: A simple program to print Welcome to GFG! # Perl program to print Welcome to GFG!#!/usr/bin/perl # Below line will print "Welcome to GFG!"print "Welcome to GFG!\n"; Output: Welcome to GFG! Comments: Comments are used for enhancing the readability of the code. The interpreter will ignore the comment entries and does not execute them. Comments can be of the single line or multiple lines. Single line Comment:Syntax:# Single line comment Syntax: # Single line comment Multi-line comment:Syntax:= Multi line comments Line start from = is interpreted as the starting of multiline comment and =cut is consider as the end of multiline comment =cut Syntax: = Multi line comments Line start from = is interpreted as the starting of multiline comment and =cut is consider as the end of multiline comment =cut print: It is a function in Perl to show the result or any specified output on the console. Quotes: In Perl, you can use either single quotes(‘’)or double quotes(“”). Using single quotes will not interpolate any variable or special character but using double quotes will interpolates. \n: It is used for the new line character which uses the backslash (\) character to escape any type of character. /usr/bin/perl: It is actual Perl interpreter binary which always starts with #!. This is used in the Perl Script Mode Programming. Note: Perl is case sensitive programming language and that’s why $Geeks and $geeks are two different identifiers. Advantages of Perl: Perl Provides supports for cross platform and it is compatible with mark-up languages like HTML, XML etc. It is very efficient in text-manipulation i.e. Regular Expression. It also provides the socket capability. It is free and a Open Source software which is licensed under Artistic and GNU General Public License (GPL). It is an embeddable language that’s why it can embed in web servers and database servers. It supports more than 25, 000 open source modules on CPAN(Comprehensive Perl Archive Network) which provide many powerful extensions to the standard library. For example, XML processing, GUI(Graphical User Interface) and DI(Database Integration) etc. Disadvantages of Perl: Perl doesn’t supports portability due to CPAN modules. Programs runs slowly and program needs to be interpreted each time when any changes are made. In Perl, the same result can be achieved in several different ways which make the code untidy as well as unreadable. Usability factor is lower when compared to other languages. Applications: One of the major application of Perl language is to processing of text files and analysis of the strings. Perl also used for CGI( Common Gateway Interface) scripts. Used in web development, GUI(Graphical User Interface) development. Perl’s text-handling capabilities is also used for generating SQL queries. perl-basics Perl Perl Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Perl | split() Function Perl | push() Function Perl | chomp() Function Perl | substr() function Perl | grep() Function Perl | exists() Function Perl Tutorial - Learn Perl With Examples Perl | Subroutines or Functions Perl | length() Function Use of print() and say() in Perl
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Sep, 2019" }, { "code": null, "e": 673, "s": 28, "text": "Perl is a general-purpose, high level interpreted and dynamic programming language. It was developed by Larry Wall, in 1987. There is no official Full form of the Perl, but still, the most used expansion is “Practical Extraction and Reporting Language“. Some of the programmers also refer Perl as the “Pathologically Eclectic Rubbish Lister” Or “Practically Everything Really Likable“. The acronym “Practical Extraction and Reporting Language” is used widely because Perl was originally developed for the text processing like extracting the required information from a specified text file and for converting the text file into a different form." }, { "code": null, "e": 837, "s": 673, "text": "Perl supports both the procedural and Object-Oriented programming. Perl is a lot similar to C syntactically and is easy for the users who have knowledge of C, C++." }, { "code": null, "e": 856, "s": 837, "text": "Evolution of Perl:" }, { "code": null, "e": 1787, "s": 856, "text": "It all started when Larry Wall was working on a task to generate the reports from a lot of text files which have cross-references. Then he started to use awk for this task but soon he found that it is not sufficient for this task. So instead of writing a utility for this task, he wrote a new language i.e. Perl and also wrote the interpreter for it. He wrote the language Perl in C and some of the concepts are taken from awk, sed, and LISP etc. At the beginning level, Perl was developed only for the system management and text handling but in later versions, Perl got the ability to handle regular expressions, and network sockets etc. In present Perl is popular for its ability to handling the Regex(Regular Expressions). The first version of Perl was 1.0 which released on December 18, 1987. The latest version of Perl is 5.28. Perl 6 is different from Perl 5 because it is a fully object-oriented reimplementation of Perl 5." }, { "code": null, "e": 1797, "s": 1787, "text": "Why Perl?" }, { "code": null, "e": 1892, "s": 1797, "text": "Perl has many reasons for being popular and in demand. Few of the reasons are mentioned below:" }, { "code": null, "e": 2048, "s": 1892, "text": "Easy to start: Perl is a high-level language so it is closer to other popular programming languages like C, C++ and thus, becomes easy to learn for anyone." }, { "code": null, "e": 2307, "s": 2048, "text": "Text-Processing: As the acronym “Practical Extraction and Reporting Language” suggest that Perl has the high text manipulation abilities by which it can generate reports from different text files easily. Also, it can convert the files into some another form." }, { "code": null, "e": 2461, "s": 2307, "text": "Contained best Features: Perl contains the features of different languages like C, sed, awk, and sh etc. which makes the Perl more useful and productive." }, { "code": null, "e": 2809, "s": 2461, "text": "System Administration: Due to having the different scripting languages capabilities Perl make the task of system administration very easy. Instead of becoming dependent on many languages, just use Perl to complete out the whole task of system administration. In Spite of this Perl also used in web programming, web automation, GUI programming etc." }, { "code": null, "e": 2970, "s": 2809, "text": "Web and Perl: Perl can be embedded into web servers to increase its processing power and it has the DBI package, which makes web-database integration very easy." }, { "code": null, "e": 3003, "s": 2970, "text": "Beginning with Perl Programming:" }, { "code": null, "e": 3115, "s": 3003, "text": "Finding a Interpreter: There are various online IDEs which can be used to run Perl programs without installing." }, { "code": null, "e": 3217, "s": 3115, "text": "Windows: There are various IDEs to run Perl programs or scripts: Padre, Eclipse with EPIC plugin etc." }, { "code": null, "e": 3237, "s": 3217, "text": "Programming in Perl" }, { "code": null, "e": 3585, "s": 3237, "text": "Since the Perl is a lot similar to other widely used languages syntactically, it is easier to code and learn in Perl. Programs can be written in Perl in any of the widely used text editors like Notepad++, gedit etc. After writing the program save the file with the extension .pl or .PL To run the program use perl file_name.pl on the command line." }, { "code": null, "e": 3636, "s": 3585, "text": "Example: A simple program to print Welcome to GFG!" }, { "code": "# Perl program to print Welcome to GFG!#!/usr/bin/perl # Below line will print \"Welcome to GFG!\"print \"Welcome to GFG!\\n\";", "e": 3760, "s": 3636, "text": null }, { "code": null, "e": 3768, "s": 3760, "text": "Output:" }, { "code": null, "e": 3784, "s": 3768, "text": "Welcome to GFG!" }, { "code": null, "e": 3984, "s": 3784, "text": "Comments: Comments are used for enhancing the readability of the code. The interpreter will ignore the comment entries and does not execute them. Comments can be of the single line or multiple lines." }, { "code": null, "e": 4033, "s": 3984, "text": "Single line Comment:Syntax:# Single line comment" }, { "code": null, "e": 4041, "s": 4033, "text": "Syntax:" }, { "code": null, "e": 4063, "s": 4041, "text": "# Single line comment" }, { "code": null, "e": 4241, "s": 4063, "text": "Multi-line comment:Syntax:= Multi line comments\nLine start from = is interpreted as the\nstarting of multiline comment and =cut is \nconsider as the end of multiline comment\n=cut" }, { "code": null, "e": 4249, "s": 4241, "text": "Syntax:" }, { "code": null, "e": 4401, "s": 4249, "text": "= Multi line comments\nLine start from = is interpreted as the\nstarting of multiline comment and =cut is \nconsider as the end of multiline comment\n=cut" }, { "code": null, "e": 4492, "s": 4401, "text": "print: It is a function in Perl to show the result or any specified output on the console." }, { "code": null, "e": 4685, "s": 4492, "text": "Quotes: In Perl, you can use either single quotes(‘’)or double quotes(“”). Using single quotes will not interpolate any variable or special character but using double quotes will interpolates." }, { "code": null, "e": 4799, "s": 4685, "text": "\\n: It is used for the new line character which uses the backslash (\\) character to escape any type of character." }, { "code": null, "e": 4930, "s": 4799, "text": "/usr/bin/perl: It is actual Perl interpreter binary which always starts with #!. This is used in the Perl Script Mode Programming." }, { "code": null, "e": 5044, "s": 4930, "text": "Note: Perl is case sensitive programming language and that’s why $Geeks and $geeks are two different identifiers." }, { "code": null, "e": 5064, "s": 5044, "text": "Advantages of Perl:" }, { "code": null, "e": 5170, "s": 5064, "text": "Perl Provides supports for cross platform and it is compatible with mark-up languages like HTML, XML etc." }, { "code": null, "e": 5277, "s": 5170, "text": "It is very efficient in text-manipulation i.e. Regular Expression. It also provides the socket capability." }, { "code": null, "e": 5386, "s": 5277, "text": "It is free and a Open Source software which is licensed under Artistic and GNU General Public License (GPL)." }, { "code": null, "e": 5476, "s": 5386, "text": "It is an embeddable language that’s why it can embed in web servers and database servers." }, { "code": null, "e": 5727, "s": 5476, "text": "It supports more than 25, 000 open source modules on CPAN(Comprehensive Perl Archive Network) which provide many powerful extensions to the standard library. For example, XML processing, GUI(Graphical User Interface) and DI(Database Integration) etc." }, { "code": null, "e": 5750, "s": 5727, "text": "Disadvantages of Perl:" }, { "code": null, "e": 5805, "s": 5750, "text": "Perl doesn’t supports portability due to CPAN modules." }, { "code": null, "e": 5899, "s": 5805, "text": "Programs runs slowly and program needs to be interpreted each time when any changes are made." }, { "code": null, "e": 6016, "s": 5899, "text": "In Perl, the same result can be achieved in several different ways which make the code untidy as well as unreadable." }, { "code": null, "e": 6076, "s": 6016, "text": "Usability factor is lower when compared to other languages." }, { "code": null, "e": 6090, "s": 6076, "text": "Applications:" }, { "code": null, "e": 6196, "s": 6090, "text": "One of the major application of Perl language is to processing of text files and analysis of the strings." }, { "code": null, "e": 6255, "s": 6196, "text": "Perl also used for CGI( Common Gateway Interface) scripts." }, { "code": null, "e": 6323, "s": 6255, "text": "Used in web development, GUI(Graphical User Interface) development." }, { "code": null, "e": 6398, "s": 6323, "text": "Perl’s text-handling capabilities is also used for generating SQL queries." }, { "code": null, "e": 6410, "s": 6398, "text": "perl-basics" }, { "code": null, "e": 6415, "s": 6410, "text": "Perl" }, { "code": null, "e": 6420, "s": 6415, "text": "Perl" }, { "code": null, "e": 6518, "s": 6420, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6542, "s": 6518, "text": "Perl | split() Function" }, { "code": null, "e": 6565, "s": 6542, "text": "Perl | push() Function" }, { "code": null, "e": 6589, "s": 6565, "text": "Perl | chomp() Function" }, { "code": null, "e": 6614, "s": 6589, "text": "Perl | substr() function" }, { "code": null, "e": 6637, "s": 6614, "text": "Perl | grep() Function" }, { "code": null, "e": 6662, "s": 6637, "text": "Perl | exists() Function" }, { "code": null, "e": 6703, "s": 6662, "text": "Perl Tutorial - Learn Perl With Examples" }, { "code": null, "e": 6735, "s": 6703, "text": "Perl | Subroutines or Functions" }, { "code": null, "e": 6760, "s": 6735, "text": "Perl | length() Function" } ]
Creating a Camera Application using Pyqt5
23 Dec, 2021 Prerequisite: Introduction to pyqt-5 PyQt5 is a cross-platform GUI toolkit, a set of python bindings for Qt v5. One can develop an interactive desktop application with so much ease because of the tools and simplicity provided by this library. In this article, we will see how we can create a simple camera application using PyQt5, which will capture the images and save them in the desired location which can be changed any time. Create the main window.Add QCameraViewfinder object as the central widget to the main window.Add a status bar to the window for status tips. Add the toolbar to the window. Add Click and change location actions to the toolbar, and a combo box for selecting the camera, below is how toolbar will look like. Create the main window. Add QCameraViewfinder object as the central widget to the main window. Add a status bar to the window for status tips. Add the toolbar to the window. Add Click and change location actions to the toolbar, and a combo box for selecting the camera, below is how toolbar will look like. Create a path variable and set it currently to blank. Add available cameras to the combo box and set the first camera as default. Add action to the Take Photo button. Inside the click action, capture the photo at the given path with name as a timestamp and increment the count.Add action to the change location button.Inside the change location action, open the dialog box to get the path and update the path and the counter.Add action to the combo box.Inside the combo, box action get the selected camera, set viewfinder to it, and the mode of capture. Create an alert method that shows an error message if any error is shown while selecting the path and changing the camera. Create a path variable and set it currently to blank. Add available cameras to the combo box and set the first camera as default. Add action to the Take Photo button. Inside the click action, capture the photo at the given path with name as a timestamp and increment the count. Add action to the change location button. Inside the change location action, open the dialog box to get the path and update the path and the counter. Add action to the combo box. Inside the combo, box action get the selected camera, set viewfinder to it, and the mode of capture. Create an alert method that shows an error message if any error is shown while selecting the path and changing the camera. Below is the implementation : Python3 # importing required librariesfrom PyQt5.QtWidgets import *from PyQt5.QtMultimedia import *from PyQt5.QtMultimediaWidgets import *import osimport sysimport time # Main window classclass MainWindow(QMainWindow): # constructor def __init__(self): super().__init__() # setting geometry self.setGeometry(100, 100, 800, 600) # setting style sheet self.setStyleSheet("background : lightgrey;") # getting available cameras self.available_cameras = QCameraInfo.availableCameras() # if no camera found if not self.available_cameras: # exit the code sys.exit() # creating a status bar self.status = QStatusBar() # setting style sheet to the status bar self.status.setStyleSheet("background : white;") # adding status bar to the main window self.setStatusBar(self.status) # path to save self.save_path = "" # creating a QCameraViewfinder object self.viewfinder = QCameraViewfinder() # showing this viewfinder self.viewfinder.show() # making it central widget of main window self.setCentralWidget(self.viewfinder) # Set the default camera. self.select_camera(0) # creating a tool bar toolbar = QToolBar("Camera Tool Bar") # adding tool bar to main window self.addToolBar(toolbar) # creating a photo action to take photo click_action = QAction("Click photo", self) # adding status tip to the photo action click_action.setStatusTip("This will capture picture") # adding tool tip click_action.setToolTip("Capture picture") # adding action to it # calling take_photo method click_action.triggered.connect(self.click_photo) # adding this to the tool bar toolbar.addAction(click_action) # similarly creating action for changing save folder change_folder_action = QAction("Change save location", self) # adding status tip change_folder_action.setStatusTip("Change folder where picture will be saved saved.") # adding tool tip to it change_folder_action.setToolTip("Change save location") # setting calling method to the change folder action # when triggered signal is emitted change_folder_action.triggered.connect(self.change_folder) # adding this to the tool bar toolbar.addAction(change_folder_action) # creating a combo box for selecting camera camera_selector = QComboBox() # adding status tip to it camera_selector.setStatusTip("Choose camera to take pictures") # adding tool tip to it camera_selector.setToolTip("Select Camera") camera_selector.setToolTipDuration(2500) # adding items to the combo box camera_selector.addItems([camera.description() for camera in self.available_cameras]) # adding action to the combo box # calling the select camera method camera_selector.currentIndexChanged.connect(self.select_camera) # adding this to tool bar toolbar.addWidget(camera_selector) # setting tool bar stylesheet toolbar.setStyleSheet("background : white;") # setting window title self.setWindowTitle("PyQt5 Cam") # showing the main window self.show() # method to select camera def select_camera(self, i): # getting the selected camera self.camera = QCamera(self.available_cameras[i]) # setting view finder to the camera self.camera.setViewfinder(self.viewfinder) # setting capture mode to the camera self.camera.setCaptureMode(QCamera.CaptureStillImage) # if any error occur show the alert self.camera.error.connect(lambda: self.alert(self.camera.errorString())) # start the camera self.camera.start() # creating a QCameraImageCapture object self.capture = QCameraImageCapture(self.camera) # showing alert if error occur self.capture.error.connect(lambda error_msg, error, msg: self.alert(msg)) # when image captured showing message self.capture.imageCaptured.connect(lambda d, i: self.status.showMessage("Image captured : " + str(self.save_seq))) # getting current camera name self.current_camera_name = self.available_cameras[i].description() # initial save sequence self.save_seq = 0 # method to take photo def click_photo(self): # time stamp timestamp = time.strftime("%d-%b-%Y-%H_%M_%S") # capture the image and save it on the save path self.capture.capture(os.path.join(self.save_path, "%s-%04d-%s.jpg" % ( self.current_camera_name, self.save_seq, timestamp ))) # increment the sequence self.save_seq += 1 # change folder method def change_folder(self): # open the dialog to select path path = QFileDialog.getExistingDirectory(self, "Picture Location", "") # if path is selected if path: # update the path self.save_path = path # update the sequence self.save_seq = 0 # method for alerts def alert(self, msg): # error message error = QErrorMessage(self) # setting text to the error message error.showMessage(msg) # Driver codeif __name__ == "__main__" : # create pyqt5 app App = QApplication(sys.argv) # create the instance of our Window window = MainWindow() # start the app sys.exit(App.exec()) Output : When we click on the change location, this dialog will appear Let’s go to this folder and see if the images are captured or not ruhelaa48 Python-projects Python-PyQt Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Rotate axis tick labels in Seaborn and Matplotlib Enumerate() in Python Deque in Python Stack in Python Python Dictionary sum() function in Python Print lists in Python (5 Different Ways) Different ways to create Pandas Dataframe Queue in Python Defaultdict in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Dec, 2021" }, { "code": null, "e": 65, "s": 28, "text": "Prerequisite: Introduction to pyqt-5" }, { "code": null, "e": 271, "s": 65, "text": "PyQt5 is a cross-platform GUI toolkit, a set of python bindings for Qt v5. One can develop an interactive desktop application with so much ease because of the tools and simplicity provided by this library." }, { "code": null, "e": 458, "s": 271, "text": "In this article, we will see how we can create a simple camera application using PyQt5, which will capture the images and save them in the desired location which can be changed any time." }, { "code": null, "e": 764, "s": 458, "text": "Create the main window.Add QCameraViewfinder object as the central widget to the main window.Add a status bar to the window for status tips. Add the toolbar to the window. Add Click and change location actions to the toolbar, and a combo box for selecting the camera, below is how toolbar will look like. " }, { "code": null, "e": 788, "s": 764, "text": "Create the main window." }, { "code": null, "e": 859, "s": 788, "text": "Add QCameraViewfinder object as the central widget to the main window." }, { "code": null, "e": 908, "s": 859, "text": "Add a status bar to the window for status tips. " }, { "code": null, "e": 940, "s": 908, "text": "Add the toolbar to the window. " }, { "code": null, "e": 1074, "s": 940, "text": "Add Click and change location actions to the toolbar, and a combo box for selecting the camera, below is how toolbar will look like. " }, { "code": null, "e": 1752, "s": 1074, "text": "Create a path variable and set it currently to blank. Add available cameras to the combo box and set the first camera as default. Add action to the Take Photo button. Inside the click action, capture the photo at the given path with name as a timestamp and increment the count.Add action to the change location button.Inside the change location action, open the dialog box to get the path and update the path and the counter.Add action to the combo box.Inside the combo, box action get the selected camera, set viewfinder to it, and the mode of capture. Create an alert method that shows an error message if any error is shown while selecting the path and changing the camera. " }, { "code": null, "e": 1807, "s": 1752, "text": "Create a path variable and set it currently to blank. " }, { "code": null, "e": 1884, "s": 1807, "text": "Add available cameras to the combo box and set the first camera as default. " }, { "code": null, "e": 1922, "s": 1884, "text": "Add action to the Take Photo button. " }, { "code": null, "e": 2033, "s": 1922, "text": "Inside the click action, capture the photo at the given path with name as a timestamp and increment the count." }, { "code": null, "e": 2075, "s": 2033, "text": "Add action to the change location button." }, { "code": null, "e": 2183, "s": 2075, "text": "Inside the change location action, open the dialog box to get the path and update the path and the counter." }, { "code": null, "e": 2212, "s": 2183, "text": "Add action to the combo box." }, { "code": null, "e": 2314, "s": 2212, "text": "Inside the combo, box action get the selected camera, set viewfinder to it, and the mode of capture. " }, { "code": null, "e": 2438, "s": 2314, "text": "Create an alert method that shows an error message if any error is shown while selecting the path and changing the camera. " }, { "code": null, "e": 2468, "s": 2438, "text": "Below is the implementation :" }, { "code": null, "e": 2476, "s": 2468, "text": "Python3" }, { "code": "# importing required librariesfrom PyQt5.QtWidgets import *from PyQt5.QtMultimedia import *from PyQt5.QtMultimediaWidgets import *import osimport sysimport time # Main window classclass MainWindow(QMainWindow): # constructor def __init__(self): super().__init__() # setting geometry self.setGeometry(100, 100, 800, 600) # setting style sheet self.setStyleSheet(\"background : lightgrey;\") # getting available cameras self.available_cameras = QCameraInfo.availableCameras() # if no camera found if not self.available_cameras: # exit the code sys.exit() # creating a status bar self.status = QStatusBar() # setting style sheet to the status bar self.status.setStyleSheet(\"background : white;\") # adding status bar to the main window self.setStatusBar(self.status) # path to save self.save_path = \"\" # creating a QCameraViewfinder object self.viewfinder = QCameraViewfinder() # showing this viewfinder self.viewfinder.show() # making it central widget of main window self.setCentralWidget(self.viewfinder) # Set the default camera. self.select_camera(0) # creating a tool bar toolbar = QToolBar(\"Camera Tool Bar\") # adding tool bar to main window self.addToolBar(toolbar) # creating a photo action to take photo click_action = QAction(\"Click photo\", self) # adding status tip to the photo action click_action.setStatusTip(\"This will capture picture\") # adding tool tip click_action.setToolTip(\"Capture picture\") # adding action to it # calling take_photo method click_action.triggered.connect(self.click_photo) # adding this to the tool bar toolbar.addAction(click_action) # similarly creating action for changing save folder change_folder_action = QAction(\"Change save location\", self) # adding status tip change_folder_action.setStatusTip(\"Change folder where picture will be saved saved.\") # adding tool tip to it change_folder_action.setToolTip(\"Change save location\") # setting calling method to the change folder action # when triggered signal is emitted change_folder_action.triggered.connect(self.change_folder) # adding this to the tool bar toolbar.addAction(change_folder_action) # creating a combo box for selecting camera camera_selector = QComboBox() # adding status tip to it camera_selector.setStatusTip(\"Choose camera to take pictures\") # adding tool tip to it camera_selector.setToolTip(\"Select Camera\") camera_selector.setToolTipDuration(2500) # adding items to the combo box camera_selector.addItems([camera.description() for camera in self.available_cameras]) # adding action to the combo box # calling the select camera method camera_selector.currentIndexChanged.connect(self.select_camera) # adding this to tool bar toolbar.addWidget(camera_selector) # setting tool bar stylesheet toolbar.setStyleSheet(\"background : white;\") # setting window title self.setWindowTitle(\"PyQt5 Cam\") # showing the main window self.show() # method to select camera def select_camera(self, i): # getting the selected camera self.camera = QCamera(self.available_cameras[i]) # setting view finder to the camera self.camera.setViewfinder(self.viewfinder) # setting capture mode to the camera self.camera.setCaptureMode(QCamera.CaptureStillImage) # if any error occur show the alert self.camera.error.connect(lambda: self.alert(self.camera.errorString())) # start the camera self.camera.start() # creating a QCameraImageCapture object self.capture = QCameraImageCapture(self.camera) # showing alert if error occur self.capture.error.connect(lambda error_msg, error, msg: self.alert(msg)) # when image captured showing message self.capture.imageCaptured.connect(lambda d, i: self.status.showMessage(\"Image captured : \" + str(self.save_seq))) # getting current camera name self.current_camera_name = self.available_cameras[i].description() # initial save sequence self.save_seq = 0 # method to take photo def click_photo(self): # time stamp timestamp = time.strftime(\"%d-%b-%Y-%H_%M_%S\") # capture the image and save it on the save path self.capture.capture(os.path.join(self.save_path, \"%s-%04d-%s.jpg\" % ( self.current_camera_name, self.save_seq, timestamp ))) # increment the sequence self.save_seq += 1 # change folder method def change_folder(self): # open the dialog to select path path = QFileDialog.getExistingDirectory(self, \"Picture Location\", \"\") # if path is selected if path: # update the path self.save_path = path # update the sequence self.save_seq = 0 # method for alerts def alert(self, msg): # error message error = QErrorMessage(self) # setting text to the error message error.showMessage(msg) # Driver codeif __name__ == \"__main__\" : # create pyqt5 app App = QApplication(sys.argv) # create the instance of our Window window = MainWindow() # start the app sys.exit(App.exec())", "e": 8506, "s": 2476, "text": null }, { "code": null, "e": 8579, "s": 8506, "text": "Output : When we click on the change location, this dialog will appear " }, { "code": null, "e": 8647, "s": 8579, "text": "Let’s go to this folder and see if the images are captured or not " }, { "code": null, "e": 8659, "s": 8649, "text": "ruhelaa48" }, { "code": null, "e": 8675, "s": 8659, "text": "Python-projects" }, { "code": null, "e": 8687, "s": 8675, "text": "Python-PyQt" }, { "code": null, "e": 8694, "s": 8687, "text": "Python" }, { "code": null, "e": 8792, "s": 8694, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8842, "s": 8792, "text": "Rotate axis tick labels in Seaborn and Matplotlib" }, { "code": null, "e": 8864, "s": 8842, "text": "Enumerate() in Python" }, { "code": null, "e": 8880, "s": 8864, "text": "Deque in Python" }, { "code": null, "e": 8896, "s": 8880, "text": "Stack in Python" }, { "code": null, "e": 8914, "s": 8896, "text": "Python Dictionary" }, { "code": null, "e": 8939, "s": 8914, "text": "sum() function in Python" }, { "code": null, "e": 8980, "s": 8939, "text": "Print lists in Python (5 Different Ways)" }, { "code": null, "e": 9022, "s": 8980, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 9038, "s": 9022, "text": "Queue in Python" } ]
Create a comma separated list from an array in JavaScript
14 May, 2019 Here is a need to convert an array into an object. To do so we are going to use a few of the most preferred methods. First here is a method to know. Array join() methodThis method joins the elements of the array to form a string and returns the new string.The elements of the array will be separated by a specified separator. If not specified, Default separator comma (, ) is used.Syntax:array.join(separator) Parameters:separator:This parameter is optional. It specifies the separator to be used. If not used, Separated Comma(, ) is used.Return value:A String, containing the array values, separated by the specified separator. array.join(separator) Parameters: separator:This parameter is optional. It specifies the separator to be used. If not used, Separated Comma(, ) is used. Return value:A String, containing the array values, separated by the specified separator. Array toString() methodThis method converts an array into a String and returns the new string.Syntax:array.toString() Return value:It returns a string which represents the values of the array, separated by a comma. array.toString() Return value:It returns a string which represents the values of the array, separated by a comma. Example-1: This example joins the element of the array by join() method using comma(, ). <!DOCTYPE html><html> <head> <title> JavaScript | Create comma separated list from an array. </title></head> <body style="text-align:center;" id="body"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 16px; font-weight: bold;"> </p> <button onclick="gfg_Run()"> click here </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 arr = ["GFG1", "GFG2", "GFG3"]; el_up.innerHTML = 'Original Array = ["' + arr[0] + '", ' + arr[1] + '", ' + arr[2] + '"' + ']';; function gfg_Run() { el_down.innerHTML = "Comma separates list = " + arr.join(", "); } </script></body> </html> Output: Before clicking on the button: After clicking on the button: Example-2:This example uses the toString() method to convert an array into a comma separated list. <!DOCTYPE html><html> <head> <title> JavaScript | Create comma separated list from an array. </title></head> <body style="text-align:center;" id="body"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 16px; font-weight: bold;"> </p> <button onclick="gfg_Run()"> click here </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 arr = ["GFG1", "GFG2", "GFG3"]; el_up.innerHTML = 'Original Array = ["' + arr[0] + '", ' + arr[1] + '", ' + arr[2] + '"' + ']';; function gfg_Run() { el_down.innerHTML = "Comma separates list = " + arr.toString(); } </script></body> </html> Output: Before clicking on the button: After clicking on the button: Example-3:This example uses the normal array name and do the same work. <!DOCTYPE html><html> <head> <title> JavaScript | Create comma separated list from an array. </title></head> <body style="text-align:center;" id="body"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 16px; font-weight: bold;"> </p> <button onclick="gfg_Run()"> click here </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 arr = ["GFG1", "GFG2", "GFG3"]; el_up.innerHTML = 'Original Array = ["' + arr[0] + '", ' + arr[1] + '", ' + arr[2] + '"' + ']';; function gfg_Run() { el_down.innerHTML = "Comma separates list = " + arr; } </script></body> </html> Output: Before clicking on the button: After clicking on the button: javascript-array JavaScript-Misc JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Difference Between PUT and PATCH Request How to append HTML code to a div using JavaScript ? Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n14 May, 2019" }, { "code": null, "e": 177, "s": 28, "text": "Here is a need to convert an array into an object. To do so we are going to use a few of the most preferred methods. First here is a method to know." }, { "code": null, "e": 657, "s": 177, "text": "Array join() methodThis method joins the elements of the array to form a string and returns the new string.The elements of the array will be separated by a specified separator. If not specified, Default separator comma (, ) is used.Syntax:array.join(separator)\nParameters:separator:This parameter is optional. It specifies the separator to be used. If not used, Separated Comma(, ) is used.Return value:A String, containing the array values, separated by the specified separator." }, { "code": null, "e": 680, "s": 657, "text": "array.join(separator)\n" }, { "code": null, "e": 692, "s": 680, "text": "Parameters:" }, { "code": null, "e": 811, "s": 692, "text": "separator:This parameter is optional. It specifies the separator to be used. If not used, Separated Comma(, ) is used." }, { "code": null, "e": 901, "s": 811, "text": "Return value:A String, containing the array values, separated by the specified separator." }, { "code": null, "e": 1116, "s": 901, "text": "Array toString() methodThis method converts an array into a String and returns the new string.Syntax:array.toString()\nReturn value:It returns a string which represents the values of the array, separated by a comma." }, { "code": null, "e": 1134, "s": 1116, "text": "array.toString()\n" }, { "code": null, "e": 1231, "s": 1134, "text": "Return value:It returns a string which represents the values of the array, separated by a comma." }, { "code": null, "e": 1320, "s": 1231, "text": "Example-1: This example joins the element of the array by join() method using comma(, )." }, { "code": "<!DOCTYPE html><html> <head> <title> JavaScript | Create comma separated list from an array. </title></head> <body style=\"text-align:center;\" id=\"body\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 16px; font-weight: bold;\"> </p> <button onclick=\"gfg_Run()\"> click here </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 arr = [\"GFG1\", \"GFG2\", \"GFG3\"]; el_up.innerHTML = 'Original Array = [\"' + arr[0] + '\", ' + arr[1] + '\", ' + arr[2] + '\"' + ']';; function gfg_Run() { el_down.innerHTML = \"Comma separates list = \" + arr.join(\", \"); } </script></body> </html>", "e": 2441, "s": 1320, "text": null }, { "code": null, "e": 2449, "s": 2441, "text": "Output:" }, { "code": null, "e": 2480, "s": 2449, "text": "Before clicking on the button:" }, { "code": null, "e": 2510, "s": 2480, "text": "After clicking on the button:" }, { "code": null, "e": 2609, "s": 2510, "text": "Example-2:This example uses the toString() method to convert an array into a comma separated list." }, { "code": "<!DOCTYPE html><html> <head> <title> JavaScript | Create comma separated list from an array. </title></head> <body style=\"text-align:center;\" id=\"body\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 16px; font-weight: bold;\"> </p> <button onclick=\"gfg_Run()\"> click here </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 arr = [\"GFG1\", \"GFG2\", \"GFG3\"]; el_up.innerHTML = 'Original Array = [\"' + arr[0] + '\", ' + arr[1] + '\", ' + arr[2] + '\"' + ']';; function gfg_Run() { el_down.innerHTML = \"Comma separates list = \" + arr.toString(); } </script></body> </html>", "e": 3722, "s": 2609, "text": null }, { "code": null, "e": 3730, "s": 3722, "text": "Output:" }, { "code": null, "e": 3761, "s": 3730, "text": "Before clicking on the button:" }, { "code": null, "e": 3791, "s": 3761, "text": "After clicking on the button:" }, { "code": null, "e": 3863, "s": 3791, "text": "Example-3:This example uses the normal array name and do the same work." }, { "code": "<!DOCTYPE html><html> <head> <title> JavaScript | Create comma separated list from an array. </title></head> <body style=\"text-align:center;\" id=\"body\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 16px; font-weight: bold;\"> </p> <button onclick=\"gfg_Run()\"> click here </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 arr = [\"GFG1\", \"GFG2\", \"GFG3\"]; el_up.innerHTML = 'Original Array = [\"' + arr[0] + '\", ' + arr[1] + '\", ' + arr[2] + '\"' + ']';; function gfg_Run() { el_down.innerHTML = \"Comma separates list = \" + arr; } </script></body> </html>", "e": 4973, "s": 3863, "text": null }, { "code": null, "e": 4981, "s": 4973, "text": "Output:" }, { "code": null, "e": 5012, "s": 4981, "text": "Before clicking on the button:" }, { "code": null, "e": 5042, "s": 5012, "text": "After clicking on the button:" }, { "code": null, "e": 5059, "s": 5042, "text": "javascript-array" }, { "code": null, "e": 5075, "s": 5059, "text": "JavaScript-Misc" }, { "code": null, "e": 5086, "s": 5075, "text": "JavaScript" }, { "code": null, "e": 5103, "s": 5086, "text": "Web Technologies" }, { "code": null, "e": 5201, "s": 5103, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5262, "s": 5201, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 5334, "s": 5262, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 5374, "s": 5334, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 5415, "s": 5374, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 5467, "s": 5415, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 5500, "s": 5467, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 5562, "s": 5500, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 5623, "s": 5562, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 5673, "s": 5623, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Difference between C-LOOK and C-SCAN Disk Scheduling Algorithm
21 Jul, 2020 C-LOOK is the modified version of both LOOK and C-scan algorithms. In this algorithm, the head starts from the first request in one direction and moves towards the last request at another end, serving all request in between. After reaching the last request in one end, the head jumps in another direction and move towards the remaining requests and then satisfies them in the same direction as before. Unlike C-SCAN, the head pointer will move till the end request of the disk. Example : Consider a disk with 200 tracks (0-199) and the disk queue having I/O requests in the following order as follows: 98, 183, 40, 122, 10, 124, 65 The current head position of the Read/Write head is 53 and will move in Right direction. Calculate the total number of track movements of Read/Write head using C-LOOK algorithm. Total head movements = (65 - 53) + (98 - 65) + (122 - 98) + (124 - 122) + (183 - 124) + (183 - 10) + (40 - 10) = 333 C-scan algorithm, also known as Circular Elevator algorithm is the modified version of SCAN algorithm. In this algorithm, the head pointer starts from one end of the disk and moves towards the other end, serving all requests in between. After reaching the other end, the head reverses its direction and go to the starting point. It then satisfies the remaining requests, in the same direction as before. Unlike C-LOOK, the head pointer will move till the end of the disk, whether there is a request or not. Example – Consider a disk with 200 tracks (0-199) and the disk queue having I/O requests in the following order as follows: 98, 183, 40, 122, 10, 124, 65 The current head position of the Read/Write head is 53 and will move in Right direction. Calculate the total number of track movements of Read/Write head using C-scan algorithm. Total head movements = (65 - 53) + (98 - 65) + (122 - 98) + (124 - 122) + (183 - 124) + (199 - 183) + (199 - 0) + (10 - 0) + (40 - 10) = 395 Algorithms Difference Between Operating Systems Operating Systems Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Jul, 2020" }, { "code": null, "e": 506, "s": 28, "text": "C-LOOK is the modified version of both LOOK and C-scan algorithms. In this algorithm, the head starts from the first request in one direction and moves towards the last request at another end, serving all request in between. After reaching the last request in one end, the head jumps in another direction and move towards the remaining requests and then satisfies them in the same direction as before. Unlike C-SCAN, the head pointer will move till the end request of the disk." }, { "code": null, "e": 516, "s": 506, "text": "Example :" }, { "code": null, "e": 631, "s": 516, "text": "Consider a disk with 200 tracks (0-199) and the disk queue having I/O requests in the following order as follows: " }, { "code": null, "e": 662, "s": 631, "text": "98, 183, 40, 122, 10, 124, 65\n" }, { "code": null, "e": 840, "s": 662, "text": "The current head position of the Read/Write head is 53 and will move in Right direction. Calculate the total number of track movements of Read/Write head using C-LOOK algorithm." }, { "code": null, "e": 964, "s": 840, "text": "Total head movements\n= (65 - 53) + (98 - 65)\n + (122 - 98)\n + (124 - 122) + (183 - 124)\n + (183 - 10) + (40 - 10)\n= 333\n" }, { "code": null, "e": 1474, "s": 964, "text": "C-scan algorithm, also known as Circular Elevator algorithm is the modified version of SCAN algorithm. In this algorithm, the head pointer starts from one end of the disk and moves towards the other end, serving all requests in between. After reaching the other end, the head reverses its direction and go to the starting point. It then satisfies the remaining requests, in the same direction as before. Unlike C-LOOK, the head pointer will move till the end of the disk, whether there is a request or not. " }, { "code": null, "e": 1484, "s": 1474, "text": "Example –" }, { "code": null, "e": 1599, "s": 1484, "text": "Consider a disk with 200 tracks (0-199) and the disk queue having I/O requests in the following order as follows: " }, { "code": null, "e": 1630, "s": 1599, "text": "98, 183, 40, 122, 10, 124, 65\n" }, { "code": null, "e": 1808, "s": 1630, "text": "The current head position of the Read/Write head is 53 and will move in Right direction. Calculate the total number of track movements of Read/Write head using C-scan algorithm." }, { "code": null, "e": 1962, "s": 1808, "text": "Total head movements\n= (65 - 53) + (98 - 65)\n + (122 - 98)\n + (124 - 122) + (183 - 124)\n + (199 - 183) + (199 - 0)\n + (10 - 0) + (40 - 10)\n= 395\n" }, { "code": null, "e": 1973, "s": 1962, "text": "Algorithms" }, { "code": null, "e": 1992, "s": 1973, "text": "Difference Between" }, { "code": null, "e": 2010, "s": 1992, "text": "Operating Systems" }, { "code": null, "e": 2028, "s": 2010, "text": "Operating Systems" }, { "code": null, "e": 2039, "s": 2028, "text": "Algorithms" } ]
Express.js express.static() Function
16 Jun, 2022 The express.static() function is a built-in middleware function in Express. It serves static files and is based on serve-static. Syntax: express.static(root, [options]) Parameters: The root parameter describes the root directory from which to serve static assets. Return Value: It returns an Object. Installation of express module: You can visit the link to Install express module. You can install this package by using this command. You can visit the link to Install express module. You can install this package by using this command. npm install express After installing the express module, you can check your express version in command prompt using the command. After installing the express module, you can check your express version in command prompt using the command. npm version express After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command. After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command. node index.js Example 1: Filename: index.js javascript var express = require('express');var app = express();var path = require('path');var PORT = 3000; // Static Middlewareapp.use(express.static(path.join(__dirname, 'public'))) app.get('/', function (req, res, next) { res.render('home.ejs');}) app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT);}); Now, create home.ejs file in views folder with the following code: Filename: home.ejs html <!DOCTYPE html><html><head> <title>express.static() Demo</title></head><body> <h2>Greetings from GeeksforGeeks</h2> <img src="Demo.jpg" width="150" height="100" /></body></html> Steps to run the program: The project structure will look like this: Note: Demo.jpg is placed in the public folder, as public folder is now being served as static to the server.Make sure you have installed express and ejs module using the following command: The project structure will look like this: Note: Demo.jpg is placed in the public folder, as public folder is now being served as static to the server. Make sure you have installed express and ejs module using the following command: npm install express npm install ejs Run index.js file using below command: Run index.js file using below command: node index.js Output: Output: Server listening on PORT 3000 Now open your browser and go to http://localhost:3000/, you will see the following output on your screen: Now open your browser and go to http://localhost:3000/, you will see the following output on your screen: Example 2: Filename: index.js javascript var express = require('express');var app = express();var path = require('path'); // Static Middlewareconsole.log(app.use(express.static( path.join(__dirname, 'public')))) Run index.js file using below command: node index.js Output: [Function: app] EventEmitter { _events: [Object: null prototype] { mount: [Function: onmount] }, _eventsCount: 1, _maxListeners: undefined, setMaxListeners: [Function: setMaxListeners], getMaxListeners: [Function: getMaxListeners], emit: [Function: emit], . . . . locals: [Object: null prototype] { settings: { 'x-powered-by': true, etag: 'weak', 'etag fn': [Function: generateETag], env: 'development', 'query parser': 'extended', 'query parser fn': [Function: parseExtendedQueryString], 'subdomain offset': 2, 'trust proxy': false, 'trust proxy fn': [Function: trustNone], view: [Function: View], views: 'C:\\Users\\Lenovo\\Downloads\\GFG Reviewer Internship\\Program\\views', 'jsonp callback name': 'callback' } }, mountpath: '/', _router: [Function: router] { params: {}, _params: [], caseSensitive: false, mergeParams: undefined, strict: false, stack: [ [Layer], [Layer], [Layer] ] } } Reference: Official Documentation Vijay Sirra zack_aayush sumitgumber28 Express.js Node.js Web Technologies 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 ? Installation of Node.js on Linux Node.js fs.readFileSync() Method Node.js fs.writeFile() Method How to install the previous version of node.js and npm ? Top 10 Projects For Beginners To Practice HTML and CSS Skills Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Jun, 2022" }, { "code": null, "e": 165, "s": 28, "text": "The express.static() function is a built-in middleware function in Express. It serves static files and is based on serve-static. Syntax:" }, { "code": null, "e": 197, "s": 165, "text": "express.static(root, [options])" }, { "code": null, "e": 360, "s": 197, "text": "Parameters: The root parameter describes the root directory from which to serve static assets. Return Value: It returns an Object. Installation of express module:" }, { "code": null, "e": 462, "s": 360, "text": "You can visit the link to Install express module. You can install this package by using this command." }, { "code": null, "e": 564, "s": 462, "text": "You can visit the link to Install express module. You can install this package by using this command." }, { "code": null, "e": 584, "s": 564, "text": "npm install express" }, { "code": null, "e": 693, "s": 584, "text": "After installing the express module, you can check your express version in command prompt using the command." }, { "code": null, "e": 802, "s": 693, "text": "After installing the express module, you can check your express version in command prompt using the command." }, { "code": null, "e": 822, "s": 802, "text": "npm version express" }, { "code": null, "e": 957, "s": 822, "text": "After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command." }, { "code": null, "e": 1092, "s": 957, "text": "After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command." }, { "code": null, "e": 1106, "s": 1092, "text": "node index.js" }, { "code": null, "e": 1137, "s": 1106, "text": "Example 1: Filename: index.js " }, { "code": null, "e": 1148, "s": 1137, "text": "javascript" }, { "code": "var express = require('express');var app = express();var path = require('path');var PORT = 3000; // Static Middlewareapp.use(express.static(path.join(__dirname, 'public'))) app.get('/', function (req, res, next) { res.render('home.ejs');}) app.listen(PORT, function(err){ if (err) console.log(err); console.log(\"Server listening on PORT\", PORT);});", "e": 1508, "s": 1148, "text": null }, { "code": null, "e": 1595, "s": 1508, "text": "Now, create home.ejs file in views folder with the following code: Filename: home.ejs " }, { "code": null, "e": 1600, "s": 1595, "text": "html" }, { "code": "<!DOCTYPE html><html><head> <title>express.static() Demo</title></head><body> <h2>Greetings from GeeksforGeeks</h2> <img src=\"Demo.jpg\" width=\"150\" height=\"100\" /></body></html>", "e": 1784, "s": 1600, "text": null }, { "code": null, "e": 1810, "s": 1784, "text": "Steps to run the program:" }, { "code": null, "e": 2043, "s": 1810, "text": "The project structure will look like this: Note: Demo.jpg is placed in the public folder, as public folder is now being served as static to the server.Make sure you have installed express and ejs module using the following command:" }, { "code": null, "e": 2196, "s": 2043, "text": "The project structure will look like this: Note: Demo.jpg is placed in the public folder, as public folder is now being served as static to the server." }, { "code": null, "e": 2277, "s": 2196, "text": "Make sure you have installed express and ejs module using the following command:" }, { "code": null, "e": 2313, "s": 2277, "text": "npm install express\nnpm install ejs" }, { "code": null, "e": 2352, "s": 2313, "text": "Run index.js file using below command:" }, { "code": null, "e": 2391, "s": 2352, "text": "Run index.js file using below command:" }, { "code": null, "e": 2405, "s": 2391, "text": "node index.js" }, { "code": null, "e": 2413, "s": 2405, "text": "Output:" }, { "code": null, "e": 2421, "s": 2413, "text": "Output:" }, { "code": null, "e": 2451, "s": 2421, "text": "Server listening on PORT 3000" }, { "code": null, "e": 2558, "s": 2451, "text": "Now open your browser and go to http://localhost:3000/, you will see the following output on your screen: " }, { "code": null, "e": 2665, "s": 2558, "text": "Now open your browser and go to http://localhost:3000/, you will see the following output on your screen: " }, { "code": null, "e": 2696, "s": 2665, "text": "Example 2: Filename: index.js " }, { "code": null, "e": 2707, "s": 2696, "text": "javascript" }, { "code": "var express = require('express');var app = express();var path = require('path'); // Static Middlewareconsole.log(app.use(express.static( path.join(__dirname, 'public'))))", "e": 2881, "s": 2707, "text": null }, { "code": null, "e": 2920, "s": 2881, "text": "Run index.js file using below command:" }, { "code": null, "e": 2934, "s": 2920, "text": "node index.js" }, { "code": null, "e": 2942, "s": 2934, "text": "Output:" }, { "code": null, "e": 3976, "s": 2942, "text": "[Function: app] EventEmitter {\n _events: [Object: null prototype] { mount: [Function: onmount] },\n _eventsCount: 1,\n _maxListeners: undefined,\n setMaxListeners: [Function: setMaxListeners],\n getMaxListeners: [Function: getMaxListeners],\n emit: [Function: emit],\n .\n .\n .\n .\n locals: [Object: null prototype] {\n settings: {\n 'x-powered-by': true,\n etag: 'weak',\n 'etag fn': [Function: generateETag],\n env: 'development',\n 'query parser': 'extended',\n 'query parser fn': [Function: parseExtendedQueryString],\n 'subdomain offset': 2,\n 'trust proxy': false,\n 'trust proxy fn': [Function: trustNone],\n view: [Function: View],\n views: 'C:\\\\Users\\\\Lenovo\\\\Downloads\\\\GFG \n Reviewer Internship\\\\Program\\\\views',\n 'jsonp callback name': 'callback'\n }\n },\n mountpath: '/',\n _router: [Function: router] {\n params: {},\n _params: [],\n caseSensitive: false,\n mergeParams: undefined,\n strict: false,\n stack: [ [Layer], [Layer], [Layer] ]\n }\n}" }, { "code": null, "e": 4010, "s": 3976, "text": "Reference: Official Documentation" }, { "code": null, "e": 4022, "s": 4010, "text": "Vijay Sirra" }, { "code": null, "e": 4034, "s": 4022, "text": "zack_aayush" }, { "code": null, "e": 4048, "s": 4034, "text": "sumitgumber28" }, { "code": null, "e": 4059, "s": 4048, "text": "Express.js" }, { "code": null, "e": 4067, "s": 4059, "text": "Node.js" }, { "code": null, "e": 4084, "s": 4067, "text": "Web Technologies" }, { "code": null, "e": 4182, "s": 4084, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4230, "s": 4182, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 4263, "s": 4230, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 4296, "s": 4263, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 4326, "s": 4296, "text": "Node.js fs.writeFile() Method" }, { "code": null, "e": 4383, "s": 4326, "text": "How to install the previous version of node.js and npm ?" }, { "code": null, "e": 4445, "s": 4383, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 4478, "s": 4445, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 4539, "s": 4478, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 4589, "s": 4539, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Python – Unlist Single Valued Dictionary List
16 Aug, 2021 Given list of dictionaries, perform the unlisting of records in which we just have 1 dictionary as record element. Input : test_list = [{‘best’: [{‘a’: 6}], ‘Gfg’: 15}] Output : [{‘best’: {‘a’: 6}, ‘Gfg’: 15}] Explanation : The value list associated with ‘best’ key is changed to dictionary. Input : test_list = [{‘Gfg’: [{‘best’ : 17}]}] Output : [{‘Gfg’: {‘best’: 17}}] Explanation : ‘Gfg’ key’s value changed to single dictionary. Method #1: Using loop + isinstance() This is brute force way in which this task can be performed. In this, we test for the list type using isinstance(), and loop is used for iterations. Python3 # Python3 code to demonstrate working of# Unlist Single Valued Dictionary List# Using loop + isinstance() # initializing listtest_list = [{'Gfg': 1, 'is': [{'a': 2, 'b': 3}]}, {'best': [{'c': 4, 'd': 5}], 'CS': 6}] # printing original listprint("The original list is : " + str(test_list)) # Using loop + isinstance()for dicts in test_list: for key, val in dicts.items(): # isinstance() is used to check for list to convert if isinstance(val, list): dicts[key] = val[0] # printing resultprint("The converted Dictionary list : " + str(test_list)) The original list is : [{'Gfg': 1, 'is': [{'b': 3, 'a': 2}]}, {'CS': 6, 'best': [{'d': 5, 'c': 4}]}] The converted Dictionary list : [{'Gfg': 1, 'is': {'b': 3, 'a': 2}}, {'CS': 6, 'best': {'d': 5, 'c': 4}}] Method #2: Using list comprehension + isinstance() The combination of above functions can be used to solve the problem. In this, we perform similar task with short hand approach similar to above method. Python3 # Python3 code to demonstrate working of# Unlist Single Valued Dictionary List# Using list comprehension + isinstance() # initializing listtest_list = [{'Gfg': 1, 'is': [{'a': 2, 'b': 3}]}, {'best': [{'c': 4, 'd': 5}], 'CS': 6}] # printing original listprint("The original list is : " + str(test_list)) # Using list comprehension + isinstance()# Similar way as above, extracting first element of listres = [{key: val[0] if isinstance(val, list) else val for key, val in sub.items()} for sub in test_list] # printing resultprint("The converted Dictionary list : " + str(res)) The original list is : [{'Gfg': 1, 'is': [{'b': 3, 'a': 2}]}, {'CS': 6, 'best': [{'d': 5, 'c': 4}]}] The converted Dictionary list : [{'Gfg': 1, 'is': {'b': 3, 'a': 2}}, {'CS': 6, 'best': {'d': 5, 'c': 4}}] kk773572498 Python list-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": "\n16 Aug, 2021" }, { "code": null, "e": 144, "s": 28, "text": "Given list of dictionaries, perform the unlisting of records in which we just have 1 dictionary as record element. " }, { "code": null, "e": 321, "s": 144, "text": "Input : test_list = [{‘best’: [{‘a’: 6}], ‘Gfg’: 15}] Output : [{‘best’: {‘a’: 6}, ‘Gfg’: 15}] Explanation : The value list associated with ‘best’ key is changed to dictionary." }, { "code": null, "e": 465, "s": 321, "text": "Input : test_list = [{‘Gfg’: [{‘best’ : 17}]}] Output : [{‘Gfg’: {‘best’: 17}}] Explanation : ‘Gfg’ key’s value changed to single dictionary. " }, { "code": null, "e": 651, "s": 465, "text": "Method #1: Using loop + isinstance() This is brute force way in which this task can be performed. In this, we test for the list type using isinstance(), and loop is used for iterations." }, { "code": null, "e": 659, "s": 651, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Unlist Single Valued Dictionary List# Using loop + isinstance() # initializing listtest_list = [{'Gfg': 1, 'is': [{'a': 2, 'b': 3}]}, {'best': [{'c': 4, 'd': 5}], 'CS': 6}] # printing original listprint(\"The original list is : \" + str(test_list)) # Using loop + isinstance()for dicts in test_list: for key, val in dicts.items(): # isinstance() is used to check for list to convert if isinstance(val, list): dicts[key] = val[0] # printing resultprint(\"The converted Dictionary list : \" + str(test_list))", "e": 1275, "s": 659, "text": null }, { "code": null, "e": 1482, "s": 1275, "text": "The original list is : [{'Gfg': 1, 'is': [{'b': 3, 'a': 2}]}, {'CS': 6, 'best': [{'d': 5, 'c': 4}]}]\nThe converted Dictionary list : [{'Gfg': 1, 'is': {'b': 3, 'a': 2}}, {'CS': 6, 'best': {'d': 5, 'c': 4}}]" }, { "code": null, "e": 1687, "s": 1484, "text": "Method #2: Using list comprehension + isinstance() The combination of above functions can be used to solve the problem. In this, we perform similar task with short hand approach similar to above method." }, { "code": null, "e": 1695, "s": 1687, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Unlist Single Valued Dictionary List# Using list comprehension + isinstance() # initializing listtest_list = [{'Gfg': 1, 'is': [{'a': 2, 'b': 3}]}, {'best': [{'c': 4, 'd': 5}], 'CS': 6}] # printing original listprint(\"The original list is : \" + str(test_list)) # Using list comprehension + isinstance()# Similar way as above, extracting first element of listres = [{key: val[0] if isinstance(val, list) else val for key, val in sub.items()} for sub in test_list] # printing resultprint(\"The converted Dictionary list : \" + str(res))", "e": 2318, "s": 1695, "text": null }, { "code": null, "e": 2525, "s": 2318, "text": "The original list is : [{'Gfg': 1, 'is': [{'b': 3, 'a': 2}]}, {'CS': 6, 'best': [{'d': 5, 'c': 4}]}]\nThe converted Dictionary list : [{'Gfg': 1, 'is': {'b': 3, 'a': 2}}, {'CS': 6, 'best': {'d': 5, 'c': 4}}]" }, { "code": null, "e": 2539, "s": 2527, "text": "kk773572498" }, { "code": null, "e": 2560, "s": 2539, "text": "Python list-programs" }, { "code": null, "e": 2567, "s": 2560, "text": "Python" }, { "code": null, "e": 2583, "s": 2567, "text": "Python Programs" } ]
Collections synchronizedList() method in Java with Examples
08 Oct, 2018 The synchronizedList() method of java.util.Collections class is used to return a synchronized (thread-safe) list backed by the specified list. In order to guarantee serial access, it is critical that all access to the backing list is accomplished through the returned list. Syntax: public static <T> List<T> synchronizedList(List<T> list) Parameters: This method takes the list as a parameter to be “wrapped” in a synchronized list. Return Value: This method returns a synchronized view of the specified list. Below are the examples to illustrate the synchronizedList() method Example 1: // Java program to demonstrate// synchronizedList() method for String Value import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // creating object of List<String> List<String> list = new ArrayList<String>(); // populate the list list.add("A"); list.add("B"); list.add("C"); list.add("D"); list.add("E"); // printing the Collection System.out.println("List : " + list); // create a synchronized list List<String> synlist = Collections .synchronizedList(list); // printing the Collection System.out.println("Synchronized list is : " + synlist); } catch (IllegalArgumentException e) { System.out.println("Exception thrown : " + e); } }} List : [A, B, C, D, E] Synchronized list is : [A, B, C, D, E] Example 2: // Java program to demonstrate// synchronizedList() method for Integer Value import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // creating object of List<Integer> List<Integer> list = new ArrayList<Integer>(); // populate the list list.add(20); list.add(30); list.add(40); list.add(50); list.add(60); // printing the Collection System.out.println("List : " + list); // create a synchronized list List<Integer> synlist = Collections .synchronizedList(list); // printing the Collection System.out.println("Synchronized list is : " + synlist); } catch (IllegalArgumentException e) { System.out.println("Exception thrown : " + e); } }} List : [20, 30, 40, 50, 60] Synchronized list is : [20, 30, 40, 50, 60] Java - util package Java-Collections Java-Functions 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 Java Programming Examples Strings in Java Differences between JDK, JRE and JVM Abstraction in Java
[ { "code": null, "e": 54, "s": 26, "text": "\n08 Oct, 2018" }, { "code": null, "e": 328, "s": 54, "text": "The synchronizedList() method of java.util.Collections class is used to return a synchronized (thread-safe) list backed by the specified list. In order to guarantee serial access, it is critical that all access to the backing list is accomplished through the returned list." }, { "code": null, "e": 336, "s": 328, "text": "Syntax:" }, { "code": null, "e": 395, "s": 336, "text": "public static <T> List<T>\n synchronizedList(List<T> list)" }, { "code": null, "e": 489, "s": 395, "text": "Parameters: This method takes the list as a parameter to be “wrapped” in a synchronized list." }, { "code": null, "e": 566, "s": 489, "text": "Return Value: This method returns a synchronized view of the specified list." }, { "code": null, "e": 633, "s": 566, "text": "Below are the examples to illustrate the synchronizedList() method" }, { "code": null, "e": 644, "s": 633, "text": "Example 1:" }, { "code": "// Java program to demonstrate// synchronizedList() method for String Value import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // creating object of List<String> List<String> list = new ArrayList<String>(); // populate the list list.add(\"A\"); list.add(\"B\"); list.add(\"C\"); list.add(\"D\"); list.add(\"E\"); // printing the Collection System.out.println(\"List : \" + list); // create a synchronized list List<String> synlist = Collections .synchronizedList(list); // printing the Collection System.out.println(\"Synchronized list is : \" + synlist); } catch (IllegalArgumentException e) { System.out.println(\"Exception thrown : \" + e); } }}", "e": 1584, "s": 644, "text": null }, { "code": null, "e": 1647, "s": 1584, "text": "List : [A, B, C, D, E]\nSynchronized list is : [A, B, C, D, E]\n" }, { "code": null, "e": 1658, "s": 1647, "text": "Example 2:" }, { "code": "// Java program to demonstrate// synchronizedList() method for Integer Value import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // creating object of List<Integer> List<Integer> list = new ArrayList<Integer>(); // populate the list list.add(20); list.add(30); list.add(40); list.add(50); list.add(60); // printing the Collection System.out.println(\"List : \" + list); // create a synchronized list List<Integer> synlist = Collections .synchronizedList(list); // printing the Collection System.out.println(\"Synchronized list is : \" + synlist); } catch (IllegalArgumentException e) { System.out.println(\"Exception thrown : \" + e); } }}", "e": 2608, "s": 1658, "text": null }, { "code": null, "e": 2681, "s": 2608, "text": "List : [20, 30, 40, 50, 60]\nSynchronized list is : [20, 30, 40, 50, 60]\n" }, { "code": null, "e": 2701, "s": 2681, "text": "Java - util package" }, { "code": null, "e": 2718, "s": 2701, "text": "Java-Collections" }, { "code": null, "e": 2733, "s": 2718, "text": "Java-Functions" }, { "code": null, "e": 2738, "s": 2733, "text": "Java" }, { "code": null, "e": 2743, "s": 2738, "text": "Java" }, { "code": null, "e": 2760, "s": 2743, "text": "Java-Collections" }, { "code": null, "e": 2858, "s": 2760, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2873, "s": 2858, "text": "Stream In Java" }, { "code": null, "e": 2894, "s": 2873, "text": "Introduction to Java" }, { "code": null, "e": 2915, "s": 2894, "text": "Constructors in Java" }, { "code": null, "e": 2934, "s": 2915, "text": "Exceptions in Java" }, { "code": null, "e": 2951, "s": 2934, "text": "Generics in Java" }, { "code": null, "e": 2981, "s": 2951, "text": "Functional Interfaces in Java" }, { "code": null, "e": 3007, "s": 2981, "text": "Java Programming Examples" }, { "code": null, "e": 3023, "s": 3007, "text": "Strings in Java" }, { "code": null, "e": 3060, "s": 3023, "text": "Differences between JDK, JRE and JVM" } ]
How to Convert string to integer type in Golang?
14 Sep, 2021 Strings in Golang is a sequence of variable-width characters where each and every character is represented by one or more bytes using UTF-8 Encoding. In Go language, both signed and unsigned integers are available in four different sizes. In order to convert string to integer type in Golang, you can use the following methods. 1. Atoi() Function: The Atoi stands for ASCII to integer and returns the result of ParseInt(s, 10, 0) converted to type int. Syntax: func Atoi(s string) (int, error) Example: Go // Go program to illustrate how to// Convert string to the integer type package main import ( "fmt" "strconv") func main() { str1 := "123" // using ParseInt method int1, err := strconv.ParseInt(str1, 6, 12) fmt.Println(int1) // If the input string contains the integer // greater than base, get the zero value in return str2 := "123" int2, err := strconv.ParseInt(str2, 2, 32) fmt.Println(int2, err) } Output: 123 0 strconv.Atoi: parsing "12.3": invalid syntax 2. ParseInt() Function: The ParseInt interprets a string s in the given base (0, 2 to 36) and bit size (0 to 64) and returns the corresponding value i. Syntax: func ParseInt(s string, base int, bitSize int) (i int64, err error) Example: Go // Go program to illustrate how to// Convert string to the integer type package main import ( "fmt" "strconv") func main() { str1 := "123" // using ParseInt method int1, err := strconv.ParseInt(str1, 6, 12) fmt.Println(int1) // If the input string contains the integer // greater than base, get the zero value in return str2 := "123" int2, err := strconv.ParseInt(str2, 2, 32) fmt.Println(int2, err) } Output: 51 0 strconv.ParseInt: parsing "123": invalid syntax anikakapoor Golang-Program Picked Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n14 Sep, 2021" }, { "code": null, "e": 356, "s": 28, "text": "Strings in Golang is a sequence of variable-width characters where each and every character is represented by one or more bytes using UTF-8 Encoding. In Go language, both signed and unsigned integers are available in four different sizes. In order to convert string to integer type in Golang, you can use the following methods." }, { "code": null, "e": 481, "s": 356, "text": "1. Atoi() Function: The Atoi stands for ASCII to integer and returns the result of ParseInt(s, 10, 0) converted to type int." }, { "code": null, "e": 490, "s": 481, "text": "Syntax: " }, { "code": null, "e": 523, "s": 490, "text": "func Atoi(s string) (int, error)" }, { "code": null, "e": 533, "s": 523, "text": "Example: " }, { "code": null, "e": 536, "s": 533, "text": "Go" }, { "code": "// Go program to illustrate how to// Convert string to the integer type package main import ( \"fmt\" \"strconv\") func main() { str1 := \"123\" // using ParseInt method int1, err := strconv.ParseInt(str1, 6, 12) fmt.Println(int1) // If the input string contains the integer // greater than base, get the zero value in return str2 := \"123\" int2, err := strconv.ParseInt(str2, 2, 32) fmt.Println(int2, err) }", "e": 976, "s": 536, "text": null }, { "code": null, "e": 985, "s": 976, "text": "Output: " }, { "code": null, "e": 1036, "s": 985, "text": "123\n0 strconv.Atoi: parsing \"12.3\": invalid syntax" }, { "code": null, "e": 1188, "s": 1036, "text": "2. ParseInt() Function: The ParseInt interprets a string s in the given base (0, 2 to 36) and bit size (0 to 64) and returns the corresponding value i." }, { "code": null, "e": 1198, "s": 1188, "text": "Syntax: " }, { "code": null, "e": 1266, "s": 1198, "text": "func ParseInt(s string, base int, bitSize int) (i int64, err error)" }, { "code": null, "e": 1276, "s": 1266, "text": "Example: " }, { "code": null, "e": 1279, "s": 1276, "text": "Go" }, { "code": "// Go program to illustrate how to// Convert string to the integer type package main import ( \"fmt\" \"strconv\") func main() { str1 := \"123\" // using ParseInt method int1, err := strconv.ParseInt(str1, 6, 12) fmt.Println(int1) // If the input string contains the integer // greater than base, get the zero value in return str2 := \"123\" int2, err := strconv.ParseInt(str2, 2, 32) fmt.Println(int2, err) }", "e": 1719, "s": 1279, "text": null }, { "code": null, "e": 1728, "s": 1719, "text": "Output: " }, { "code": null, "e": 1781, "s": 1728, "text": "51\n0 strconv.ParseInt: parsing \"123\": invalid syntax" }, { "code": null, "e": 1795, "s": 1783, "text": "anikakapoor" }, { "code": null, "e": 1810, "s": 1795, "text": "Golang-Program" }, { "code": null, "e": 1817, "s": 1810, "text": "Picked" }, { "code": null, "e": 1829, "s": 1817, "text": "Go Language" } ]
Try-with-resources Feature in Java
13 Jun, 2022 In Java, the Try-with-resources statement is a try statement that declares one or more resources in it. A resource is an object that must be closed once your program is done using it. For example, a File resource or a Socket connection resource. The try-with-resources statement ensures that each resource is closed at the end of the statement execution. If we don’t close the resources, it may constitute a resource leak and also the program could exhaust the resources available to it. You can pass any object as a resource that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable. By this, now we don’t need to add an extra finally block for just passing the closing statements of the resources. The resources will be closed as soon as the try-catch block is executed. Syntax: Try-with-resources try(declare resources here) { // use resources } catch(FileNotFoundException e) { // exception handling } Exceptions: When it comes to exceptions, there is a difference in try-catch-finally block and try-with-resources block. If an exception is thrown in both try block and finally block, the method returns the exception thrown in finally block. For try-with-resources, if an exception is thrown in a try block and in a try-with-resources statement, then the method returns the exception thrown in the try block. The exceptions thrown by try-with-resources are suppressed, i.e. we can say that try-with-resources block throws suppressed exceptions. Now, let us discuss both the possible scenarios which are demonstrated below as an example as follows: Case 1: Single resource Case 2: Multiple resources Example 1: try-with-resources having a single resource Java // Java Program for try-with-resources// having single resource // Importing all input output classesimport java.io.*; // Classclass GFG { // Main driver method public static void main(String[] args) { // Try block to check for exceptions try ( // Creating an object of FileOutputStream // to write stream or raw data // Adding resource FileOutputStream fos = new FileOutputStream("gfgtextfile.txt")) { // Custom string input String text = "Hello World. This is my java program"; // Converting string to bytes byte arr[] = text.getBytes(); // Text written in the file fos.write(arr); } // Catch block to handle exceptions catch (Exception e) { // Display message for the occurred exception System.out.println(e); } // Display message for successful execution of // program System.out.println( "Resource are closed and message has been written into the gfgtextfile.txt"); }} Output: Resource are closed and message has been written into the gfgtextfile.txt Example 2: try-with-resources having multiple resources Java // Java program for try-with-resources// having multiple resources // Importing all input output classesimport java.io.*; // Classclass GFG { // Main driver method public static void main(String[] args) { // Try block to check for exceptions // Writing data to a file using FileOutputStream // by passing input file as a parameter try (FileOutputStream fos = new FileOutputStream("outputfile.txt"); // Adding resouce // Reading the stream of character from BufferedReader br = new BufferedReader( new FileReader("gfgtextfile.txt"))) { // Declaring a string holding the // stream content of the file String text; // Condition check using readLine() method // which holds true till there is content // in the input file while ((text = br.readLine()) != null) { // Reading from input file passed above // using getBytes() method byte arr[] = text.getBytes(); // String converted to bytes fos.write(arr); // Copying the content of passed input file // 'inputgfgtext' file to outputfile.txt } // Display message when // file is successfully copied System.out.println( "File content copied to another one."); } // Catch block to handle generic exceptions catch (Exception e) { // Display the exception on the // console window System.out.println(e); } // Display message for successful execution of the // program System.out.println( "Resource are closed and message has been written into the gfgtextfile.txt"); }} Output: File content copied to another one. Resource are closed and message has been written into the gfgtextfile.txt ruhelaa48 sweetyty surinderdawra388 Java-Exception Handling Picked Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n13 Jun, 2022" }, { "code": null, "e": 543, "s": 54, "text": "In Java, the Try-with-resources statement is a try statement that declares one or more resources in it. A resource is an object that must be closed once your program is done using it. For example, a File resource or a Socket connection resource. The try-with-resources statement ensures that each resource is closed at the end of the statement execution. If we don’t close the resources, it may constitute a resource leak and also the program could exhaust the resources available to it." }, { "code": null, "e": 684, "s": 543, "text": "You can pass any object as a resource that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable." }, { "code": null, "e": 873, "s": 684, "text": "By this, now we don’t need to add an extra finally block for just passing the closing statements of the resources. The resources will be closed as soon as the try-catch block is executed. " }, { "code": null, "e": 900, "s": 873, "text": "Syntax: Try-with-resources" }, { "code": null, "e": 1014, "s": 900, "text": "try(declare resources here) {\n // use resources\n}\ncatch(FileNotFoundException e) {\n // exception handling\n}" }, { "code": null, "e": 1026, "s": 1014, "text": "Exceptions:" }, { "code": null, "e": 1255, "s": 1026, "text": "When it comes to exceptions, there is a difference in try-catch-finally block and try-with-resources block. If an exception is thrown in both try block and finally block, the method returns the exception thrown in finally block." }, { "code": null, "e": 1558, "s": 1255, "text": "For try-with-resources, if an exception is thrown in a try block and in a try-with-resources statement, then the method returns the exception thrown in the try block. The exceptions thrown by try-with-resources are suppressed, i.e. we can say that try-with-resources block throws suppressed exceptions." }, { "code": null, "e": 1661, "s": 1558, "text": "Now, let us discuss both the possible scenarios which are demonstrated below as an example as follows:" }, { "code": null, "e": 1685, "s": 1661, "text": "Case 1: Single resource" }, { "code": null, "e": 1712, "s": 1685, "text": "Case 2: Multiple resources" }, { "code": null, "e": 1767, "s": 1712, "text": "Example 1: try-with-resources having a single resource" }, { "code": null, "e": 1772, "s": 1767, "text": "Java" }, { "code": "// Java Program for try-with-resources// having single resource // Importing all input output classesimport java.io.*; // Classclass GFG { // Main driver method public static void main(String[] args) { // Try block to check for exceptions try ( // Creating an object of FileOutputStream // to write stream or raw data // Adding resource FileOutputStream fos = new FileOutputStream(\"gfgtextfile.txt\")) { // Custom string input String text = \"Hello World. This is my java program\"; // Converting string to bytes byte arr[] = text.getBytes(); // Text written in the file fos.write(arr); } // Catch block to handle exceptions catch (Exception e) { // Display message for the occurred exception System.out.println(e); } // Display message for successful execution of // program System.out.println( \"Resource are closed and message has been written into the gfgtextfile.txt\"); }}", "e": 2899, "s": 1772, "text": null }, { "code": null, "e": 2909, "s": 2899, "text": " Output: " }, { "code": null, "e": 2983, "s": 2909, "text": "Resource are closed and message has been written into the gfgtextfile.txt" }, { "code": null, "e": 3039, "s": 2983, "text": "Example 2: try-with-resources having multiple resources" }, { "code": null, "e": 3044, "s": 3039, "text": "Java" }, { "code": "// Java program for try-with-resources// having multiple resources // Importing all input output classesimport java.io.*; // Classclass GFG { // Main driver method public static void main(String[] args) { // Try block to check for exceptions // Writing data to a file using FileOutputStream // by passing input file as a parameter try (FileOutputStream fos = new FileOutputStream(\"outputfile.txt\"); // Adding resouce // Reading the stream of character from BufferedReader br = new BufferedReader( new FileReader(\"gfgtextfile.txt\"))) { // Declaring a string holding the // stream content of the file String text; // Condition check using readLine() method // which holds true till there is content // in the input file while ((text = br.readLine()) != null) { // Reading from input file passed above // using getBytes() method byte arr[] = text.getBytes(); // String converted to bytes fos.write(arr); // Copying the content of passed input file // 'inputgfgtext' file to outputfile.txt } // Display message when // file is successfully copied System.out.println( \"File content copied to another one.\"); } // Catch block to handle generic exceptions catch (Exception e) { // Display the exception on the // console window System.out.println(e); } // Display message for successful execution of the // program System.out.println( \"Resource are closed and message has been written into the gfgtextfile.txt\"); }}", "e": 4904, "s": 3044, "text": null }, { "code": null, "e": 4913, "s": 4904, "text": "Output: " }, { "code": null, "e": 5023, "s": 4913, "text": "File content copied to another one.\nResource are closed and message has been written into the gfgtextfile.txt" }, { "code": null, "e": 5035, "s": 5025, "text": "ruhelaa48" }, { "code": null, "e": 5044, "s": 5035, "text": "sweetyty" }, { "code": null, "e": 5061, "s": 5044, "text": "surinderdawra388" }, { "code": null, "e": 5085, "s": 5061, "text": "Java-Exception Handling" }, { "code": null, "e": 5092, "s": 5085, "text": "Picked" }, { "code": null, "e": 5097, "s": 5092, "text": "Java" }, { "code": null, "e": 5102, "s": 5097, "text": "Java" } ]
SQL Outer Join
13 Apr, 2021 In a relational DBMS, we follow the principles of normalization that allows us to minimize the large tables into small tables. By using a select statement in Joins, we can retrieve the big table back. Outer joins are of following three types. Left outer joinRight outer joinFull outer join Left outer join Right outer join Full outer join Creating a database : Run the following command to create a database. Create database testdb; Using the database : Run the following command to use a database. use testdb; Adding table to the database : Run the following command to add tables to a database. CREATE TABLE Students ( StudentID int, LastName varchar(255), FirstName varchar(255), Address varchar(255), City varchar(255) ); Inserting rows into database : INSERT INTO students ( StudentID, LastName, FirstName, Address, City ) VALUES ( 111, 'James', 'Johnson', 'USA', california ); Output of database : Type the following command to get output. SELECT * FROM students; Types of outer join : 1.Left Outer Join : The left join operation returns all record from left table and matching records from the right table. On a matching element not found in right table, NULL is represented in that case. Syntax : SELECT column_name(s) FROM table1 LEFT JOIN Table2 ON Table1.Column_Name=table2.column_name; 2. Right Outer Join : The right join operation returns all record from right table and matching records from the left table. On a matching element not found in left table, NULL is represented in that case. Syntax : SELECT column_name(s) FROM table1 RIGHT JOIN table2 ON table1.column_name = table2.column_name; 3. Full Outer Join : The full outer Join keyword returns all records when there is a match in left or right table records. Syntax: SELECT column_name FROM table1 FULL OUTER JOIN table2 ON table1.columnName = table2.columnName WHERE condition; Example : Creating 1st Sample table students. CREATE TABLE students ( id INTEGER, name TEXT NOT NULL, gender TEXT NOT NULL ); -- insert some values INSERT INTO students VALUES (1, 'Ryan', 'M'); INSERT INTO students VALUES (2, 'Joanna', 'F'); INSERT INTO students Values (3, 'Moana', 'F'); Creating 2nd sample table college. CREATE TABLE college ( id INTEGER, classTeacher TEXT NOT NULL, Strength TEXT NOT NULL ); -- insert some values INSERT INTO college VALUES (1, 'Alpha', '50'); INSERT INTO college VALUES (2, 'Romeo', '60'); INSERT INTO college Values (3, 'Charlie', '55'); Performing outer join on above two tables. SELECT College.classTeacher, students.id FROM College FULL OUTER JOIN College ON College.id=students.id ORDER BY College.classTeacher; The above code will perform a full outer join on tables students and college and will return the output that matches the id of college with id of students. The output will be class Teacher from college table and id from students table. The table will be ordered by class Teacher from college table. DBMS-SQL SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Update Multiple Columns in Single Update Statement in SQL? Window functions in SQL What is Temporary Table in SQL? SQL using Python SQL | Sub queries in From Clause SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter RANK() Function in SQL Server SQL Query to Convert VARCHAR to INT SQL Query to Compare Two Dates SQL | DROP, TRUNCATE
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Apr, 2021" }, { "code": null, "e": 271, "s": 28, "text": "In a relational DBMS, we follow the principles of normalization that allows us to minimize the large tables into small tables. By using a select statement in Joins, we can retrieve the big table back. Outer joins are of following three types." }, { "code": null, "e": 318, "s": 271, "text": "Left outer joinRight outer joinFull outer join" }, { "code": null, "e": 334, "s": 318, "text": "Left outer join" }, { "code": null, "e": 351, "s": 334, "text": "Right outer join" }, { "code": null, "e": 367, "s": 351, "text": "Full outer join" }, { "code": null, "e": 437, "s": 367, "text": "Creating a database : Run the following command to create a database." }, { "code": null, "e": 461, "s": 437, "text": "Create database testdb;" }, { "code": null, "e": 528, "s": 461, "text": " Using the database : Run the following command to use a database." }, { "code": null, "e": 540, "s": 528, "text": "use testdb;" }, { "code": null, "e": 626, "s": 540, "text": "Adding table to the database : Run the following command to add tables to a database." }, { "code": null, "e": 770, "s": 626, "text": "CREATE TABLE Students (\n StudentID int,\n LastName varchar(255),\n FirstName varchar(255),\n Address varchar(255),\n City varchar(255)\n);" }, { "code": null, "e": 801, "s": 770, "text": "Inserting rows into database :" }, { "code": null, "e": 931, "s": 801, "text": "INSERT INTO students (\nStudentID,\nLastName,\nFirstName,\nAddress,\nCity\n)\nVALUES\n(\n111, \n'James',\n 'Johnson',\n 'USA',\n california\n);" }, { "code": null, "e": 952, "s": 931, "text": "Output of database :" }, { "code": null, "e": 994, "s": 952, "text": "Type the following command to get output." }, { "code": null, "e": 1019, "s": 994, "text": "SELECT * FROM students;" }, { "code": null, "e": 1041, "s": 1019, "text": "Types of outer join :" }, { "code": null, "e": 1245, "s": 1041, "text": "1.Left Outer Join : The left join operation returns all record from left table and matching records from the right table. On a matching element not found in right table, NULL is represented in that case." }, { "code": null, "e": 1254, "s": 1245, "text": "Syntax :" }, { "code": null, "e": 1348, "s": 1254, "text": "SELECT column_name(s)\nFROM table1\nLEFT JOIN Table2 \nON Table1.Column_Name=table2.column_name;" }, { "code": null, "e": 1554, "s": 1348, "text": "2. Right Outer Join : The right join operation returns all record from right table and matching records from the left table. On a matching element not found in left table, NULL is represented in that case." }, { "code": null, "e": 1563, "s": 1554, "text": "Syntax :" }, { "code": null, "e": 1659, "s": 1563, "text": "SELECT column_name(s)\nFROM table1\nRIGHT JOIN table2\nON table1.column_name = table2.column_name;" }, { "code": null, "e": 1782, "s": 1659, "text": "3. Full Outer Join : The full outer Join keyword returns all records when there is a match in left or right table records." }, { "code": null, "e": 1902, "s": 1782, "text": "Syntax:\nSELECT column_name\nFROM table1\nFULL OUTER JOIN table2\nON table1.columnName = table2.columnName\nWHERE condition;" }, { "code": null, "e": 1912, "s": 1902, "text": "Example :" }, { "code": null, "e": 1948, "s": 1912, "text": "Creating 1st Sample table students." }, { "code": null, "e": 2194, "s": 1948, "text": "CREATE TABLE students (\n id INTEGER,\n name TEXT NOT NULL,\n gender TEXT NOT NULL\n);\n-- insert some values\nINSERT INTO students VALUES (1, 'Ryan', 'M');\nINSERT INTO students VALUES (2, 'Joanna', 'F');\nINSERT INTO students Values (3, 'Moana', 'F');" }, { "code": null, "e": 2229, "s": 2194, "text": "Creating 2nd sample table college." }, { "code": null, "e": 2486, "s": 2229, "text": "CREATE TABLE college (\n id INTEGER,\n classTeacher TEXT NOT NULL,\n Strength TEXT NOT NULL\n);\n-- insert some values\nINSERT INTO college VALUES (1, 'Alpha', '50');\nINSERT INTO college VALUES (2, 'Romeo', '60');\nINSERT INTO college Values (3, 'Charlie', '55');" }, { "code": null, "e": 2529, "s": 2486, "text": "Performing outer join on above two tables." }, { "code": null, "e": 2570, "s": 2529, "text": "SELECT College.classTeacher, students.id" }, { "code": null, "e": 2583, "s": 2570, "text": "FROM College" }, { "code": null, "e": 2633, "s": 2583, "text": "FULL OUTER JOIN College ON College.id=students.id" }, { "code": null, "e": 2664, "s": 2633, "text": "ORDER BY College.classTeacher;" }, { "code": null, "e": 2963, "s": 2664, "text": "The above code will perform a full outer join on tables students and college and will return the output that matches the id of college with id of students. The output will be class Teacher from college table and id from students table. The table will be ordered by class Teacher from college table." }, { "code": null, "e": 2972, "s": 2963, "text": "DBMS-SQL" }, { "code": null, "e": 2976, "s": 2972, "text": "SQL" }, { "code": null, "e": 2980, "s": 2976, "text": "SQL" }, { "code": null, "e": 3078, "s": 2980, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3144, "s": 3078, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 3168, "s": 3144, "text": "Window functions in SQL" }, { "code": null, "e": 3200, "s": 3168, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 3217, "s": 3200, "text": "SQL using Python" }, { "code": null, "e": 3250, "s": 3217, "text": "SQL | Sub queries in From Clause" }, { "code": null, "e": 3328, "s": 3250, "text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter" }, { "code": null, "e": 3358, "s": 3328, "text": "RANK() Function in SQL Server" }, { "code": null, "e": 3394, "s": 3358, "text": "SQL Query to Convert VARCHAR to INT" }, { "code": null, "e": 3425, "s": 3394, "text": "SQL Query to Compare Two Dates" } ]
C# Program to Display the Student Details Using Select Clause LINQ - GeeksforGeeks
24 Oct, 2021 LINQ is known as Language Integrated Query and it is introduced in .NET 3.5. It gives the ability to .NET languages to generate queries to retrieve data from the data source. It removes the mismatch between programming languages and databases and the syntax used to create a query is the same no matter which type of data source is used. In this article, we will learn how to print the list of students along with their details using a select clause in LINQ. The Select clause is used when we want to select some specific value from the given collection. Syntax: IEnumerable<Student> Query = from student in stu select student; Example: Input : { stu_id = 101, stu_name = "bobby", stu_dept = "cse", stu_salary = 8900 }, { stu_id = 102, stu_name = "sravan", stu_dept = "ece", stu_salary = 8900 }, { stu_id = 103, stu_name = "deepu", stu_dept = "mba", stu_salary = 8900 }}; Output : { stu_id = 101, stu_name = "bobby", stu_dept = "cse", stu_salary = 8900 }, { stu_id = 102, stu_name = "sravan", stu_dept = "ece", stu_salary = 8900 }, { stu_id = 103, stu_name = "deepu", stu_dept = "mba", stu_salary = 8900 }}; Input : { stu_id = 101, stu_name = "bobby", stu_dept = "cse", stu_salary = 8900 } Output: { stu_id = 101, stu_name = "bobby", stu_dept = "cse", stu_salary = 8900 } Approach To display the list of students follow the following steps: Create a list of students with four variables(Id, name department and semester).Iterate through the student details by using for loop and get the student details by using select clauseDisplay the student details. Create a list of students with four variables(Id, name department and semester). Iterate through the student details by using for loop and get the student details by using select clause Display the student details. Example : C# // C# program to print the list of students// details using select clause using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks; class Student{ // Declare 4 variables - id, age, department and semesterint stu_id; string stu_dept;string stu_name;int stu_semester; // Get the to string method that returns// id, age, department and semesterpublic override string ToString(){ return stu_id + " " + stu_name + " " + stu_dept + " " + stu_semester;} // Driver codestatic void Main(string[] args){ // Declare a list variable List<Student> stu = new List<Student>() { // Create 3 Student details new Student{ stu_id = 101, stu_name = "bobby", stu_dept = "CSE", stu_semester = 2 }, new Student{ stu_id = 102, stu_name = "sravan", stu_dept = "ECE", stu_semester = 1 }, new Student{ stu_id = 103, stu_name = "deepu", stu_dept = "EEE", stu_semester = 4}, }; // Iterate the Employee // using select function IEnumerable<Student> Query = from student in stu select student; // Display student details Console.WriteLine("ID Name Department Semester"); Console.WriteLine("+++++++++++++++++++++++++++"); foreach (Student e in Query) { // Call the to string method Console.WriteLine(e.ToString()); }}} Output: ID Name Department Semester +++++++++++++++++++++++++++ 101 bobby CSE 2 102 sravan ECE 1 103 deepu EEE 4 CSharp LINQ CSharp-programs Picked C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Extension Method in C# HashSet in C# with Examples Partial Classes in C# Top 50 C# Interview Questions & Answers C# | How to insert an element in an Array? C# | List Class C# | Inheritance Linked List Implementation in C# Lambda Expressions in C# Convert String to Character Array in C#
[ { "code": null, "e": 24222, "s": 24194, "text": "\n24 Oct, 2021" }, { "code": null, "e": 24777, "s": 24222, "text": "LINQ is known as Language Integrated Query and it is introduced in .NET 3.5. It gives the ability to .NET languages to generate queries to retrieve data from the data source. It removes the mismatch between programming languages and databases and the syntax used to create a query is the same no matter which type of data source is used. In this article, we will learn how to print the list of students along with their details using a select clause in LINQ. The Select clause is used when we want to select some specific value from the given collection." }, { "code": null, "e": 24785, "s": 24777, "text": "Syntax:" }, { "code": null, "e": 24851, "s": 24785, "text": " IEnumerable<Student> Query = from student in stu select student;" }, { "code": null, "e": 24860, "s": 24851, "text": "Example:" }, { "code": null, "e": 25547, "s": 24860, "text": "Input :\n{ stu_id = 101, stu_name = \"bobby\", \n stu_dept = \"cse\", stu_salary = 8900 },\n{ stu_id = 102, stu_name = \"sravan\", \n stu_dept = \"ece\", stu_salary = 8900 },\n{ stu_id = 103, stu_name = \"deepu\", \n stu_dept = \"mba\", stu_salary = 8900 }};\nOutput :\n{ stu_id = 101, stu_name = \"bobby\", \n stu_dept = \"cse\", stu_salary = 8900 },\n{ stu_id = 102, stu_name = \"sravan\", \n stu_dept = \"ece\", stu_salary = 8900 },\n{ stu_id = 103, stu_name = \"deepu\", \n stu_dept = \"mba\", stu_salary = 8900 }};\n \nInput :\n{ stu_id = 101, stu_name = \"bobby\", \n stu_dept = \"cse\", stu_salary = 8900 }\nOutput:\n{ stu_id = 101, stu_name = \"bobby\", \n stu_dept = \"cse\", stu_salary = 8900 }\n " }, { "code": null, "e": 25556, "s": 25547, "text": "Approach" }, { "code": null, "e": 25616, "s": 25556, "text": "To display the list of students follow the following steps:" }, { "code": null, "e": 25829, "s": 25616, "text": "Create a list of students with four variables(Id, name department and semester).Iterate through the student details by using for loop and get the student details by using select clauseDisplay the student details." }, { "code": null, "e": 25910, "s": 25829, "text": "Create a list of students with four variables(Id, name department and semester)." }, { "code": null, "e": 26015, "s": 25910, "text": "Iterate through the student details by using for loop and get the student details by using select clause" }, { "code": null, "e": 26044, "s": 26015, "text": "Display the student details." }, { "code": null, "e": 26054, "s": 26044, "text": "Example :" }, { "code": null, "e": 26057, "s": 26054, "text": "C#" }, { "code": "// C# program to print the list of students// details using select clause using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks; class Student{ // Declare 4 variables - id, age, department and semesterint stu_id; string stu_dept;string stu_name;int stu_semester; // Get the to string method that returns// id, age, department and semesterpublic override string ToString(){ return stu_id + \" \" + stu_name + \" \" + stu_dept + \" \" + stu_semester;} // Driver codestatic void Main(string[] args){ // Declare a list variable List<Student> stu = new List<Student>() { // Create 3 Student details new Student{ stu_id = 101, stu_name = \"bobby\", stu_dept = \"CSE\", stu_semester = 2 }, new Student{ stu_id = 102, stu_name = \"sravan\", stu_dept = \"ECE\", stu_semester = 1 }, new Student{ stu_id = 103, stu_name = \"deepu\", stu_dept = \"EEE\", stu_semester = 4}, }; // Iterate the Employee // using select function IEnumerable<Student> Query = from student in stu select student; // Display student details Console.WriteLine(\"ID Name Department Semester\"); Console.WriteLine(\"+++++++++++++++++++++++++++\"); foreach (Student e in Query) { // Call the to string method Console.WriteLine(e.ToString()); }}}", "e": 27507, "s": 26057, "text": null }, { "code": null, "e": 27515, "s": 27507, "text": "Output:" }, { "code": null, "e": 27622, "s": 27515, "text": "ID Name Department Semester\n+++++++++++++++++++++++++++\n101 bobby CSE 2\n102 sravan ECE 1\n103 deepu EEE 4" }, { "code": null, "e": 27634, "s": 27622, "text": "CSharp LINQ" }, { "code": null, "e": 27650, "s": 27634, "text": "CSharp-programs" }, { "code": null, "e": 27657, "s": 27650, "text": "Picked" }, { "code": null, "e": 27660, "s": 27657, "text": "C#" }, { "code": null, "e": 27758, "s": 27660, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27767, "s": 27758, "text": "Comments" }, { "code": null, "e": 27780, "s": 27767, "text": "Old Comments" }, { "code": null, "e": 27803, "s": 27780, "text": "Extension Method in C#" }, { "code": null, "e": 27831, "s": 27803, "text": "HashSet in C# with Examples" }, { "code": null, "e": 27853, "s": 27831, "text": "Partial Classes in C#" }, { "code": null, "e": 27893, "s": 27853, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 27936, "s": 27893, "text": "C# | How to insert an element in an Array?" }, { "code": null, "e": 27952, "s": 27936, "text": "C# | List Class" }, { "code": null, "e": 27969, "s": 27952, "text": "C# | Inheritance" }, { "code": null, "e": 28002, "s": 27969, "text": "Linked List Implementation in C#" }, { "code": null, "e": 28027, "s": 28002, "text": "Lambda Expressions in C#" } ]
Python - Maximum Sum Record - GeeksforGeeks
30 Jan, 2020 Sometimes, while working with data, we might have a problem in which we need to find maximum sum between available pairs in list. This can be application to many problems in mathematics domain. Let’s discuss certain ways in which this task can be performed. Method #1 : Using max() + list comprehensionThe combination of this functions can be used to perform this task. In this, we compute the sum of all pairs and then return the max of it using max(). # Python3 code to demonstrate working of# Maximum Sum Record# Using list comprehension + max() # initialize listtest_list = [(3, 5), (1, 7), (10, 3), (1, 2)] # printing original list print("The original list : " + str(test_list)) # Maximum Sum Record# Using list comprehension + max()temp = [b + a for a, b in test_list]res = max(temp) # printing resultprint("Maximum sum among pairs : " + str(res)) The original list : [(3, 5), (1, 7), (10, 3), (1, 2)] Maximum sum among pairs : 13 Method #2 : Using max() + lambdaThis is similar to above method. In this the task performed by list comprehension is solved using lambda function, providing the sum computation logic. Returns the max. sum pair. # Python3 code to demonstrate working of# Maximum Sum Record# Using lambda + max() # initialize listtest_list = [(3, 5), (1, 7), (10, 3), (1, 2)] # printing original list print("The original list : " + str(test_list)) # Maximum Sum Record# Using lambda + max()res = max(test_list, key = lambda sub: sub[1] + sub[0]) # printing resultprint("Maximum sum among pairs : " + str(res)) The original list : [(3, 5), (1, 7), (10, 3), (1, 2)] Maximum sum among pairs : 13 Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary
[ { "code": null, "e": 25865, "s": 25837, "text": "\n30 Jan, 2020" }, { "code": null, "e": 26123, "s": 25865, "text": "Sometimes, while working with data, we might have a problem in which we need to find maximum sum between available pairs in list. This can be application to many problems in mathematics domain. Let’s discuss certain ways in which this task can be performed." }, { "code": null, "e": 26319, "s": 26123, "text": "Method #1 : Using max() + list comprehensionThe combination of this functions can be used to perform this task. In this, we compute the sum of all pairs and then return the max of it using max()." }, { "code": "# Python3 code to demonstrate working of# Maximum Sum Record# Using list comprehension + max() # initialize listtest_list = [(3, 5), (1, 7), (10, 3), (1, 2)] # printing original list print(\"The original list : \" + str(test_list)) # Maximum Sum Record# Using list comprehension + max()temp = [b + a for a, b in test_list]res = max(temp) # printing resultprint(\"Maximum sum among pairs : \" + str(res))", "e": 26723, "s": 26319, "text": null }, { "code": null, "e": 26807, "s": 26723, "text": "The original list : [(3, 5), (1, 7), (10, 3), (1, 2)]\nMaximum sum among pairs : 13\n" }, { "code": null, "e": 27020, "s": 26809, "text": "Method #2 : Using max() + lambdaThis is similar to above method. In this the task performed by list comprehension is solved using lambda function, providing the sum computation logic. Returns the max. sum pair." }, { "code": "# Python3 code to demonstrate working of# Maximum Sum Record# Using lambda + max() # initialize listtest_list = [(3, 5), (1, 7), (10, 3), (1, 2)] # printing original list print(\"The original list : \" + str(test_list)) # Maximum Sum Record# Using lambda + max()res = max(test_list, key = lambda sub: sub[1] + sub[0]) # printing resultprint(\"Maximum sum among pairs : \" + str(res))", "e": 27404, "s": 27020, "text": null }, { "code": null, "e": 27488, "s": 27404, "text": "The original list : [(3, 5), (1, 7), (10, 3), (1, 2)]\nMaximum sum among pairs : 13\n" }, { "code": null, "e": 27509, "s": 27488, "text": "Python list-programs" }, { "code": null, "e": 27516, "s": 27509, "text": "Python" }, { "code": null, "e": 27532, "s": 27516, "text": "Python Programs" }, { "code": null, "e": 27630, "s": 27532, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27648, "s": 27630, "text": "Python Dictionary" }, { "code": null, "e": 27680, "s": 27648, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27702, "s": 27680, "text": "Enumerate() in Python" }, { "code": null, "e": 27744, "s": 27702, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27774, "s": 27744, "text": "Iterate over a list in Python" }, { "code": null, "e": 27817, "s": 27774, "text": "Python program to convert a list to string" }, { "code": null, "e": 27839, "s": 27817, "text": "Defaultdict in Python" }, { "code": null, "e": 27878, "s": 27839, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 27924, "s": 27878, "text": "Python | Split string into list of characters" } ]
BigInteger abs() Method in Java - GeeksforGeeks
20 May, 2019 prerequisite : BigInteger Basics The java.math.BigInteger.abs() method returns absolute value of a BigInteger. By using this method one can find absolute value of any large size of numerical data stored as BigInteger. Syntax: public BigInteger abs() Parameters: The method does not take any parameters. Return Value: The method returns the absolute value of a BigInteger. Examples: Input: -2300 Output: 2300 Explanation: Applying mathematical abs() operation on -2300, positive 2300 is obtained i.e |-2300| = 2300. Input: -5482549 Output: 5482549 Below program illustrates abs() method of BigInteger: // Below program illustrates the abs() method// of BigInteger import java.math.*; public class GFG { public static void main(String[] args) { // Create BigInteger object BigInteger biginteger=new BigInteger("-2300"); // abs() method on bigInteger to find the absolute value // of a BigInteger BigInteger absolutevalue= biginteger.abs(); // Define result String result ="BigInteger "+biginteger+ " and Absolute value is "+absolutevalue; // Print result System.out.println(result); }} BigInteger -2300 and Absolute value is 2300 Reference: https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html#abs() Akanksha_Rai Java-BigInteger Java-Functions java-math Java-math-package Java Java-BigInteger Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Exceptions in Java Constructors in Java Different ways of Reading a text file in Java Functional Interfaces in Java Generics in Java Comparator Interface in Java with Examples PriorityQueue in Java Introduction to Java How to remove an element from ArrayList in Java?
[ { "code": null, "e": 25788, "s": 25760, "text": "\n20 May, 2019" }, { "code": null, "e": 25821, "s": 25788, "text": "prerequisite : BigInteger Basics" }, { "code": null, "e": 26006, "s": 25821, "text": "The java.math.BigInteger.abs() method returns absolute value of a BigInteger. By using this method one can find absolute value of any large size of numerical data stored as BigInteger." }, { "code": null, "e": 26014, "s": 26006, "text": "Syntax:" }, { "code": null, "e": 26038, "s": 26014, "text": "public BigInteger abs()" }, { "code": null, "e": 26091, "s": 26038, "text": "Parameters: The method does not take any parameters." }, { "code": null, "e": 26160, "s": 26091, "text": "Return Value: The method returns the absolute value of a BigInteger." }, { "code": null, "e": 26170, "s": 26160, "text": "Examples:" }, { "code": null, "e": 26341, "s": 26170, "text": "Input: -2300 \nOutput: 2300\nExplanation:\nApplying mathematical abs() operation on \n-2300, positive 2300 is obtained i.e |-2300| = 2300. \n\nInput: -5482549 \nOutput: 5482549\n" }, { "code": null, "e": 26395, "s": 26341, "text": "Below program illustrates abs() method of BigInteger:" }, { "code": "// Below program illustrates the abs() method// of BigInteger import java.math.*; public class GFG { public static void main(String[] args) { // Create BigInteger object BigInteger biginteger=new BigInteger(\"-2300\"); // abs() method on bigInteger to find the absolute value // of a BigInteger BigInteger absolutevalue= biginteger.abs(); // Define result String result =\"BigInteger \"+biginteger+ \" and Absolute value is \"+absolutevalue; // Print result System.out.println(result); }}", "e": 26992, "s": 26395, "text": null }, { "code": null, "e": 27037, "s": 26992, "text": "BigInteger -2300 and Absolute value is 2300\n" }, { "code": null, "e": 27122, "s": 27037, "text": "Reference: https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html#abs()" }, { "code": null, "e": 27135, "s": 27122, "text": "Akanksha_Rai" }, { "code": null, "e": 27151, "s": 27135, "text": "Java-BigInteger" }, { "code": null, "e": 27166, "s": 27151, "text": "Java-Functions" }, { "code": null, "e": 27176, "s": 27166, "text": "java-math" }, { "code": null, "e": 27194, "s": 27176, "text": "Java-math-package" }, { "code": null, "e": 27199, "s": 27194, "text": "Java" }, { "code": null, "e": 27215, "s": 27199, "text": "Java-BigInteger" }, { "code": null, "e": 27220, "s": 27215, "text": "Java" }, { "code": null, "e": 27318, "s": 27220, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27333, "s": 27318, "text": "Stream In Java" }, { "code": null, "e": 27352, "s": 27333, "text": "Exceptions in Java" }, { "code": null, "e": 27373, "s": 27352, "text": "Constructors in Java" }, { "code": null, "e": 27419, "s": 27373, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 27449, "s": 27419, "text": "Functional Interfaces in Java" }, { "code": null, "e": 27466, "s": 27449, "text": "Generics in Java" }, { "code": null, "e": 27509, "s": 27466, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 27531, "s": 27509, "text": "PriorityQueue in Java" }, { "code": null, "e": 27552, "s": 27531, "text": "Introduction to Java" } ]
C# - File I/O
A file is a collection of data stored in a disk with a specific name and a directory path. When a file is opened for reading or writing, it becomes a stream. The stream is basically the sequence of bytes passing through the communication path. There are two main streams: the input stream and the output stream. The input stream is used for reading data from file (read operation) and the output stream is used for writing into the file (write operation). The System.IO namespace has various classes that are used for performing numerous operations with files, such as creating and deleting files, reading from or writing to a file, closing a file etc. The following table shows some commonly used non-abstract classes in the System.IO namespace − BinaryReader Reads primitive data from a binary stream. BinaryWriter Writes primitive data in binary format. BufferedStream A temporary storage for a stream of bytes. Directory Helps in manipulating a directory structure. DirectoryInfo Used for performing operations on directories. DriveInfo Provides information for the drives. File Helps in manipulating files. FileInfo Used for performing operations on files. FileStream Used to read from and write to any location in a file. MemoryStream Used for random access to streamed data stored in memory. Path Performs operations on path information. StreamReader Used for reading characters from a byte stream. StreamWriter Is used for writing characters to a stream. StringReader Is used for reading from a string buffer. StringWriter Is used for writing into a string buffer. The FileStream class in the System.IO namespace helps in reading from, writing to and closing files. This class derives from the abstract class Stream. You need to create a FileStream object to create a new file or open an existing file. The syntax for creating a FileStream object is as follows − FileStream <object_name> = new FileStream( <file_name>, <FileMode Enumerator>, <FileAccess Enumerator>, <FileShare Enumerator>); For example, we create a FileStream object F for reading a file named sample.txt as shown − FileStream F = new FileStream("sample.txt", FileMode.Open, FileAccess.Read, FileShare.Read); FileMode The FileMode enumerator defines various methods for opening files. The members of the FileMode enumerator are − Append − It opens an existing file and puts cursor at the end of file, or creates the file, if the file does not exist. Append − It opens an existing file and puts cursor at the end of file, or creates the file, if the file does not exist. Create − It creates a new file. Create − It creates a new file. CreateNew − It specifies to the operating system, that it should create a new file. CreateNew − It specifies to the operating system, that it should create a new file. Open − It opens an existing file. Open − It opens an existing file. OpenOrCreate − It specifies to the operating system that it should open a file if it exists, otherwise it should create a new file. OpenOrCreate − It specifies to the operating system that it should open a file if it exists, otherwise it should create a new file. Truncate − It opens an existing file and truncates its size to zero bytes. Truncate − It opens an existing file and truncates its size to zero bytes. FileAccess FileAccess enumerators have members: Read, ReadWrite and Write. FileShare FileShare enumerators have the following members − Inheritable − It allows a file handle to pass inheritance to the child processes Inheritable − It allows a file handle to pass inheritance to the child processes None − It declines sharing of the current file None − It declines sharing of the current file Read − It allows opening the file for readin. Read − It allows opening the file for readin. ReadWrite − It allows opening the file for reading and writing ReadWrite − It allows opening the file for reading and writing Write − It allows opening the file for writing Write − It allows opening the file for writing The following program demonstrates use of the FileStream class − using System; using System.IO; namespace FileIOApplication { class Program { static void Main(string[] args) { FileStream F = new FileStream("test.dat", FileMode.OpenOrCreate, FileAccess.ReadWrite); for (int i = 1; i <= 20; i++) { F.WriteByte((byte)i); } F.Position = 0; for (int i = 0; i <= 20; i++) { Console.Write(F.ReadByte() + " "); } F.Close(); Console.ReadKey(); } } } When the above code is compiled and executed, it produces the following result − 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 -1 The preceding example provides simple file operations in C#. However, to utilize the immense powers of C# System.IO classes, you need to know the commonly used properties and methods of these classes. It involves reading from and writing into text files. The StreamReader and StreamWriter class helps to accomplish it. It involves reading from and writing into binary files. The BinaryReader and BinaryWriter class helps to accomplish this. It gives a C# programamer the ability to browse and locate Windows files and directories. 119 Lectures 23.5 hours Raja Biswas 37 Lectures 13 hours Trevoir Williams 16 Lectures 1 hours Peter Jepson 159 Lectures 21.5 hours Ebenezer Ogbu 193 Lectures 17 hours Arnold Higuit 24 Lectures 2.5 hours Eric Frick Print Add Notes Bookmark this page
[ { "code": null, "e": 2428, "s": 2270, "text": "A file is a collection of data stored in a disk with a specific name and a directory path. When a file is opened for reading or writing, it becomes a stream." }, { "code": null, "e": 2726, "s": 2428, "text": "The stream is basically the sequence of bytes passing through the communication path. There are two main streams: the input stream and the output stream. The input stream is used for reading data from file (read operation) and the output stream is used for writing into the file (write operation)." }, { "code": null, "e": 2923, "s": 2726, "text": "The System.IO namespace has various classes that are used for performing numerous operations with files, such as creating and deleting files, reading from or writing to a file, closing a file etc." }, { "code": null, "e": 3018, "s": 2923, "text": "The following table shows some commonly used non-abstract classes in the System.IO namespace −" }, { "code": null, "e": 3031, "s": 3018, "text": "BinaryReader" }, { "code": null, "e": 3074, "s": 3031, "text": "Reads primitive data from a binary stream." }, { "code": null, "e": 3087, "s": 3074, "text": "BinaryWriter" }, { "code": null, "e": 3127, "s": 3087, "text": "Writes primitive data in binary format." }, { "code": null, "e": 3142, "s": 3127, "text": "BufferedStream" }, { "code": null, "e": 3185, "s": 3142, "text": "A temporary storage for a stream of bytes." }, { "code": null, "e": 3195, "s": 3185, "text": "Directory" }, { "code": null, "e": 3240, "s": 3195, "text": "Helps in manipulating a directory structure." }, { "code": null, "e": 3254, "s": 3240, "text": "DirectoryInfo" }, { "code": null, "e": 3301, "s": 3254, "text": "Used for performing operations on directories." }, { "code": null, "e": 3311, "s": 3301, "text": "DriveInfo" }, { "code": null, "e": 3348, "s": 3311, "text": "Provides information for the drives." }, { "code": null, "e": 3353, "s": 3348, "text": "File" }, { "code": null, "e": 3382, "s": 3353, "text": "Helps in manipulating files." }, { "code": null, "e": 3391, "s": 3382, "text": "FileInfo" }, { "code": null, "e": 3432, "s": 3391, "text": "Used for performing operations on files." }, { "code": null, "e": 3443, "s": 3432, "text": "FileStream" }, { "code": null, "e": 3498, "s": 3443, "text": "Used to read from and write to any location in a file." }, { "code": null, "e": 3511, "s": 3498, "text": "MemoryStream" }, { "code": null, "e": 3569, "s": 3511, "text": "Used for random access to streamed data stored in memory." }, { "code": null, "e": 3574, "s": 3569, "text": "Path" }, { "code": null, "e": 3615, "s": 3574, "text": "Performs operations on path information." }, { "code": null, "e": 3628, "s": 3615, "text": "StreamReader" }, { "code": null, "e": 3676, "s": 3628, "text": "Used for reading characters from a byte stream." }, { "code": null, "e": 3689, "s": 3676, "text": "StreamWriter" }, { "code": null, "e": 3733, "s": 3689, "text": "Is used for writing characters to a stream." }, { "code": null, "e": 3746, "s": 3733, "text": "StringReader" }, { "code": null, "e": 3788, "s": 3746, "text": "Is used for reading from a string buffer." }, { "code": null, "e": 3801, "s": 3788, "text": "StringWriter" }, { "code": null, "e": 3843, "s": 3801, "text": "Is used for writing into a string buffer." }, { "code": null, "e": 3995, "s": 3843, "text": "The FileStream class in the System.IO namespace helps in reading from, writing to and closing files. This class derives from the abstract class Stream." }, { "code": null, "e": 4141, "s": 3995, "text": "You need to create a FileStream object to create a new file or open an existing file. The syntax for creating a FileStream object is as follows −" }, { "code": null, "e": 4274, "s": 4141, "text": "FileStream <object_name> = new FileStream( <file_name>, <FileMode Enumerator>,\n <FileAccess Enumerator>, <FileShare Enumerator>);\n" }, { "code": null, "e": 4366, "s": 4274, "text": "For example, we create a FileStream object F for reading a file named sample.txt as shown −" }, { "code": null, "e": 4463, "s": 4366, "text": "FileStream F = new FileStream(\"sample.txt\", FileMode.Open, FileAccess.Read,\n FileShare.Read);\n" }, { "code": null, "e": 4472, "s": 4463, "text": "FileMode" }, { "code": null, "e": 4584, "s": 4472, "text": "The FileMode enumerator defines various methods for opening files. The members of the FileMode enumerator are −" }, { "code": null, "e": 4704, "s": 4584, "text": "Append − It opens an existing file and puts cursor at the end of file, or creates the file, if the file does not exist." }, { "code": null, "e": 4824, "s": 4704, "text": "Append − It opens an existing file and puts cursor at the end of file, or creates the file, if the file does not exist." }, { "code": null, "e": 4856, "s": 4824, "text": "Create − It creates a new file." }, { "code": null, "e": 4888, "s": 4856, "text": "Create − It creates a new file." }, { "code": null, "e": 4972, "s": 4888, "text": "CreateNew − It specifies to the operating system, that it should create a new file." }, { "code": null, "e": 5056, "s": 4972, "text": "CreateNew − It specifies to the operating system, that it should create a new file." }, { "code": null, "e": 5090, "s": 5056, "text": "Open − It opens an existing file." }, { "code": null, "e": 5124, "s": 5090, "text": "Open − It opens an existing file." }, { "code": null, "e": 5256, "s": 5124, "text": "OpenOrCreate − It specifies to the operating system that it should open a file if it exists, otherwise it should create a new file." }, { "code": null, "e": 5388, "s": 5256, "text": "OpenOrCreate − It specifies to the operating system that it should open a file if it exists, otherwise it should create a new file." }, { "code": null, "e": 5463, "s": 5388, "text": "Truncate − It opens an existing file and truncates its size to zero bytes." }, { "code": null, "e": 5538, "s": 5463, "text": "Truncate − It opens an existing file and truncates its size to zero bytes." }, { "code": null, "e": 5549, "s": 5538, "text": "FileAccess" }, { "code": null, "e": 5613, "s": 5549, "text": "FileAccess enumerators have members: Read, ReadWrite and Write." }, { "code": null, "e": 5623, "s": 5613, "text": "FileShare" }, { "code": null, "e": 5674, "s": 5623, "text": "FileShare enumerators have the following members −" }, { "code": null, "e": 5755, "s": 5674, "text": "Inheritable − It allows a file handle to pass inheritance to the child processes" }, { "code": null, "e": 5836, "s": 5755, "text": "Inheritable − It allows a file handle to pass inheritance to the child processes" }, { "code": null, "e": 5883, "s": 5836, "text": "None − It declines sharing of the current file" }, { "code": null, "e": 5930, "s": 5883, "text": "None − It declines sharing of the current file" }, { "code": null, "e": 5976, "s": 5930, "text": "Read − It allows opening the file for readin." }, { "code": null, "e": 6022, "s": 5976, "text": "Read − It allows opening the file for readin." }, { "code": null, "e": 6085, "s": 6022, "text": "ReadWrite − It allows opening the file for reading and writing" }, { "code": null, "e": 6148, "s": 6085, "text": "ReadWrite − It allows opening the file for reading and writing" }, { "code": null, "e": 6195, "s": 6148, "text": "Write − It allows opening the file for writing" }, { "code": null, "e": 6242, "s": 6195, "text": "Write − It allows opening the file for writing" }, { "code": null, "e": 6307, "s": 6242, "text": "The following program demonstrates use of the FileStream class −" }, { "code": null, "e": 6821, "s": 6307, "text": "using System;\nusing System.IO;\n\nnamespace FileIOApplication {\n class Program {\n static void Main(string[] args) {\n FileStream F = new FileStream(\"test.dat\", FileMode.OpenOrCreate, \n FileAccess.ReadWrite);\n \n for (int i = 1; i <= 20; i++) {\n F.WriteByte((byte)i);\n }\n F.Position = 0;\n for (int i = 0; i <= 20; i++) {\n Console.Write(F.ReadByte() + \" \");\n }\n F.Close();\n Console.ReadKey();\n }\n }\n}" }, { "code": null, "e": 6902, "s": 6821, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 6957, "s": 6902, "text": "1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 -1\n" }, { "code": null, "e": 7158, "s": 6957, "text": "The preceding example provides simple file operations in C#. However, to utilize the immense powers of C# System.IO classes, you need to know the commonly used properties and methods of these classes." }, { "code": null, "e": 7276, "s": 7158, "text": "It involves reading from and writing into text files. The StreamReader and StreamWriter class helps to accomplish it." }, { "code": null, "e": 7398, "s": 7276, "text": "It involves reading from and writing into binary files. The BinaryReader and BinaryWriter class helps to accomplish this." }, { "code": null, "e": 7489, "s": 7398, "text": "It gives a C# programamer the ability to browse and locate Windows files and directories.\n" }, { "code": null, "e": 7526, "s": 7489, "text": "\n 119 Lectures \n 23.5 hours \n" }, { "code": null, "e": 7539, "s": 7526, "text": " Raja Biswas" }, { "code": null, "e": 7573, "s": 7539, "text": "\n 37 Lectures \n 13 hours \n" }, { "code": null, "e": 7591, "s": 7573, "text": " Trevoir Williams" }, { "code": null, "e": 7624, "s": 7591, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 7638, "s": 7624, "text": " Peter Jepson" }, { "code": null, "e": 7675, "s": 7638, "text": "\n 159 Lectures \n 21.5 hours \n" }, { "code": null, "e": 7690, "s": 7675, "text": " Ebenezer Ogbu" }, { "code": null, "e": 7725, "s": 7690, "text": "\n 193 Lectures \n 17 hours \n" }, { "code": null, "e": 7740, "s": 7725, "text": " Arnold Higuit" }, { "code": null, "e": 7775, "s": 7740, "text": "\n 24 Lectures \n 2.5 hours \n" }, { "code": null, "e": 7787, "s": 7775, "text": " Eric Frick" }, { "code": null, "e": 7794, "s": 7787, "text": " Print" }, { "code": null, "e": 7805, "s": 7794, "text": " Add Notes" } ]
Tryit Editor v3.7
Tryit: Styling lists with colors
[]
How to initialize Array of objects with parameterized constructors in C++ - GeeksforGeeks
19 Apr, 2022 Array of Objects: When a class is defined, only the specification for the object is defined; no memory or storage is allocated. To use the data and access functions defined in the class, you need to create objects. Syntax: ClassName ObjectName[number of objects]; Different methods to initialize the Array of objects with parameterized constructors: 1. Using bunch of function calls as elements of array: It’s just like normal array declaration but here we initialize the array with function calls of constructor as elements of that array. C++ #include <iostream>using namespace std; class Test { // private variables.private: int x, y; public: // parameterized constructor Test(int cx, int cy) { x = cx; y = cy; } // method to add two numbers void add() { cout << x + y << endl; }};int main(){ // Initializing 3 array Objects with function calls of // parameterized constructor as elements of that array Test obj[] = { Test(1, 1), Test(2, 2), Test(3, 3) }; // using add method for each of three elements. for (int i = 0; i < 3; i++) { obj[i].add(); } return 0;} 2. Using malloc(): To avoid the call of a non-parameterized constructor, use malloc() method. “malloc” or “memory allocation” method in C++ is used to dynamically allocate a single large block of memory with the specified size. It returns a pointer of type void which can be cast into a pointer of any form. C++ #include <iostream>#define N 5 using namespace std; class Test { // private variables int x, y; public: // parameterized constructor Test(int x, int y) { this->x = x; this->y = y; } // function to print void print() { cout << x << " " << y << endl; }}; int main(){ // allocating dynamic array // of Size N using malloc() Test* arr = (Test*)malloc(sizeof(Test) * N); // calling constructor // for each index of array for (int i = 0; i < N; i++) { arr[i] = Test(i, i + 1); } // printing contents of array for (int i = 0; i < N; i++) { arr[i].print(); } return 0;} 0 1 1 2 2 3 3 4 4 5 3. Using new keyword: The new operator denotes a request for memory allocation on the Heap. If sufficient memory is available, the new operator initializes the memory and returns the address of the newly allocated and initialized memory to the pointer variable. Here, pointer-variable is the pointer of type data-type. Data-type could be any built-in data type including array or any user-defined data types including structure and class. For dynamic initialization new keyword require non parameterized constructor if we add a parameterized constructor. So we will use a dummy constructor for it. C++ #include <iostream>#define N 5 using namespace std; class Test { // private variables int x, y; public: // dummy constructor Test() {} // parameterized constructor Test(int x, int y) { this->x = x; this->y = y; } // function to print void print() { cout << x << " " << y << endl; }}; int main(){ // allocating dynamic array // of Size N using new keyword Test* arr = new Test[N]; // calling constructor // for each index of array for (int i = 0; i < N; i++) { arr[i] = Test(i, i + 1); } // printing contents of array for (int i = 0; i < N; i++) { arr[i].print(); } return 0;} 0 1 1 2 2 3 3 4 4 5 If we don’t use the dummy constructor compiler would show the error given below Compiler Error: error: no matching function for call to ‘Test::Test()’ Test *arr=new Test[N]; 4. Using Double pointer (pointer to pointer concept): A pointer to a pointer is a form of multiple indirections, or a chain of pointers. Normally, a pointer contains the address of a variable. When we define a pointer to a pointer, the first pointer contains the address of the second pointer, which points to the location that contains the actual value as shown below.Here we can assign a number of blocks to be allocated and thus for every index we have to call parameterized constructor using the new keyword to initialize. C++ #include <iostream>#define N 5 using namespace std; class Test { // private variables int x, y; public: // parameterized constructor Test(int x, int y) : x(x) , y(y) { } // function to print void print() { cout << x << " " << y << endl; }}; int main(){ // allocating array using // pointer to pointer concept Test** arr = new Test*[N]; // calling constructor for each index // of array using new keyword for (int i = 0; i < N; i++) { arr[i] = new Test(i, i + 1); } // printing contents of array for (int i = 0; i < N; i++) { arr[i]->print(); } return 0;} 0 1 1 2 2 3 3 4 4 5 5. Using Vector of type class: Vector is one of the most powerful element of Standard Template Library makes it easy to write any complex codes related to static or dynamic array in an efficient way. It takes one parameter that can be of any type and thus we use our Class as a type of vector and push Objects in every iteration of the loop. Vectors are same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container. Vector elements are placed in contiguous storage so that they can be accessed and traversed using iterators. In vectors, data is inserted at the end. C++ #include <iostream>#include <vector>#define N 5 using namespace std; class Test { // private variables int x, y; public: // parameterized constructor Test(int x, int y) : x(x) , y(y) { } // function to print void print() { cout << x << " " << y << endl; }}; int main(){ // vector of type Test class vector<Test> v; // inserting object at the end of vector for (int i = 0; i < N; i++) v.push_back(Test(i, i + 1)); // printing object content for (int i = 0; i < N; i++) v[i].print(); return 0;} 0 1 1 2 2 3 3 4 4 5 viveksuman393 akshaysingh98088 chhabradhanvi rkbhola5 C++-Class and Object Dynamic Memory Allocation Arrays C++ Arrays CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Multidimensional Arrays in Java Introduction to Arrays Python | Using 2D arrays/lists the right way Linked List vs Array Vector in C++ STL Initialize a vector in C++ (6 different ways) Inheritance in C++ Map in C++ Standard Template Library (STL) std::sort() in C++ STL
[ { "code": null, "e": 24448, "s": 24420, "text": "\n19 Apr, 2022" }, { "code": null, "e": 24663, "s": 24448, "text": "Array of Objects: When a class is defined, only the specification for the object is defined; no memory or storage is allocated. To use the data and access functions defined in the class, you need to create objects." }, { "code": null, "e": 24672, "s": 24663, "text": "Syntax: " }, { "code": null, "e": 24713, "s": 24672, "text": "ClassName ObjectName[number of objects];" }, { "code": null, "e": 24800, "s": 24713, "text": "Different methods to initialize the Array of objects with parameterized constructors: " }, { "code": null, "e": 24998, "s": 24800, "text": " 1. Using bunch of function calls as elements of array: It’s just like normal array declaration but here we initialize the array with function calls of constructor as elements of that array." }, { "code": null, "e": 25002, "s": 24998, "text": "C++" }, { "code": "#include <iostream>using namespace std; class Test { // private variables.private: int x, y; public: // parameterized constructor Test(int cx, int cy) { x = cx; y = cy; } // method to add two numbers void add() { cout << x + y << endl; }};int main(){ // Initializing 3 array Objects with function calls of // parameterized constructor as elements of that array Test obj[] = { Test(1, 1), Test(2, 2), Test(3, 3) }; // using add method for each of three elements. for (int i = 0; i < 3; i++) { obj[i].add(); } return 0;}", "e": 25587, "s": 25002, "text": null }, { "code": null, "e": 25902, "s": 25587, "text": " 2. Using malloc(): To avoid the call of a non-parameterized constructor, use malloc() method. “malloc” or “memory allocation” method in C++ is used to dynamically allocate a single large block of memory with the specified size. It returns a pointer of type void which can be cast into a pointer of any form." }, { "code": null, "e": 25906, "s": 25902, "text": "C++" }, { "code": "#include <iostream>#define N 5 using namespace std; class Test { // private variables int x, y; public: // parameterized constructor Test(int x, int y) { this->x = x; this->y = y; } // function to print void print() { cout << x << \" \" << y << endl; }}; int main(){ // allocating dynamic array // of Size N using malloc() Test* arr = (Test*)malloc(sizeof(Test) * N); // calling constructor // for each index of array for (int i = 0; i < N; i++) { arr[i] = Test(i, i + 1); } // printing contents of array for (int i = 0; i < N; i++) { arr[i].print(); } return 0;}", "e": 26557, "s": 25906, "text": null }, { "code": null, "e": 26577, "s": 26557, "text": "0 1\n1 2\n2 3\n3 4\n4 5" }, { "code": null, "e": 27025, "s": 26579, "text": " 3. Using new keyword: The new operator denotes a request for memory allocation on the Heap. If sufficient memory is available, the new operator initializes the memory and returns the address of the newly allocated and initialized memory to the pointer variable. Here, pointer-variable is the pointer of type data-type. Data-type could be any built-in data type including array or any user-defined data types including structure and class." }, { "code": null, "e": 27184, "s": 27025, "text": "For dynamic initialization new keyword require non parameterized constructor if we add a parameterized constructor. So we will use a dummy constructor for it." }, { "code": null, "e": 27188, "s": 27184, "text": "C++" }, { "code": "#include <iostream>#define N 5 using namespace std; class Test { // private variables int x, y; public: // dummy constructor Test() {} // parameterized constructor Test(int x, int y) { this->x = x; this->y = y; } // function to print void print() { cout << x << \" \" << y << endl; }}; int main(){ // allocating dynamic array // of Size N using new keyword Test* arr = new Test[N]; // calling constructor // for each index of array for (int i = 0; i < N; i++) { arr[i] = Test(i, i + 1); } // printing contents of array for (int i = 0; i < N; i++) { arr[i].print(); } return 0;}", "e": 27861, "s": 27188, "text": null }, { "code": null, "e": 27881, "s": 27861, "text": "0 1\n1 2\n2 3\n3 4\n4 5" }, { "code": null, "e": 27964, "s": 27883, "text": "If we don’t use the dummy constructor compiler would show the error given below " }, { "code": null, "e": 27982, "s": 27964, "text": "Compiler Error: " }, { "code": null, "e": 28065, "s": 27982, "text": "error: no matching function for call to ‘Test::Test()’\n Test *arr=new Test[N];" }, { "code": null, "e": 28599, "s": 28065, "text": " 4. Using Double pointer (pointer to pointer concept): A pointer to a pointer is a form of multiple indirections, or a chain of pointers. Normally, a pointer contains the address of a variable. When we define a pointer to a pointer, the first pointer contains the address of the second pointer, which points to the location that contains the actual value as shown below.Here we can assign a number of blocks to be allocated and thus for every index we have to call parameterized constructor using the new keyword to initialize." }, { "code": null, "e": 28603, "s": 28599, "text": "C++" }, { "code": "#include <iostream>#define N 5 using namespace std; class Test { // private variables int x, y; public: // parameterized constructor Test(int x, int y) : x(x) , y(y) { } // function to print void print() { cout << x << \" \" << y << endl; }}; int main(){ // allocating array using // pointer to pointer concept Test** arr = new Test*[N]; // calling constructor for each index // of array using new keyword for (int i = 0; i < N; i++) { arr[i] = new Test(i, i + 1); } // printing contents of array for (int i = 0; i < N; i++) { arr[i]->print(); } return 0;}", "e": 29248, "s": 28603, "text": null }, { "code": null, "e": 29268, "s": 29248, "text": "0 1\n1 2\n2 3\n3 4\n4 5" }, { "code": null, "e": 29958, "s": 29270, "text": " 5. Using Vector of type class: Vector is one of the most powerful element of Standard Template Library makes it easy to write any complex codes related to static or dynamic array in an efficient way. It takes one parameter that can be of any type and thus we use our Class as a type of vector and push Objects in every iteration of the loop. Vectors are same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container. Vector elements are placed in contiguous storage so that they can be accessed and traversed using iterators. In vectors, data is inserted at the end. " }, { "code": null, "e": 29962, "s": 29958, "text": "C++" }, { "code": "#include <iostream>#include <vector>#define N 5 using namespace std; class Test { // private variables int x, y; public: // parameterized constructor Test(int x, int y) : x(x) , y(y) { } // function to print void print() { cout << x << \" \" << y << endl; }}; int main(){ // vector of type Test class vector<Test> v; // inserting object at the end of vector for (int i = 0; i < N; i++) v.push_back(Test(i, i + 1)); // printing object content for (int i = 0; i < N; i++) v[i].print(); return 0;}", "e": 30533, "s": 29962, "text": null }, { "code": null, "e": 30553, "s": 30533, "text": "0 1\n1 2\n2 3\n3 4\n4 5" }, { "code": null, "e": 30573, "s": 30559, "text": "viveksuman393" }, { "code": null, "e": 30590, "s": 30573, "text": "akshaysingh98088" }, { "code": null, "e": 30604, "s": 30590, "text": "chhabradhanvi" }, { "code": null, "e": 30613, "s": 30604, "text": "rkbhola5" }, { "code": null, "e": 30634, "s": 30613, "text": "C++-Class and Object" }, { "code": null, "e": 30660, "s": 30634, "text": "Dynamic Memory Allocation" }, { "code": null, "e": 30667, "s": 30660, "text": "Arrays" }, { "code": null, "e": 30671, "s": 30667, "text": "C++" }, { "code": null, "e": 30678, "s": 30671, "text": "Arrays" }, { "code": null, "e": 30682, "s": 30678, "text": "CPP" }, { "code": null, "e": 30780, "s": 30682, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30848, "s": 30780, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 30880, "s": 30848, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 30903, "s": 30880, "text": "Introduction to Arrays" }, { "code": null, "e": 30948, "s": 30903, "text": "Python | Using 2D arrays/lists the right way" }, { "code": null, "e": 30969, "s": 30948, "text": "Linked List vs Array" }, { "code": null, "e": 30987, "s": 30969, "text": "Vector in C++ STL" }, { "code": null, "e": 31033, "s": 30987, "text": "Initialize a vector in C++ (6 different ways)" }, { "code": null, "e": 31052, "s": 31033, "text": "Inheritance in C++" }, { "code": null, "e": 31095, "s": 31052, "text": "Map in C++ Standard Template Library (STL)" } ]
Intro to Geographical Plotting. Visualizing geographic data on any map... | by Mamtha | Towards Data Science
In the field of data science, we often work on visualizing the data which gives us clear patterns about the data and makes it easy for analysis. Luckily python provides powerful data visualization tools for this purpose. In addition, it would be more interesting to visualize map-based data around the world or any specific country which gives us cool insights about the geographical data. Geographic maps are important because they provide context for our data values. So, let’s check out Python’s Interactive Visualization tool — plotly.Using Plotly we can create beautiful Choropleth maps from the geo-data. Choropleth maps helps us to plot out information on a global or national wide. It allows us to see how a certain variable is distributed across a territory. In this blog, we will focus on using plotly for plotting choropleth maps. Plotly is an open-source library which allows us to create interactive plots that can be used in dashboards or websites. Plotly is also a company, that supports online and offline to host data visualisatoins. Let’s use offline mode for now as it is an open-source and as it makes easy to work inside our Python Jupyter notebook. Geographical plotting using plotly is a bit challenging at first due to its various formats of data, so please refer this cheat sheet for syntax of all types of plotly plots. Let’s get started with the below example to understand this concept... Let’s find out Starbucks Stores across the globe and also on a national scale and visualize this data using choropleth maps. Dataset(directory.csv) can be downloaded from here. This dataset includes a record for every Starbucks store location currently in operation as of February 2017. We will go through the following steps: Import all the libraries and set our Jupyter notebook to work in offline mode.Extract Starbucks data to Dataframe using pandas.Create ‘data’ and ‘layout’ objects for ‘USA Country’ and plot the choropleth map.Create ‘data’ and ‘layout’ objects for ‘World Wide’ and plot the choropleth map. Import all the libraries and set our Jupyter notebook to work in offline mode. Extract Starbucks data to Dataframe using pandas. Create ‘data’ and ‘layout’ objects for ‘USA Country’ and plot the choropleth map. Create ‘data’ and ‘layout’ objects for ‘World Wide’ and plot the choropleth map. Let’s first install plotly to Jupyter notebook pip install plotly Step 1: import plotly.plotly as py import plotly.graph_objs as go #importing graphical objectsfrom plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot download_plotlyjs allows plotly to work in offline mode.init_notebook_mode connects Javascript to our notebook. Step 2: import pandas as pddf = pd.read_csv('directory.csv') Before moving to step 3, let’s quickly perform below tasks: ☑ Get subset data (US Country data) from the above dataset and assign it to a new data frame.☑ Add one new column to the dataset — ‘Store Count’, to get the total number of stores for each state. df_US = df[df['Country'] == 'US'] Now to add new column ‘Store Count’ to dataframe, we can use groupby() on ‘State/Province’ column as below df_US['Store Count'] = df_US['Store Number'].groupby(df_US['State/Province']).transform('count') df_US[df_US['State/Province'] == 'CA'][['State/Province','Store Count']].head(1) # to check num of stores in 'California' Step 3: Plotting ‘USA Country’ map Let’s define our ‘data’ and ‘layout’ objects as below: data = dict(type='choropleth', locations = df_US['State/Province'], locationmode = 'USA-states', colorscale = 'Reds', text = df_US['Brand'], z = df_US['Store Count'], colorbar = {'title':"Stores Count"} ) type: Defines the type of the map(choropleth)locations: Names of all stateslocationmode: Specify the location by giving a Country namecolorscale: Displays a color map. (Refer below for more colorscales)text: Displays a text when hovering over the map for each state elementz : Integer value which displays ‘Store Count’ for each state elementcolorbar : Title for the right sidebar colorscales: [‘Greys’, ‘YlGnBu’, ‘Greens’, ‘YlOrRd’, ‘Bluered’, ‘RdBu’, ‘Reds’, ‘Blues’, ‘Picnic’, ‘Rainbow’, ‘Portland’, ‘Jet’, ‘Hot’, ‘Blackbody’, ‘Earth’, ‘Electric’, ‘Viridis’, ‘Cividis’] layout = dict(title = 'Starbucks locations in USA Map', geo = dict(scope='usa') ) Now, we can use go.Figure() method to create an object for the map and then use iplot() method to generate the plot choromap = go.Figure(data = [data],layout = layout)iplot(choromap) Cool! Our choropleth map for the ‘US’ country has been generated and from above we can see that each state displays text, number of stores and state names when hovering over each element on the map and the more concentrated the data is in one particular area, the deeper the shade of color on the map. Here ‘California’ has more number of stores (2821) and so the color is so deep. Similar to Choropleth maps, we have another cool interactive map called ‘Scatter Plot’. ‘Scatter Plot’ provides each data point (which is represented as a marker point) on the map and location which is represented by the x (Longitude) and y(Latitude) columns. We can use columns - ‘Longitude’ and ‘Latitude’ from our dataset to generate scatterplot. Let’s create a scatter plot using the below code. data = go.Scattergeo( lon = df_US['Longitude'], lat = df_US['Latitude'], text = df_US['text'], mode = 'markers', marker = dict(symbol = 'star',size=5,colorscale = 'Reds' ), marker_color = df_US['Store Count'], )layout = dict(title = 'Starbucks locations in USA Map', geo_scope = 'usa' )choromap = go.Figure(data = [data],layout = layout)iplot(choromap) Step 4: Plotting ‘World’ map Added a new column ‘Store Count’ as we did before. And also I have added one more column to dataset ‘CountryCode’ which has ISO 3(3 digits) code. Here is the code for creating a choropleth world map... data = dict( type = 'choropleth', locations = df['CountryCode'], z = df['Store Count'], text = df['Brand'], colorbar = {'title' : 'Starbucks Stores - World Wide'}, )layout = dict( title = 'Stores Count', geo = dict( showframe = False, projection = {'type':'natural earth'} ))choromap = go.Figure(data = [data],layout = layout)iplot(choromap) This concludes our geographical data visualization section. Please check out plotly maps official page to view more interesting types of plots. I hope you found this article useful and please do share your comments/feedback in the comments section below. Thank you!!
[ { "code": null, "e": 641, "s": 171, "text": "In the field of data science, we often work on visualizing the data which gives us clear patterns about the data and makes it easy for analysis. Luckily python provides powerful data visualization tools for this purpose. In addition, it would be more interesting to visualize map-based data around the world or any specific country which gives us cool insights about the geographical data. Geographic maps are important because they provide context for our data values." }, { "code": null, "e": 782, "s": 641, "text": "So, let’s check out Python’s Interactive Visualization tool — plotly.Using Plotly we can create beautiful Choropleth maps from the geo-data." }, { "code": null, "e": 1013, "s": 782, "text": "Choropleth maps helps us to plot out information on a global or national wide. It allows us to see how a certain variable is distributed across a territory. In this blog, we will focus on using plotly for plotting choropleth maps." }, { "code": null, "e": 1342, "s": 1013, "text": "Plotly is an open-source library which allows us to create interactive plots that can be used in dashboards or websites. Plotly is also a company, that supports online and offline to host data visualisatoins. Let’s use offline mode for now as it is an open-source and as it makes easy to work inside our Python Jupyter notebook." }, { "code": null, "e": 1517, "s": 1342, "text": "Geographical plotting using plotly is a bit challenging at first due to its various formats of data, so please refer this cheat sheet for syntax of all types of plotly plots." }, { "code": null, "e": 1588, "s": 1517, "text": "Let’s get started with the below example to understand this concept..." }, { "code": null, "e": 1875, "s": 1588, "text": "Let’s find out Starbucks Stores across the globe and also on a national scale and visualize this data using choropleth maps. Dataset(directory.csv) can be downloaded from here. This dataset includes a record for every Starbucks store location currently in operation as of February 2017." }, { "code": null, "e": 1915, "s": 1875, "text": "We will go through the following steps:" }, { "code": null, "e": 2204, "s": 1915, "text": "Import all the libraries and set our Jupyter notebook to work in offline mode.Extract Starbucks data to Dataframe using pandas.Create ‘data’ and ‘layout’ objects for ‘USA Country’ and plot the choropleth map.Create ‘data’ and ‘layout’ objects for ‘World Wide’ and plot the choropleth map." }, { "code": null, "e": 2283, "s": 2204, "text": "Import all the libraries and set our Jupyter notebook to work in offline mode." }, { "code": null, "e": 2333, "s": 2283, "text": "Extract Starbucks data to Dataframe using pandas." }, { "code": null, "e": 2415, "s": 2333, "text": "Create ‘data’ and ‘layout’ objects for ‘USA Country’ and plot the choropleth map." }, { "code": null, "e": 2496, "s": 2415, "text": "Create ‘data’ and ‘layout’ objects for ‘World Wide’ and plot the choropleth map." }, { "code": null, "e": 2543, "s": 2496, "text": "Let’s first install plotly to Jupyter notebook" }, { "code": null, "e": 2562, "s": 2543, "text": "pip install plotly" }, { "code": null, "e": 2570, "s": 2562, "text": "Step 1:" }, { "code": null, "e": 2734, "s": 2570, "text": "import plotly.plotly as py import plotly.graph_objs as go #importing graphical objectsfrom plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot" }, { "code": null, "e": 2846, "s": 2734, "text": "download_plotlyjs allows plotly to work in offline mode.init_notebook_mode connects Javascript to our notebook." }, { "code": null, "e": 2854, "s": 2846, "text": "Step 2:" }, { "code": null, "e": 2907, "s": 2854, "text": "import pandas as pddf = pd.read_csv('directory.csv')" }, { "code": null, "e": 2967, "s": 2907, "text": "Before moving to step 3, let’s quickly perform below tasks:" }, { "code": null, "e": 3163, "s": 2967, "text": "☑ Get subset data (US Country data) from the above dataset and assign it to a new data frame.☑ Add one new column to the dataset — ‘Store Count’, to get the total number of stores for each state." }, { "code": null, "e": 3197, "s": 3163, "text": "df_US = df[df['Country'] == 'US']" }, { "code": null, "e": 3304, "s": 3197, "text": "Now to add new column ‘Store Count’ to dataframe, we can use groupby() on ‘State/Province’ column as below" }, { "code": null, "e": 3401, "s": 3304, "text": "df_US['Store Count'] = df_US['Store Number'].groupby(df_US['State/Province']).transform('count')" }, { "code": null, "e": 3524, "s": 3401, "text": "df_US[df_US['State/Province'] == 'CA'][['State/Province','Store Count']].head(1) # to check num of stores in 'California'" }, { "code": null, "e": 3559, "s": 3524, "text": "Step 3: Plotting ‘USA Country’ map" }, { "code": null, "e": 3614, "s": 3559, "text": "Let’s define our ‘data’ and ‘layout’ objects as below:" }, { "code": null, "e": 3896, "s": 3614, "text": "data = dict(type='choropleth', locations = df_US['State/Province'], locationmode = 'USA-states', colorscale = 'Reds', text = df_US['Brand'], z = df_US['Store Count'], colorbar = {'title':\"Stores Count\"} )" }, { "code": null, "e": 4277, "s": 3896, "text": "type: Defines the type of the map(choropleth)locations: Names of all stateslocationmode: Specify the location by giving a Country namecolorscale: Displays a color map. (Refer below for more colorscales)text: Displays a text when hovering over the map for each state elementz : Integer value which displays ‘Store Count’ for each state elementcolorbar : Title for the right sidebar" }, { "code": null, "e": 4470, "s": 4277, "text": "colorscales: [‘Greys’, ‘YlGnBu’, ‘Greens’, ‘YlOrRd’, ‘Bluered’, ‘RdBu’, ‘Reds’, ‘Blues’, ‘Picnic’, ‘Rainbow’, ‘Portland’, ‘Jet’, ‘Hot’, ‘Blackbody’, ‘Earth’, ‘Electric’, ‘Viridis’, ‘Cividis’]" }, { "code": null, "e": 4577, "s": 4470, "text": "layout = dict(title = 'Starbucks locations in USA Map', geo = dict(scope='usa') )" }, { "code": null, "e": 4693, "s": 4577, "text": "Now, we can use go.Figure() method to create an object for the map and then use iplot() method to generate the plot" }, { "code": null, "e": 4760, "s": 4693, "text": "choromap = go.Figure(data = [data],layout = layout)iplot(choromap)" }, { "code": null, "e": 5142, "s": 4760, "text": "Cool! Our choropleth map for the ‘US’ country has been generated and from above we can see that each state displays text, number of stores and state names when hovering over each element on the map and the more concentrated the data is in one particular area, the deeper the shade of color on the map. Here ‘California’ has more number of stores (2821) and so the color is so deep." }, { "code": null, "e": 5230, "s": 5142, "text": "Similar to Choropleth maps, we have another cool interactive map called ‘Scatter Plot’." }, { "code": null, "e": 5402, "s": 5230, "text": "‘Scatter Plot’ provides each data point (which is represented as a marker point) on the map and location which is represented by the x (Longitude) and y(Latitude) columns." }, { "code": null, "e": 5492, "s": 5402, "text": "We can use columns - ‘Longitude’ and ‘Latitude’ from our dataset to generate scatterplot." }, { "code": null, "e": 5542, "s": 5492, "text": "Let’s create a scatter plot using the below code." }, { "code": null, "e": 5990, "s": 5542, "text": "data = go.Scattergeo( lon = df_US['Longitude'], lat = df_US['Latitude'], text = df_US['text'], mode = 'markers', marker = dict(symbol = 'star',size=5,colorscale = 'Reds' ), marker_color = df_US['Store Count'], )layout = dict(title = 'Starbucks locations in USA Map', geo_scope = 'usa' )choromap = go.Figure(data = [data],layout = layout)iplot(choromap)" }, { "code": null, "e": 6019, "s": 5990, "text": "Step 4: Plotting ‘World’ map" }, { "code": null, "e": 6165, "s": 6019, "text": "Added a new column ‘Store Count’ as we did before. And also I have added one more column to dataset ‘CountryCode’ which has ISO 3(3 digits) code." }, { "code": null, "e": 6221, "s": 6165, "text": "Here is the code for creating a choropleth world map..." }, { "code": null, "e": 6634, "s": 6221, "text": "data = dict( type = 'choropleth', locations = df['CountryCode'], z = df['Store Count'], text = df['Brand'], colorbar = {'title' : 'Starbucks Stores - World Wide'}, )layout = dict( title = 'Stores Count', geo = dict( showframe = False, projection = {'type':'natural earth'} ))choromap = go.Figure(data = [data],layout = layout)iplot(choromap)" }, { "code": null, "e": 6778, "s": 6634, "text": "This concludes our geographical data visualization section. Please check out plotly maps official page to view more interesting types of plots." } ]
MySQL CREATE USER with a variable?
You can use a dynamic query for this. First set the variable name for username and variable name for a password. The syntax is as follows − SET @anyVariableName=’yourUserName’; SET @anyVariableName1=’yourpassword’; Now you can use the CONCAT() function from MySQL. The syntax is as follows − SET @yourQueryName = CONCAT (' CREATE USER "',@anyVariableName,'"@"localhost" IDENTIFIED BY "',@anyVariableName1,'" ' ); Let us use the prepared statement PREPARE. The syntax is as follows − PREPARE yourStatementVariableName FROM @yourQueryName; Now you can execute the statement. The syntax is as follows − EXECUTE yourStatementVariableName; Deallocate the above using the DEALLOCATE PREPARE. The syntax is as follows − DEALLOCATE PREPARE yourStatementVariableName; To understand the above syntax, let us follows all the steps − Step 1 − First create two variables, one for username and second for a password using SET command. the query is as follows to create a username − mysql> set @UserName:='John Doe'; Query OK, 0 rows affected (0.00 sec) The query to create a password. mysql> set @Password:='John Doe 123456'; Query OK, 0 rows affected (0.00 sec) Step 2 − Now use the CONCAT() function to create a user. The query is as follows − mysql> SET @CreationOfUser = CONCAT(' '> CREATE USER "',@UserName,'"@"localhost" IDENTIFIED BY "',@Password,'" ' -> ); Query OK, 0 rows affected (0.02 sec) In the above query, we have used @UserName variable name and @Password variable name to create a user with name and password. Step 3 − Now you need to prepare the statement using the above user-defined variable @CreationOfUser. The query is as follows − mysql> PREPARE st FROM @CreationOfUser; Query OK, 0 rows affected (0.00 sec) Statement prepared Step 4 − Execute the above-prepared statement. The query is as follows − mysql> EXECUTE st; Query OK, 0 rows affected (0.37 sec) Step 5 − Check the user “John Doe” has been created in the MySQL.user table − mysql> select user,host from MySQL.user; The following is the output − +------------------+-----------+ | user | host | +------------------+-----------+ | Manish | % | | User2 | % | | mysql.infoschema | % | | mysql.session | % | | mysql.sys | % | | root | % | | @UserName@ | localhost | | Adam Smith | localhost | | John | localhost | | John Doe | localhost | | User1 | localhost | | am | localhost | | hbstudent | localhost | +------------------+-----------+ 13 rows in set (0.00 sec) Yes, we have a username with John Doe. Step 6 − Now, DEALLOCATE the prepared statement. The query is as follows − mysql> DEALLOCATE PREPARE st; Query OK, 0 rows affected (0.00 sec)
[ { "code": null, "e": 1202, "s": 1062, "text": "You can use a dynamic query for this. First set the variable name for username and variable name for a password. The syntax is as follows −" }, { "code": null, "e": 1277, "s": 1202, "text": "SET @anyVariableName=’yourUserName’;\nSET @anyVariableName1=’yourpassword’;" }, { "code": null, "e": 1354, "s": 1277, "text": "Now you can use the CONCAT() function from MySQL. The syntax is as follows −" }, { "code": null, "e": 1478, "s": 1354, "text": "SET @yourQueryName = CONCAT\n('\n CREATE USER \"',@anyVariableName,'\"@\"localhost\" IDENTIFIED BY \"',@anyVariableName1,'\" '\n);" }, { "code": null, "e": 1548, "s": 1478, "text": "Let us use the prepared statement PREPARE. The syntax is as follows −" }, { "code": null, "e": 1603, "s": 1548, "text": "PREPARE yourStatementVariableName FROM @yourQueryName;" }, { "code": null, "e": 1665, "s": 1603, "text": "Now you can execute the statement. The syntax is as follows −" }, { "code": null, "e": 1700, "s": 1665, "text": "EXECUTE yourStatementVariableName;" }, { "code": null, "e": 1778, "s": 1700, "text": "Deallocate the above using the DEALLOCATE PREPARE. The syntax is as follows −" }, { "code": null, "e": 1824, "s": 1778, "text": "DEALLOCATE PREPARE yourStatementVariableName;" }, { "code": null, "e": 1887, "s": 1824, "text": "To understand the above syntax, let us follows all the steps −" }, { "code": null, "e": 1986, "s": 1887, "text": "Step 1 − First create two variables, one for username and second for a password using SET command." }, { "code": null, "e": 2033, "s": 1986, "text": "the query is as follows to create a username −" }, { "code": null, "e": 2104, "s": 2033, "text": "mysql> set @UserName:='John Doe';\nQuery OK, 0 rows affected (0.00 sec)" }, { "code": null, "e": 2136, "s": 2104, "text": "The query to create a password." }, { "code": null, "e": 2214, "s": 2136, "text": "mysql> set @Password:='John Doe 123456';\nQuery OK, 0 rows affected (0.00 sec)" }, { "code": null, "e": 2297, "s": 2214, "text": "Step 2 − Now use the CONCAT() function to create a user. The query is as follows −" }, { "code": null, "e": 2459, "s": 2297, "text": "mysql> SET @CreationOfUser = CONCAT('\n '> CREATE USER \"',@UserName,'\"@\"localhost\" IDENTIFIED BY \"',@Password,'\" '\n -> );\nQuery OK, 0 rows affected (0.02 sec)" }, { "code": null, "e": 2585, "s": 2459, "text": "In the above query, we have used @UserName variable name and @Password variable name to create a user with name and password." }, { "code": null, "e": 2713, "s": 2585, "text": "Step 3 − Now you need to prepare the statement using the above user-defined variable @CreationOfUser. The query is as follows −" }, { "code": null, "e": 2809, "s": 2713, "text": "mysql> PREPARE st FROM @CreationOfUser;\nQuery OK, 0 rows affected (0.00 sec)\nStatement prepared" }, { "code": null, "e": 2882, "s": 2809, "text": "Step 4 − Execute the above-prepared statement. The query is as follows −" }, { "code": null, "e": 2938, "s": 2882, "text": "mysql> EXECUTE st;\nQuery OK, 0 rows affected (0.37 sec)" }, { "code": null, "e": 3016, "s": 2938, "text": "Step 5 − Check the user “John Doe” has been created in the MySQL.user table −" }, { "code": null, "e": 3057, "s": 3016, "text": "mysql> select user,host from MySQL.user;" }, { "code": null, "e": 3087, "s": 3057, "text": "The following is the output −" }, { "code": null, "e": 3674, "s": 3087, "text": "+------------------+-----------+\n| user | host |\n+------------------+-----------+\n| Manish | % |\n| User2 | % |\n| mysql.infoschema | % |\n| mysql.session | % |\n| mysql.sys | % |\n| root | % |\n| @UserName@ | localhost |\n| Adam Smith | localhost |\n| John | localhost |\n| John Doe | localhost |\n| User1 | localhost |\n| am | localhost |\n| hbstudent | localhost |\n+------------------+-----------+\n13 rows in set (0.00 sec)" }, { "code": null, "e": 3713, "s": 3674, "text": "Yes, we have a username with John Doe." }, { "code": null, "e": 3788, "s": 3713, "text": "Step 6 − Now, DEALLOCATE the prepared statement. The query is as follows −" }, { "code": null, "e": 3855, "s": 3788, "text": "mysql> DEALLOCATE PREPARE st;\nQuery OK, 0 rows affected (0.00 sec)" } ]
Spring Boot - Rest Controller Unit Test
Spring Boot provides an easy way to write a Unit Test for Rest Controller file. With the help of SpringJUnit4ClassRunner and MockMvc, we can create a web application context to write Unit Test for Rest Controller file. Unit Tests should be written under the src/test/java directory and classpath resources for writing a test should be placed under the src/test/resources directory. For Writing a Unit Test, we need to add the Spring Boot Starter Test dependency in your build configuration file as shown below. <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> Gradle users can add the following dependency in your build.gradle file. testCompile('org.springframework.boot:spring-boot-starter-test') Before writing a Test case, we should first build RESTful web services. For further information on building RESTful web services, please refer to the chapter on the same given in this tutorial. In this section, let us see how to write a Unit Test for the REST Controller. First, we need to create Abstract class file used to create web application context by using MockMvc and define the mapToJson() and mapFromJson() methods to convert the Java object into JSON string and convert the JSON string into Java object. package com.tutorialspoint.demo; import java.io.IOException; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = DemoApplication.class) @WebAppConfiguration public abstract class AbstractTest { protected MockMvc mvc; @Autowired WebApplicationContext webApplicationContext; protected void setUp() { mvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); } protected String mapToJson(Object obj) throws JsonProcessingException { ObjectMapper objectMapper = new ObjectMapper(); return objectMapper.writeValueAsString(obj); } protected <T> T mapFromJson(String json, Class<T> clazz) throws JsonParseException, JsonMappingException, IOException { ObjectMapper objectMapper = new ObjectMapper(); return objectMapper.readValue(json, clazz); } } Next, write a class file that extends the AbstractTest class and write a Unit Test for each method such GET, POST, PUT and DELETE. The code for GET API Test case is given below. This API is to view the list of products. @Test public void getProductsList() throws Exception { String uri = "/products"; MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.get(uri) .accept(MediaType.APPLICATION_JSON_VALUE)).andReturn(); int status = mvcResult.getResponse().getStatus(); assertEquals(200, status); String content = mvcResult.getResponse().getContentAsString(); Product[] productlist = super.mapFromJson(content, Product[].class); assertTrue(productlist.length > 0); } The code for POST API test case is given below. This API is to create a product. @Test public void createProduct() throws Exception { String uri = "/products"; Product product = new Product(); product.setId("3"); product.setName("Ginger"); String inputJson = super.mapToJson(product); MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.post(uri) .contentType(MediaType.APPLICATION_JSON_VALUE).content(inputJson)).andReturn(); int status = mvcResult.getResponse().getStatus(); assertEquals(201, status); String content = mvcResult.getResponse().getContentAsString(); assertEquals(content, "Product is created successfully"); } The code for PUT API Test case is given below. This API is to update the existing product. @Test public void updateProduct() throws Exception { String uri = "/products/2"; Product product = new Product(); product.setName("Lemon"); String inputJson = super.mapToJson(product); MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.put(uri) .contentType(MediaType.APPLICATION_JSON_VALUE).content(inputJson)).andReturn(); int status = mvcResult.getResponse().getStatus(); assertEquals(200, status); String content = mvcResult.getResponse().getContentAsString(); assertEquals(content, "Product is updated successsfully"); } The code for Delete API Test case is given below. This API will delete the existing product. @Test public void deleteProduct() throws Exception { String uri = "/products/2"; MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.delete(uri)).andReturn(); int status = mvcResult.getResponse().getStatus(); assertEquals(200, status); String content = mvcResult.getResponse().getContentAsString(); assertEquals(content, "Product is deleted successsfully"); } The full Controller Test class file is given below − package com.tutorialspoint.demo; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import com.tutorialspoint.demo.model.Product; public class ProductServiceControllerTest extends AbstractTest { @Override @Before public void setUp() { super.setUp(); } @Test public void getProductsList() throws Exception { String uri = "/products"; MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.get(uri) .accept(MediaType.APPLICATION_JSON_VALUE)).andReturn(); int status = mvcResult.getResponse().getStatus(); assertEquals(200, status); String content = mvcResult.getResponse().getContentAsString(); Product[] productlist = super.mapFromJson(content, Product[].class); assertTrue(productlist.length > 0); } @Test public void createProduct() throws Exception { String uri = "/products"; Product product = new Product(); product.setId("3"); product.setName("Ginger"); String inputJson = super.mapToJson(product); MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.post(uri) .contentType(MediaType.APPLICATION_JSON_VALUE) .content(inputJson)).andReturn(); int status = mvcResult.getResponse().getStatus(); assertEquals(201, status); String content = mvcResult.getResponse().getContentAsString(); assertEquals(content, "Product is created successfully"); } @Test public void updateProduct() throws Exception { String uri = "/products/2"; Product product = new Product(); product.setName("Lemon"); String inputJson = super.mapToJson(product); MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.put(uri) .contentType(MediaType.APPLICATION_JSON_VALUE) .content(inputJson)).andReturn(); int status = mvcResult.getResponse().getStatus(); assertEquals(200, status); String content = mvcResult.getResponse().getContentAsString(); assertEquals(content, "Product is updated successsfully"); } @Test public void deleteProduct() throws Exception { String uri = "/products/2"; MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.delete(uri)).andReturn(); int status = mvcResult.getResponse().getStatus(); assertEquals(200, status); String content = mvcResult.getResponse().getContentAsString(); assertEquals(content, "Product is deleted successsfully"); } } You can create an executable JAR file, and run the Spring Boot application by using the Maven or Gradle commands given below − For Maven, you can use the command given below − mvn clean install Now, you can see the test results in console window. For Gradle, you can use the command as shown below − gradle clean build You can see the rest results in console window as shown below. 102 Lectures 8 hours Karthikeya T 39 Lectures 5 hours Chaand Sheikh 73 Lectures 5.5 hours Senol Atac 62 Lectures 4.5 hours Senol Atac 67 Lectures 4.5 hours Senol Atac 69 Lectures 5 hours Senol Atac Print Add Notes Bookmark this page
[ { "code": null, "e": 3244, "s": 3025, "text": "Spring Boot provides an easy way to write a Unit Test for Rest Controller file. With the help of SpringJUnit4ClassRunner and MockMvc, we can create a web application context to write Unit Test for Rest Controller file." }, { "code": null, "e": 3407, "s": 3244, "text": "Unit Tests should be written under the src/test/java directory and classpath resources for writing a test should be placed under the src/test/resources directory." }, { "code": null, "e": 3536, "s": 3407, "text": "For Writing a Unit Test, we need to add the Spring Boot Starter Test dependency in your build configuration file as shown below." }, { "code": null, "e": 3686, "s": 3536, "text": "<dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-test</artifactId>\n <scope>test</scope>\n</dependency>" }, { "code": null, "e": 3759, "s": 3686, "text": "Gradle users can add the following dependency in your build.gradle file." }, { "code": null, "e": 3825, "s": 3759, "text": "testCompile('org.springframework.boot:spring-boot-starter-test')\n" }, { "code": null, "e": 4019, "s": 3825, "text": "Before writing a Test case, we should first build RESTful web services. For further information on building RESTful web services, please refer to the chapter on the same given in this tutorial." }, { "code": null, "e": 4097, "s": 4019, "text": "In this section, let us see how to write a Unit Test for the REST Controller." }, { "code": null, "e": 4341, "s": 4097, "text": "First, we need to create Abstract class file used to create web application context by using MockMvc and define the mapToJson() and mapFromJson() methods to convert the Java object into JSON string and convert the JSON string into Java object." }, { "code": null, "e": 5886, "s": 4341, "text": "package com.tutorialspoint.demo;\n\nimport java.io.IOException;\nimport org.junit.runner.RunWith;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.boot.test.context.SpringBootTest;\nimport org.springframework.test.context.junit4.SpringJUnit4ClassRunner;\nimport org.springframework.test.context.web.WebAppConfiguration;\nimport org.springframework.test.web.servlet.MockMvc;\nimport org.springframework.test.web.servlet.setup.MockMvcBuilders;\nimport org.springframework.web.context.WebApplicationContext;\n\nimport com.fasterxml.jackson.core.JsonParseException;\nimport com.fasterxml.jackson.core.JsonProcessingException;\nimport com.fasterxml.jackson.databind.JsonMappingException;\nimport com.fasterxml.jackson.databind.ObjectMapper;\n\n@RunWith(SpringJUnit4ClassRunner.class)\n@SpringBootTest(classes = DemoApplication.class)\n@WebAppConfiguration\npublic abstract class AbstractTest {\n protected MockMvc mvc;\n @Autowired\n WebApplicationContext webApplicationContext;\n\n protected void setUp() {\n mvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();\n }\n protected String mapToJson(Object obj) throws JsonProcessingException {\n ObjectMapper objectMapper = new ObjectMapper();\n return objectMapper.writeValueAsString(obj);\n }\n protected <T> T mapFromJson(String json, Class<T> clazz)\n throws JsonParseException, JsonMappingException, IOException {\n \n ObjectMapper objectMapper = new ObjectMapper();\n return objectMapper.readValue(json, clazz);\n }\n}" }, { "code": null, "e": 6017, "s": 5886, "text": "Next, write a class file that extends the AbstractTest class and write a Unit Test for each method such GET, POST, PUT and DELETE." }, { "code": null, "e": 6106, "s": 6017, "text": "The code for GET API Test case is given below. This API is to view the list of products." }, { "code": null, "e": 6587, "s": 6106, "text": "@Test\npublic void getProductsList() throws Exception {\n String uri = \"/products\";\n MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.get(uri)\n .accept(MediaType.APPLICATION_JSON_VALUE)).andReturn();\n \n int status = mvcResult.getResponse().getStatus();\n assertEquals(200, status);\n String content = mvcResult.getResponse().getContentAsString();\n Product[] productlist = super.mapFromJson(content, Product[].class);\n assertTrue(productlist.length > 0);\n}" }, { "code": null, "e": 6668, "s": 6587, "text": "The code for POST API test case is given below. This API is to create a product." }, { "code": null, "e": 7263, "s": 6668, "text": "@Test\npublic void createProduct() throws Exception {\n String uri = \"/products\";\n Product product = new Product();\n product.setId(\"3\");\n product.setName(\"Ginger\");\n \n String inputJson = super.mapToJson(product);\n MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.post(uri)\n .contentType(MediaType.APPLICATION_JSON_VALUE).content(inputJson)).andReturn();\n \n int status = mvcResult.getResponse().getStatus();\n assertEquals(201, status);\n String content = mvcResult.getResponse().getContentAsString();\n assertEquals(content, \"Product is created successfully\");\n}" }, { "code": null, "e": 7354, "s": 7263, "text": "The code for PUT API Test case is given below. This API is to update the existing product." }, { "code": null, "e": 7927, "s": 7354, "text": "@Test\npublic void updateProduct() throws Exception {\n String uri = \"/products/2\";\n Product product = new Product();\n product.setName(\"Lemon\");\n \n String inputJson = super.mapToJson(product);\n MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.put(uri)\n .contentType(MediaType.APPLICATION_JSON_VALUE).content(inputJson)).andReturn();\n \n int status = mvcResult.getResponse().getStatus();\n assertEquals(200, status);\n String content = mvcResult.getResponse().getContentAsString();\n assertEquals(content, \"Product is updated successsfully\");\n}" }, { "code": null, "e": 8020, "s": 7927, "text": "The code for Delete API Test case is given below. This API will delete the existing product." }, { "code": null, "e": 8403, "s": 8020, "text": "@Test\npublic void deleteProduct() throws Exception {\n String uri = \"/products/2\";\n MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.delete(uri)).andReturn();\n int status = mvcResult.getResponse().getStatus();\n assertEquals(200, status);\n String content = mvcResult.getResponse().getContentAsString();\n assertEquals(content, \"Product is deleted successsfully\");\n}" }, { "code": null, "e": 8456, "s": 8403, "text": "The full Controller Test class file is given below −" }, { "code": null, "e": 11185, "s": 8456, "text": "package com.tutorialspoint.demo;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertTrue;\n\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.springframework.http.MediaType;\nimport org.springframework.test.web.servlet.MvcResult;\nimport org.springframework.test.web.servlet.request.MockMvcRequestBuilders;\n\nimport com.tutorialspoint.demo.model.Product;\n\npublic class ProductServiceControllerTest extends AbstractTest {\n @Override\n @Before\n public void setUp() {\n super.setUp();\n }\n @Test\n public void getProductsList() throws Exception {\n String uri = \"/products\";\n MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.get(uri)\n .accept(MediaType.APPLICATION_JSON_VALUE)).andReturn();\n \n int status = mvcResult.getResponse().getStatus();\n assertEquals(200, status);\n String content = mvcResult.getResponse().getContentAsString();\n Product[] productlist = super.mapFromJson(content, Product[].class);\n assertTrue(productlist.length > 0);\n }\n @Test\n public void createProduct() throws Exception {\n String uri = \"/products\";\n Product product = new Product();\n product.setId(\"3\");\n product.setName(\"Ginger\");\n String inputJson = super.mapToJson(product);\n MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.post(uri)\n .contentType(MediaType.APPLICATION_JSON_VALUE)\n .content(inputJson)).andReturn();\n \n int status = mvcResult.getResponse().getStatus();\n assertEquals(201, status);\n String content = mvcResult.getResponse().getContentAsString();\n assertEquals(content, \"Product is created successfully\");\n }\n @Test\n public void updateProduct() throws Exception {\n String uri = \"/products/2\";\n Product product = new Product();\n product.setName(\"Lemon\");\n String inputJson = super.mapToJson(product);\n MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.put(uri)\n .contentType(MediaType.APPLICATION_JSON_VALUE)\n .content(inputJson)).andReturn();\n \n int status = mvcResult.getResponse().getStatus();\n assertEquals(200, status);\n String content = mvcResult.getResponse().getContentAsString();\n assertEquals(content, \"Product is updated successsfully\");\n }\n @Test\n public void deleteProduct() throws Exception {\n String uri = \"/products/2\";\n MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.delete(uri)).andReturn();\n int status = mvcResult.getResponse().getStatus();\n assertEquals(200, status);\n String content = mvcResult.getResponse().getContentAsString();\n assertEquals(content, \"Product is deleted successsfully\");\n }\n}" }, { "code": null, "e": 11312, "s": 11185, "text": "You can create an executable JAR file, and run the Spring Boot application by using the Maven or Gradle commands given below −" }, { "code": null, "e": 11361, "s": 11312, "text": "For Maven, you can use the command given below −" }, { "code": null, "e": 11381, "s": 11361, "text": "mvn clean install \n" }, { "code": null, "e": 11434, "s": 11381, "text": "Now, you can see the test results in console window." }, { "code": null, "e": 11487, "s": 11434, "text": "For Gradle, you can use the command as shown below −" }, { "code": null, "e": 11507, "s": 11487, "text": "gradle clean build\n" }, { "code": null, "e": 11570, "s": 11507, "text": "You can see the rest results in console window as shown below." }, { "code": null, "e": 11604, "s": 11570, "text": "\n 102 Lectures \n 8 hours \n" }, { "code": null, "e": 11618, "s": 11604, "text": " Karthikeya T" }, { "code": null, "e": 11651, "s": 11618, "text": "\n 39 Lectures \n 5 hours \n" }, { "code": null, "e": 11666, "s": 11651, "text": " Chaand Sheikh" }, { "code": null, "e": 11701, "s": 11666, "text": "\n 73 Lectures \n 5.5 hours \n" }, { "code": null, "e": 11713, "s": 11701, "text": " Senol Atac" }, { "code": null, "e": 11748, "s": 11713, "text": "\n 62 Lectures \n 4.5 hours \n" }, { "code": null, "e": 11760, "s": 11748, "text": " Senol Atac" }, { "code": null, "e": 11795, "s": 11760, "text": "\n 67 Lectures \n 4.5 hours \n" }, { "code": null, "e": 11807, "s": 11795, "text": " Senol Atac" }, { "code": null, "e": 11840, "s": 11807, "text": "\n 69 Lectures \n 5 hours \n" }, { "code": null, "e": 11852, "s": 11840, "text": " Senol Atac" }, { "code": null, "e": 11859, "s": 11852, "text": " Print" }, { "code": null, "e": 11870, "s": 11859, "text": " Add Notes" } ]
Difference between Argument and Parameter in C/C++ with Examples - GeeksforGeeks
24 Jun, 2021 Argument An argument is referred to the values that are passed within a function when the function is called. These values are generally the source of the function that require the arguments during the process of execution. These values are assigned to the variables in the definition of the function that is called. The type of the values passed in the function is the same as that of the variables defined in the function definition. These are also called Actual arguments or Actual Parameters. Example: Suppose a sum() function is needed to be called with two numbers to add. These two numbers are referred to as the arguments and are passed to the sum() when it called from somewhere else. C C++ // C code to illustrate Arguments #include <stdio.h> // sum: Function definitionint sum(int a, int b){ // returning the addition return a + b;} // Driver codeint main(){ int num1 = 10, num2 = 20, res; // sum() is called with // num1 & num2 as ARGUMENTS. res = sum(num1, num2); // Displaying the result printf("The summation is %d", res); return 0;} // C++ code to illustrate Arguments#include <iostream>using namespace std; // sum: Function definitionint sum(int a, int b){ // returning the addition return a + b;} // Driver codeint main(){ int num1 = 10, num2 = 20, res; // sum() is called with // num1 & num2 as ARGUMENTS. res = sum(num1, num2); // Displaying the result cout << "The summation is " << res; return 0;} The summation is 30 Parameters The parameter is referred to as the variables that are defined during a function declaration or definition. These variables are used to receive the arguments that are passed during a function call. These parameters within the function prototype are used during the execution of the function for which it is defined. These are also called Formal arguments or Formal Parameters.Example: Suppose a Mult() function is needed to be defined to multiply two numbers. These two numbers are referred to as the parameters and are defined while defining the function Mult(). C C++ // C code to illustrate Parameters #include <stdio.h> // Mult: Function definition// a and b are the PARAMETERSint Mult(int a, int b){ // returning the multiplication return a * b;} // Driver codeint main(){ int num1 = 10, num2 = 20, res; // Mult() is called with // num1 & num2 as ARGUMENTS. res = Mult(num1, num2); // Displaying the result printf("The multiplication is %d", res); return 0;} // C++ code to illustrate Parameters #include <iostream>using namespace std; // Mult: Function definition// a and b are the parametersint Mult(int a, int b){ // returning the multiplication return a * b;} // Driver codeint main(){ int num1 = 10, num2 = 20, res; // Mult() is called with // num1 & num2 as ARGUMENTS. res = Mult(num1, num2); // Displaying the result cout << "The multiplication is " << res; return 0;} The multiplication is 200 Difference between Argument and Parameter int num = 20;Call(num) // num is argument int Call(int rnum){ printf("the num is %d", rnum);} // rnum is parameter sagar0719kumar C Language C++ Difference Between CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments TCP Server-Client implementation in C 'this' pointer in C++ Exception Handling in C++ Multithreading in C UDP Server-Client implementation in C Vector in C++ STL Initialize a vector in C++ (6 different ways) Inheritance in C++ Map in C++ Standard Template Library (STL) Socket Programming in C/C++
[ { "code": null, "e": 24152, "s": 24124, "text": "\n24 Jun, 2021" }, { "code": null, "e": 24161, "s": 24152, "text": "Argument" }, { "code": null, "e": 24649, "s": 24161, "text": "An argument is referred to the values that are passed within a function when the function is called. These values are generally the source of the function that require the arguments during the process of execution. These values are assigned to the variables in the definition of the function that is called. The type of the values passed in the function is the same as that of the variables defined in the function definition. These are also called Actual arguments or Actual Parameters." }, { "code": null, "e": 24846, "s": 24649, "text": "Example: Suppose a sum() function is needed to be called with two numbers to add. These two numbers are referred to as the arguments and are passed to the sum() when it called from somewhere else." }, { "code": null, "e": 24848, "s": 24846, "text": "C" }, { "code": null, "e": 24852, "s": 24848, "text": "C++" }, { "code": "// C code to illustrate Arguments #include <stdio.h> // sum: Function definitionint sum(int a, int b){ // returning the addition return a + b;} // Driver codeint main(){ int num1 = 10, num2 = 20, res; // sum() is called with // num1 & num2 as ARGUMENTS. res = sum(num1, num2); // Displaying the result printf(\"The summation is %d\", res); return 0;}", "e": 25230, "s": 24852, "text": null }, { "code": "// C++ code to illustrate Arguments#include <iostream>using namespace std; // sum: Function definitionint sum(int a, int b){ // returning the addition return a + b;} // Driver codeint main(){ int num1 = 10, num2 = 20, res; // sum() is called with // num1 & num2 as ARGUMENTS. res = sum(num1, num2); // Displaying the result cout << \"The summation is \" << res; return 0;}", "e": 25630, "s": 25230, "text": null }, { "code": null, "e": 25651, "s": 25630, "text": "The summation is 30\n" }, { "code": null, "e": 25662, "s": 25651, "text": "Parameters" }, { "code": null, "e": 26226, "s": 25662, "text": "The parameter is referred to as the variables that are defined during a function declaration or definition. These variables are used to receive the arguments that are passed during a function call. These parameters within the function prototype are used during the execution of the function for which it is defined. These are also called Formal arguments or Formal Parameters.Example: Suppose a Mult() function is needed to be defined to multiply two numbers. These two numbers are referred to as the parameters and are defined while defining the function Mult()." }, { "code": null, "e": 26228, "s": 26226, "text": "C" }, { "code": null, "e": 26232, "s": 26228, "text": "C++" }, { "code": "// C code to illustrate Parameters #include <stdio.h> // Mult: Function definition// a and b are the PARAMETERSint Mult(int a, int b){ // returning the multiplication return a * b;} // Driver codeint main(){ int num1 = 10, num2 = 20, res; // Mult() is called with // num1 & num2 as ARGUMENTS. res = Mult(num1, num2); // Displaying the result printf(\"The multiplication is %d\", res); return 0;}", "e": 26655, "s": 26232, "text": null }, { "code": "// C++ code to illustrate Parameters #include <iostream>using namespace std; // Mult: Function definition// a and b are the parametersint Mult(int a, int b){ // returning the multiplication return a * b;} // Driver codeint main(){ int num1 = 10, num2 = 20, res; // Mult() is called with // num1 & num2 as ARGUMENTS. res = Mult(num1, num2); // Displaying the result cout << \"The multiplication is \" << res; return 0;}", "e": 27101, "s": 26655, "text": null }, { "code": null, "e": 27128, "s": 27101, "text": "The multiplication is 200\n" }, { "code": null, "e": 27170, "s": 27128, "text": "Difference between Argument and Parameter" }, { "code": "int num = 20;Call(num) // num is argument", "e": 27216, "s": 27170, "text": null }, { "code": "int Call(int rnum){ printf(\"the num is %d\", rnum);} // rnum is parameter", "e": 27292, "s": 27216, "text": null }, { "code": null, "e": 27307, "s": 27292, "text": "sagar0719kumar" }, { "code": null, "e": 27318, "s": 27307, "text": "C Language" }, { "code": null, "e": 27322, "s": 27318, "text": "C++" }, { "code": null, "e": 27341, "s": 27322, "text": "Difference Between" }, { "code": null, "e": 27345, "s": 27341, "text": "CPP" }, { "code": null, "e": 27443, "s": 27345, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27452, "s": 27443, "text": "Comments" }, { "code": null, "e": 27465, "s": 27452, "text": "Old Comments" }, { "code": null, "e": 27503, "s": 27465, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 27525, "s": 27503, "text": "'this' pointer in C++" }, { "code": null, "e": 27551, "s": 27525, "text": "Exception Handling in C++" }, { "code": null, "e": 27571, "s": 27551, "text": "Multithreading in C" }, { "code": null, "e": 27609, "s": 27571, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 27627, "s": 27609, "text": "Vector in C++ STL" }, { "code": null, "e": 27673, "s": 27627, "text": "Initialize a vector in C++ (6 different ways)" }, { "code": null, "e": 27692, "s": 27673, "text": "Inheritance in C++" }, { "code": null, "e": 27735, "s": 27692, "text": "Map in C++ Standard Template Library (STL)" } ]
PHP | DOMDocument loadHTML() Function - GeeksforGeeks
30 Aug, 2019 The DOMDocument::loadHTML() function is an inbuilt function in PHP which is used to load HTML file from a string. Syntax: bool DOMDocument::loadHTML( string $source, int $options = 0 ) Parameters: This function accepts two parameters as mentioned above and described below: $source: This parameter holds the HTML string. $options: This parameter is used to specify the additional Libxml parameters in PHP 5.4.0 and Libxml 2.6.0. Return Value: This function returns TRUE on success or FALSE on failure. This function returns a DOMDocument if it is called statically or FALSE on failure. Errors/Exceptions: If empty string is passed as parameter then it generates an warning message. This function can also be called statically but it will issue an E_STRICT error. Below program illustrates the DOMDocument::loadHTML() function in PHP: Program 1: <?php // Create a new DOMDocument$doc = new DOMDocument(); // Load the HTML file$doc->loadHTML("<html><head> <title> DOMDocument::loadHTML() function </title></head><body> <h1>GeeksforGeeks</h1> <h2>DOMDocument::loadHTML() function</h2></body> </html>"); // Creates an HTML document and display itecho $doc->saveHTML(); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"> <html> <head> <title> DOMDocument::loadHTML() function </title> </head> <body> <h1>GeeksforGeeks</h1> <h2>DOMDocument::loadHTML() function</h2> </body> </html> Program 2: <?php // Create a new DOMDocument$doc = new DOMDocument(); // Create an element$comm1 = $doc->createComment('Starting of HTML document file'); // Append element to the document$doc->appendChild($comm1); // Creates an HTML document and display itecho $doc->saveHTML(); // Load the HTML element to the document$doc->loadHTML("<html><head> <title>PHP function</title></head><body> <h1>Welcome to GeeksforGeeks</h1> <h2>PHP function</h2> <div>A computer science portal</div></body> </html>"); // Create an element$comm2 = $doc->createComment('Ending of HTML document file'); // Append element to the document$doc->appendChild($comm2); // Creates an HTML document and display itecho $doc->saveHTML(); ?> <!--Starting of HTML document file--> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"> <html> <head> <title>PHP function</title> </head> <body> <h1>Welcome to GeeksforGeeks</h1> <h2>PHP function</h2> <div>A computer science portal</div> </body> </html> <!--Ending of HTML document file--> Reference: https://www.php.net/manual/en/domdocument.loadhtml.php PHP-DOM PHP-function PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? How to check whether an array is empty using PHP? PHP | Converting string to Date and DateTime Comparing two dates in PHP Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 26589, "s": 26561, "text": "\n30 Aug, 2019" }, { "code": null, "e": 26703, "s": 26589, "text": "The DOMDocument::loadHTML() function is an inbuilt function in PHP which is used to load HTML file from a string." }, { "code": null, "e": 26711, "s": 26703, "text": "Syntax:" }, { "code": null, "e": 26774, "s": 26711, "text": "bool DOMDocument::loadHTML( string $source, int $options = 0 )" }, { "code": null, "e": 26863, "s": 26774, "text": "Parameters: This function accepts two parameters as mentioned above and described below:" }, { "code": null, "e": 26910, "s": 26863, "text": "$source: This parameter holds the HTML string." }, { "code": null, "e": 27018, "s": 26910, "text": "$options: This parameter is used to specify the additional Libxml parameters in PHP 5.4.0 and Libxml 2.6.0." }, { "code": null, "e": 27175, "s": 27018, "text": "Return Value: This function returns TRUE on success or FALSE on failure. This function returns a DOMDocument if it is called statically or FALSE on failure." }, { "code": null, "e": 27352, "s": 27175, "text": "Errors/Exceptions: If empty string is passed as parameter then it generates an warning message. This function can also be called statically but it will issue an E_STRICT error." }, { "code": null, "e": 27423, "s": 27352, "text": "Below program illustrates the DOMDocument::loadHTML() function in PHP:" }, { "code": null, "e": 27434, "s": 27423, "text": "Program 1:" }, { "code": "<?php // Create a new DOMDocument$doc = new DOMDocument(); // Load the HTML file$doc->loadHTML(\"<html><head> <title> DOMDocument::loadHTML() function </title></head><body> <h1>GeeksforGeeks</h1> <h2>DOMDocument::loadHTML() function</h2></body> </html>\"); // Creates an HTML document and display itecho $doc->saveHTML(); ?>", "e": 27783, "s": 27434, "text": null }, { "code": null, "e": 28083, "s": 27783, "text": "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\"\n \"http://www.w3.org/TR/REC-html40/loose.dtd\">\n<html>\n<head>\n <title>\n DOMDocument::loadHTML() function\n </title>\n</head>\n<body>\n <h1>GeeksforGeeks</h1>\n <h2>DOMDocument::loadHTML() function</h2>\n</body>\n</html>\n" }, { "code": null, "e": 28094, "s": 28083, "text": "Program 2:" }, { "code": "<?php // Create a new DOMDocument$doc = new DOMDocument(); // Create an element$comm1 = $doc->createComment('Starting of HTML document file'); // Append element to the document$doc->appendChild($comm1); // Creates an HTML document and display itecho $doc->saveHTML(); // Load the HTML element to the document$doc->loadHTML(\"<html><head> <title>PHP function</title></head><body> <h1>Welcome to GeeksforGeeks</h1> <h2>PHP function</h2> <div>A computer science portal</div></body> </html>\"); // Create an element$comm2 = $doc->createComment('Ending of HTML document file'); // Append element to the document$doc->appendChild($comm2); // Creates an HTML document and display itecho $doc->saveHTML(); ?>", "e": 28818, "s": 28094, "text": null }, { "code": null, "e": 29191, "s": 28818, "text": "<!--Starting of HTML document file-->\n<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" \n \"http://www.w3.org/TR/REC-html40/loose.dtd\">\n<html>\n<head>\n <title>PHP function</title>\n</head>\n<body>\n <h1>Welcome to GeeksforGeeks</h1>\n <h2>PHP function</h2>\n <div>A computer science portal</div>\n</body>\n</html>\n<!--Ending of HTML document file-->\n" }, { "code": null, "e": 29257, "s": 29191, "text": "Reference: https://www.php.net/manual/en/domdocument.loadhtml.php" }, { "code": null, "e": 29265, "s": 29257, "text": "PHP-DOM" }, { "code": null, "e": 29278, "s": 29265, "text": "PHP-function" }, { "code": null, "e": 29282, "s": 29278, "text": "PHP" }, { "code": null, "e": 29299, "s": 29282, "text": "Web Technologies" }, { "code": null, "e": 29303, "s": 29299, "text": "PHP" }, { "code": null, "e": 29401, "s": 29303, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29451, "s": 29401, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 29491, "s": 29451, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 29541, "s": 29491, "text": "How to check whether an array is empty using PHP?" }, { "code": null, "e": 29586, "s": 29541, "text": "PHP | Converting string to Date and DateTime" }, { "code": null, "e": 29613, "s": 29586, "text": "Comparing two dates in PHP" }, { "code": null, "e": 29653, "s": 29613, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29686, "s": 29653, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29731, "s": 29686, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29774, "s": 29731, "text": "How to fetch data from an API in ReactJS ?" } ]
Exploring AI at the Edge!. Image Recognition, Object and Pose... | by Marcelo Rovai | Towards Data Science
What is Edge (or Fog) Computing? Gartner defines edge computing as: “a part of a distributed computing topology in which information processing is located close to the edge — where things and people produce or consume that information.” In other words, edge computing brings computation (and some data storage) closer to the devices where it’s data are being generated or consumed (especially in real-time), rather than relying on a cloud-based central system far away. With this approach, data does not suffer latency issues, reducing the amount of cost in transmission and processing. In a way, it is a kind of “return to the recent past,” where all the computational work was done locally on a desktop and not in the cloud. Edge computing was developed due to the exponential growth of IoT devices connected to the internet for either receiving information from the cloud or delivering data back to the cloud. And many Internet of Things (IoT) devices generate enormous amounts of data during their operations. Edge computing provides new possibilities in IoT applications, particularly for those relying on machine learning (ML) for tasks such as object and pose detection, image (and face) recognition, language processing, and obstacle avoidance. Image data is an excellent addition to IoT, but also a significant resource consumer (as power, memory, and processing). Image processing “at the Edge”, running classics AI/ML models, is a great leap! Machine Learning can be divided into two separated process: Training and Inference, as explained in Gartner Blog: Training: Training refers to the process of creating a machine learning algorithm. Training involves using a deep-learning framework (e.g., TensorFlow) and training dataset (see the left-hand side of the above figure). IoT data provides a source of training data that data scientists and engineers can use to train machine learning models for various cases, from failure detection to consumer intelligence. Inference: Inference refers to the process of using a trained machine-learning algorithm to make a prediction. IoT data can be used as the input to a trained machine learning model, enabling predictions that can guide decision logic on the device, at the edge gateway, or elsewhere in the IoT system (see the right-hand side of the above figure). TensorFlow Lite is an open-source deep learning framework that enables on-device machine learning inference with low latency and small binary size. It is designed to make it easy to perform machine learning on devices, “at the edge” of the network, instead of sending data back and forth from a server. Performing machine learning on-device can help to improve: Latency: there’s no round-trip to a server Privacy: no data needs to leave the device Connectivity: an Internet connection isn’t required Power consumption: network connections are power-hungry TensorFlow Lite (TFLite) consists of two main components: The TFLite converter, which converts TensorFlow models into an efficient form for use by the interpreter, and can introduce optimizations to improve binary size and performance. The TFLite interpreter runs with specially optimized models on many different hardware types, including mobile phones, embedded Linux devices, and microcontrollers. In summary, a trained and saved TensorFlow model (like model.h5) can be converted using TFLite Converter in a TFLite FlatBuffer (like model.tflite) that will be used by TF Lite Interpreter inside the Edge device (as a Raspberry Pi), to perform inference on a new data. For example, I trained from scratch a simple CNN Image Classification model in my Mac (the “Server” on the above figure). The final model had 225,610 parameters to be trained, using as input the CIFAR10 dataset: 60,000 images (shape: 32, 32, 3). The trained model (cifar10_model.h5) had a size of 2.7Mb. Using the TFLite Converter, the model used on Raspberry Pi (model_cifar10.tflite) became with 905Kb (around 1/3 of original size). Making inference with both models (.h5 at Mac and .tflite at RPi) leaves the same results. Both notebooks can be found at GitHub. It is also possible to train models from scratch at Raspberry Pi, and for that, the full TensorFlow package is needed. But once what we will do is only the inference part, we will install just the TensorFlow Lite interpreter. The interpreter-only package is a fraction the size of the full TensorFlow package and includes the bare minimum code required to run inferences with TensorFlow Lite. It includes only the tf.lite.InterpreterPython class, used to execute .tflite models. Let’s open the terminal at Raspberry Pi and install the Python wheel needed for your specific system configuration. The options can be found on this link: Python Quickstart. For example, in my case, I am running Linux ARM32 (Raspbian Buster — Python 3.7), so the command line is: $ sudo pip3 install https://dl.google.com/coral/python/tflite_runtime-2.1.0.post1-cp37-cp37m-linux_armv7l.whl If you want to double-check what OS version you have in your Raspberry Pi, run the command: $ uname - As shown on image below, if you get ...arm7l..., the operating system is a 32bits Linux. Installing the Python wheel is the only requirement for having TFLite interpreter working in a Raspberry Pi. It is possible to double-check if the installation is OK, calling the TFLite interpreter at the terminal, as below. If no errors appear, we are good. One of the more classic tasks of IA applied to Computer Vision (CV) is Image Classification. Starting on 2012, IA and Deep Learning (DL) changed forever, when a convolutional neural network (CNN) called AlexNet (in honor of its leading developer, Alex Krizhevsky), achieved a top-5 error of 15.3% in the ImageNet 2012 Challenge. According to The Economist, “Suddenly people started to pay attention (in DL), not just within the AI community but across the technology industry as a whole This project, almost eight years after Alex Krizhevsk, a more modern architecture (MobileNet), was also pre-trained over millions of images, using the same dataset ImageNet, resulting in 1,000 different classes. This pre-trained and quantized model was so, converted in a .tflite and used here. First, let’s on Raspberry Pi move to a working directory (for example, Image_Recognition). Next, it is essential to create two subdirectories, one for models and another for images: $ mkdir images$ mkdir models Once inside the model’s directory, let’s download the pre-trained model (in this link, it is possible to download several different models). We will use a quantized Mobilenet V1 model, pre-trained with images of 224x224 pixels. The zip file that can be downloaded from TensorFlow Lite Image classification, using wget: $ cd models$ wget https://storage.googleapis.com/download.tensorflow.org/models/tflite/mobilenet_v1_1.0_224_quant_and_labels.zip Next, unzip the file: $ unzip mobilenet_v1_1.0_224_quant_and_labels Two files are downloaded: mobilenet_v1_1.0_224_quant.tflite: TensorFlow-Lite transformed model labels_mobilenet_quant_v1_224.txt: The ImageNet dataset 1,000 Classes Labels Now, get some images (for example, .png, .jpg) and save them on the created images subdirectory. On GitHub, it is possible to find the images used on this tutorial. OpenCV (Open Source Computer Vision Library) is an open-source computer vision and machine learning software library. It is beneficial as a support when working with images. If very simple to install it on a Mac or PC is a little bit “trick” to do it on a Raspberry Pi, but I recommend to use it. Please follow this great tutorial from Q-Engineering to install OpenCV on your Raspberry Pi: Install OpenCV 4.4.0 on Raspberry Pi 4. Although written for the Raspberry Pi 4, the guide can also be used without any change for the Raspberry 3 or 2. Next, Install Jupyter Notebook. It will be our development platform. $ sudo pip3 install jupyter$ jupyter notebook Also, during OpenCV installation, NumPy should have been installed, if not do it now, same with MatPlotLib. $ sudo pip3 install numpy$ sudo apt-get install python3-matplotlib And it is done! We have everything in place to start our AI journey to the Edge! Create a fresh Jupyter Notebook and follow bellow steps, or download the complete notebook from GitHub. Import Libraries: import numpy as npimport matplotlib.pyplot as pltimport cv2import tflite_runtime.interpreter as tflite Load TFLite model and allocate tensors: interpreter = tflite.Interpreter(model_path=’./models/mobilenet_v1_1.0_224_quant.tflite’)interpreter.allocate_tensors() Get input and output tensors: input_details = interpreter.get_input_details()output_details = interpreter.get_output_details() input details will give you the info needed about how the model should be feed with an image: The shape of (1, 224x224x3), informs that an image with dimensions: (224x224x3) should be input one by one (Batch Dimension: 1). The dtype uint8, tells that the values are 8bits integers The output details show that the inference will result in an array of 1,001 integer values (8 bits). Those values are the result of the image classification, where each value is the probability of that specific label be related to the image. For example, suppose that we want to classify an image wich shape is (1220, 1200, 3). First, we will need to reshape it to (224, 224, 3) and add a batch dimension of 1, as defined on input details: (1, 224, 224, 3). The inference result will be an array with 1001 size, as shown below: The steps to code those operations are: Input image and convert it to RGB (OpenCV reads an image as BGR): Input image and convert it to RGB (OpenCV reads an image as BGR): image_path = './images/cat_2.jpg'image = cv2.imread(image_path)img = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) 2. Pre-process the image, reshaping and adding batch dimension: img = cv2.resize(img, (224, 224))input_data = np.expand_dims(img, axis=0) 3. Point the data to be used for testing and run the interpreter: interpreter.set_tensor(input_details[0]['index'], input_data)interpreter.invoke() 4. Obtain results and map them to the classes: predictions = interpreter.get_tensor(output_details[0][‘index’])[0] The output values (predictions) varies from 0 to 255 (max value of an 8bit integer). To obtain a prediction that will range from 0 to 1, the output value should be divided by 255. The array’s index, related to the highest value, is the most probable classification of such an image. Having the index, we must find to what class it appoint (such as car, cat, or dog). The text file downloaded with the model has a label associated with each index that goes from 0 to 1,000. Let’s first create a function to load the .txt file as a dictionary: def load_labels(path): with open(path, 'r') as f: return {i: line.strip() for i, line in enumerate(f.readlines())} And create a dictionary named labels and inspecting some of them: labels = load_labels('./models/labels_mobilenet_quant_v1_224.txt') Returning to our example, let’s get the top 3 results (highest probabilities): top_k_indices = 3top_k_indices = np.argsort(predictions)[::-1][:top_k_results] We can see that the 3 top indices are related to cats. The prediction content is the probability associated with each one of the labels. As explained before, dividing by 255., we can get a value from 0 to 1. Let’s create a loop to go over the top results, printing label and probabilities: for i in range(top_k_results): print("\t{:20}: {}%".format( labels[top_k_indices[i]], int((predictions[top_k_indices[i]] / 255.0) * 100))) Let’s create a function, to perform inference on different images smoothly: def image_classification(image_path, labels, top_k_results=3): image = cv2.imread(image_path) img = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) plt.imshow(img)img = cv2.resize(img, (w, h)) input_data = np.expand_dims(img, axis=0)interpreter.set_tensor(input_details[0]['index'], input_data) interpreter.invoke() predictions = interpreter.get_tensor(output_details[0]['index'])[0]top_k_indices = np.argsort(predictions)[::-1][:top_k_results]print("\n\t[PREDICTION] [Prob]\n") for i in range(top_k_results): print("\t{:20}: {}%".format( labels[top_k_indices[i]], int((predictions[top_k_indices[i]] / 255.0) * 100))) The figure below shows some tests using the function: The overall performance is astonishing! From the instant that you enter with the image path in the memory card, until the time that that result is printed out, all process took less than half a second, with high precision! The function can be easily applied to frames on videos or live camera. The notebook for that and the complete code discussed in this section can be downloaded from GitHub. With Image Classification, we can detect what the dominant subject of such an image is. But what happens if several objects are dominant and of interest on the same image? To solve it, we can use an Object Detection model! Given an image or a video stream, an object detection model can identify which of a known set of objects might be present and provide information about their positions within the image. For this task, we will download a Mobilenet V1 model pre-trained using the COCO (Common Objects in Context) dataset. This dataset has more than 200,000 labeled images, in 91 categories. On Raspberry terminal run the commands: $ cd ./models $ curl -O http://storage.googleapis.com/download.tensorflow.org/models/tflite/coco_ssd_mobilenet_v1_1.0_quant_2018_06_29.zip$ unzip coco_ssd_mobilenet_v1_1.0_quant_2018_06_29.zip$ curl -O https://dl.google.com/coral/canned_models/coco_labels.txt$ rm coco_ssd_mobilenet_v1_1.0_quant_2018_06_29.zip$ rm labelmap.txt On models subdirectory, we should end with 2 new files: coco_labels.txt detect.tflite The steps to perform inference on a new image, are very similar to those done with Image Classification, except that: input: image must have a shape of 300x300 pixels output: include not only label and probability (“score”), but also the relative window position (“ Bounding Box”) about where the object is located on the image. Now, we must load the labels and model, allocating tensors. labels = load_labels('./models/coco_labels.txt')interpreter = Interpreter('./models/detect.tflite')interpreter.allocate_tensors() The input pre-process is the same as we did before, but the output should be worked to get a more readable output. The functions below will help with that: def set_input_tensor(interpreter, image): """Sets the input tensor.""" tensor_index = interpreter.get_input_details()[0]['index'] input_tensor = interpreter.tensor(tensor_index)()[0] input_tensor[:, :] = imagedef get_output_tensor(interpreter, index): """Returns the output tensor at the given index.""" output_details = interpreter.get_output_details()[index] tensor = np.squeeze(interpreter.get_tensor(output_details['index'])) return tensor With the help of the above functions, detect_objects() will return the inference results: object label id score the bounding box, that will show where the object is located. We have included a ‘threshold’ to avoid objects with a low probability of being correct. Usually, we should consider a score above 50%. def detect_objects(interpreter, image, threshold): set_input_tensor(interpreter, image) interpreter.invoke() # Get all output details boxes = get_output_tensor(interpreter, 0) classes = get_output_tensor(interpreter, 1) scores = get_output_tensor(interpreter, 2) count = int(get_output_tensor(interpreter, 3)) results = [] for i in range(count): if scores[i] >= threshold: result = { 'bounding_box': boxes[i], 'class_id': classes[i], 'score': scores[i] } results.append(result) return results If we apply the above function to a reshaped image (same as used on classification example), we should get: Great! In less than 200ms with 77% probability, an object with id 16 was detected on an area delimited by a ‘bounding box’: (0.028011084, 0.020121813, 0.9886069, 0.802299). Those four numbers are respectively related to ymin, xmin, ymax and xmax. Take into consideration that y goes from the top (ymin) to bottom (ymax) and x goes from left (xmin) to the right (xmax) as shown in figure below: Having the bounding box four values, we have, in fact, the coordinates of the top/left corner and the bottom/right one. With both edges and knowing the shape of the picture, it is possible to draw the rectangle around the object. Next, we should find what class_id equal to 16 means. Opening the file coco_labels.txt, as a dictionary, each of its elements has an index associated, and inspecting index 16, we get as expected, ‘cat.’ The probability is the value returning from the score. Let’s create a general function to detect multiple objects on a single picture. The first function, starting from an image path, will execute the inference, returning the resized image and the results (multiples ids, each one with its scores and bounding boxes: def detectObjImg_2(image_path, threshold = 0.51):img = cv2.imread(image_path) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) image = cv2.resize(img, (width, height), fx=0.5, fy=0.5, interpolation=cv2.INTER_AREA) results = detect_objects(interpreter, image, threshold)return img, results Having the reshaped image, and inference results, the below function can be used to draw a rectangle around the objects, specifying for each one, its label and probability: def detect_mult_object_picture(img, results): HEIGHT, WIDTH, _ = img.shape aspect = WIDTH / HEIGHT WIDTH = 640 HEIGHT = int(640 / aspect) dim = (WIDTH, HEIGHT) img = cv2.resize(img, dim, interpolation=cv2.INTER_AREA) for i in range(len(results)): id = int(results[i]['class_id']) prob = int(round(results[i]['score'], 2) * 100) ymin, xmin, ymax, xmax = results[i]['bounding_box'] xmin = int(xmin * WIDTH) xmax = int(xmax * WIDTH) ymin = int(ymin * HEIGHT) ymax = int(ymax * HEIGHT) text = "{}: {}%".format(labels[id], prob) if ymin > 10: ytxt = ymin - 10 else: ytxt = ymin + 15 img = cv2.rectangle(img, (xmin, ymin), (xmax, ymax), COLORS[id], thickness=2) img = cv2.putText(img, text, (xmin + 3, ytxt), FONT, 0.5, COLORS[id], 2) return img Below some results: The complete code can be found at GitHub. If you have a PiCam connected to Raspberry Pi, it is possible to capture a video and perform object recognition, frame by frame, using the same functions defined before. Please follow this tutorial if you do not have a working camera in your Pi: Getting started with the Camera Module. First, it is essential to define the size of the frame to be captured by the camera. We will use 640x480. WIDTH = 640HEIGHT = 480 Next, you must iniciate the camera: cap = cv2.VideoCapture(0)cap.set(3, WIDTH)cap.set(4, HEIGHT) And run the below code in a loop. Until the key ‘q’ is pressed, the camera will capture the video, frame by frame, drawing the bounding box with its respective labels and probabilities. while True: timer = cv2.getTickCount() success, img = cap.read() img = cv2.flip(img, 0) img = cv2.flip(img, 1) fps = cv2.getTickFrequency() / (cv2.getTickCount() - timer) cv2.putText(img, "FPS: " + str(int(fps)), (10, 470), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2) image = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) image = cv2.resize(image, (width, height), fx=0.5, fy=0.5, interpolation=cv2.INTER_AREA) start_time = time.time() results = detect_objects(interpreter, image, 0.55) elapsed_ms = (time.time() - start_time) * 1000 img = detect_mult_object_picture(img, results) cv2.imshow("Image Recognition ==> Press [q] to Exit", img)if cv2.waitKey(1) & 0xFF == ord('q'): breakcap.release()cv2.destroyAllWindows() Below is possible to see the video running in real-time on the Raspberry Pi screen. Note that the video runs around 60 FPS (frames per second), which is pretty good!. Here one screen-shot of the above video: The complete code is available on GitHub. One of the more exciting and critical areas of AI is to estimate a person’s real-time pose, enabling machines to understand what people are doing in images and videos. Pose estimation was deeply explored in my article Realtime Multiple Person 2D Pose Estimation using TensorFlow2.x, but here at the Edge, with a Raspberry Pi and with the help of TensorFlow Lite, it is possible to easily replicate almost the same that was done on a Mac. The model that we will use in this project is the PoseNet. We will do inference the same way done for Image Classification and Object Detection, where an image is fed through a pre-trained model. PoseNet comes with a few different versions of the model, corresponding to variances of MobileNet v1 architecture and ResNet50 architecture. In this project, the version pre-trained is the MobileNet V1, which is smaller, faster, but less accurate than ResNet. Also, there are separate models for single and multiple person pose detection. We will explore the model trained for a single person. In this site is possible to explore in real time and using a live camera, several PoseNet models and configurations. The libraries to execute Pose Estimation on a Raspberry Pi are the same used before. NumPy, MatPlotLib, OpenCV and TensorFlow Lite Interpreter. The pre-trained model is the posenet_mobilenet_v1_100_257x257_multi_kpt_stripped.tflite, which can be downloaded from the above link or the TensorFlow Lite — Pose Estimation Overview website. The model should be saved in the models subdirectory. Start loading TFLite model and allocating tensors: interpreter = tflite.Interpreter(model_path='./models/posenet_mobilenet_v1_100_257x257_multi_kpt_stripped.tflite')interpreter.allocate_tensors() Get input and output tensors: input_details = interpreter.get_input_details()output_details = interpreter.get_output_details() Same as we did before, looking into the input_details, it is possible to see that the image to be used to pose estimation should be (1, 257, 257, 3), which means that images must be reshaped to 257x257 pixels. Let’s take as input a simple human figure, that will help us to analyze it: The first step is to pre-process the image. This particular model was not quantized, which means that the dtype is float32. This information is essential to pre-process the input image, as shown with the below code image = cv2.resize(image, size) input_data = np.expand_dims(image, axis=0)input_data = input_data.astype(np.float32)input_data = (np.float32(input_data) - 127.5) / 127.5 Having the image pre-processed, now it is time to perform the inference, feeding the tensor with the image and invoking the interpreter: interpreter.set_tensor(input_details[0]['index'], input_data)interpreter.invoke() An article that helps a lot to understand how to work with PoseNet is the Ivan Kunyakin tutorial’s Pose estimation and matching with TensorFlow lite. There Ivan comments that on the output vector, what matters to find the key points, are: Heatmaps 3D tensor of size (9,9,17), that corresponds to the probability of appearance of each one of the 17 keypoints (body joints) in the particular part of the image (9,9). It is used to locate the approximate position of the joint. Offset Vectors: 3D tensor of size (9,9,34) that is called offset vectors. It is used for more exact calculation of the keypoint’s position. The First 17 of the third dimension correspond to the x coordinates and the second 17 of them to the y coordinates. output_details = interpreter.get_output_details()[0]heatmaps = np.squeeze(interpreter.get_tensor(output_details['index']))output_details = interpreter.get_output_details()[1]offsets = np.squeeze(interpreter.get_tensor(output_details['index'])) Let’s create a function that will return an array with all 17 keypoints (or person's joints) based on heatmaps and offsets. def get_keypoints(heatmaps, offsets): joint_num = heatmaps.shape[-1] pose_kps = np.zeros((joint_num, 2), np.uint32) max_prob = np.zeros((joint_num, 1)) for i in range(joint_num): joint_heatmap = heatmaps[:,:,i] max_val_pos = np.squeeze( np.argwhere(joint_heatmap == np.max(joint_heatmap))) remap_pos = np.array(max_val_pos / 8 * 257, dtype=np.int32) pose_kps[i, 0] = int(remap_pos[0] + offsets[max_val_pos[0], max_val_pos[1], i]) pose_kps[i, 1] = int(remap_pos[1] + offsets[max_val_pos[0], max_val_pos[1], i + joint_num]) max_prob[i] = np.amax(joint_heatmap) return pose_kps, max_prob Using the above function with the heatmaps and offset vectors that were extracted from the output tensor, resultant of the image inference, we get: The resultant array shows all 17 coordinates (y, x) regarding where the joints are located on an image of 257 x 257 pixels. Using the code below. It is possible to plot each one of the joints over the resized image. For reference, the array index is annotated, so it is easy to identify each joint: y,x = zip(*keypts_array)plt.figure(figsize=(10,10))plt.axis([0, image.shape[1], 0, image.shape[0]]) plt.scatter(x,y, s=300, color='orange', alpha=0.6)img = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)plt.imshow(img)ax=plt.gca() ax.set_ylim(ax.get_ylim()[::-1]) ax.xaxis.tick_top() plt.grid();for i, txt in enumerate(keypts_array): ax.annotate(i, (keypts_array[i][1]-3, keypts_array[i][0]+1)) As a result, we get the picure: Great, now it is time to create a general function to draw “the bones”, which is the joints’ connection. The bones will be drawn as lines, which are the connections among keypoints 5 to 16, as shown in the above figure. Independent circles will be used for keypoints 0 to 4, related to head: def join_point(img, kps, color='white', bone_size=1): if color == 'blue' : color=(255, 0, 0) elif color == 'green': color=(0, 255, 0) elif color == 'red': color=(0, 0, 255) elif color == 'white': color=(255, 255, 255) else: color=(0, 0, 0) body_parts = [(5, 6), (5, 7), (6, 8), (7, 9), (8, 10), (11, 12), (5, 11), (6, 12), (11, 13), (12, 14), (13, 15), (14, 16)] for part in body_parts: cv2.line(img, (kps[part[0]][1], kps[part[0]][0]), (kps[part[1]][1], kps[part[1]][0]), color=color, lineType=cv2.LINE_AA, thickness=bone_size) for i in range(0,len(kps)): cv2.circle(img,(kps[i,1],kps[i,0]),2,(255,0,0),-1) Calling the function, we have the estimated pose of the body in the image: join_point(img, keypts_array, bone_size=2)plt.figure(figsize=(10,10))plt.imshow(img); And last but not least, let’s create a general function to estimate posture having an image path as a start: def plot_pose(img, keypts_array, joint_color='red', bone_color='blue', bone_size=1): join_point(img, keypts_array, bone_color, bone_size) y,x = zip(*keypts_array) plt.figure(figsize=(10,10)) plt.axis([0, img.shape[1], 0, img.shape[0]]) plt.scatter(x,y, s=100, color=joint_color) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) plt.imshow(img) ax=plt.gca() ax.set_ylim(ax.get_ylim()[::-1]) ax.xaxis.tick_top() plt.grid(); return imgdef get_plot_pose(image_path, size, joint_color='red', bone_color='blue', bone_size=1): image_original = cv2.imread(image_path) image = cv2.resize(image_original, size) input_data = np.expand_dims(image, axis=0) input_data = input_data.astype(np.float32) input_data = (np.float32(input_data) - 127.5) / 127.5 interpreter.set_tensor(input_details[0]['index'], input_data) interpreter.invoke() output_details = interpreter.get_output_details()[0] heatmaps = np.squeeze(interpreter.get_tensor(output_details['index'])) output_details = interpreter.get_output_details()[1] offsets = np.squeeze(interpreter.get_tensor(output_details['index'])) keypts_array, max_prob = get_keypoints(heatmaps,offsets) orig_kps = get_original_pose_keypoints(image_original, keypts_array, size) img = plot_pose(image_original, orig_kps, joint_color, bone_color, bone_size) return orig_kps, max_prob, img At this point with only one line of code, it is possible to detect pose on images: keypts_array, max_prob, img = get_plot_pose(image_path, size, bone_size=3) All code developed on this section is available on GitHub. Another easy step is to apply the function to frames from videos and live camera. I will leave it for you! ;-) TensorFlow Lite is a great framework to implement Artificial Intelligence (more precisely, ML) at the Edge. Here we explored ML models working on a Raspberry Pi, but TFLite is now more and more used at the "edge of the edge", on very small microcontrollers, in what has been called TinyML. As always, I hope this article can inspire others to find their way in the fantastic world of AI! All the codes used in this article are available for download on project GitHub: TFLite_IA_at_the_Edge. Regards from the South of the World! See you in my next article!
[ { "code": null, "e": 205, "s": 172, "text": "What is Edge (or Fog) Computing?" }, { "code": null, "e": 409, "s": 205, "text": "Gartner defines edge computing as: “a part of a distributed computing topology in which information processing is located close to the edge — where things and people produce or consume that information.”" }, { "code": null, "e": 899, "s": 409, "text": "In other words, edge computing brings computation (and some data storage) closer to the devices where it’s data are being generated or consumed (especially in real-time), rather than relying on a cloud-based central system far away. With this approach, data does not suffer latency issues, reducing the amount of cost in transmission and processing. In a way, it is a kind of “return to the recent past,” where all the computational work was done locally on a desktop and not in the cloud." }, { "code": null, "e": 1186, "s": 899, "text": "Edge computing was developed due to the exponential growth of IoT devices connected to the internet for either receiving information from the cloud or delivering data back to the cloud. And many Internet of Things (IoT) devices generate enormous amounts of data during their operations." }, { "code": null, "e": 1626, "s": 1186, "text": "Edge computing provides new possibilities in IoT applications, particularly for those relying on machine learning (ML) for tasks such as object and pose detection, image (and face) recognition, language processing, and obstacle avoidance. Image data is an excellent addition to IoT, but also a significant resource consumer (as power, memory, and processing). Image processing “at the Edge”, running classics AI/ML models, is a great leap!" }, { "code": null, "e": 1740, "s": 1626, "text": "Machine Learning can be divided into two separated process: Training and Inference, as explained in Gartner Blog:" }, { "code": null, "e": 2147, "s": 1740, "text": "Training: Training refers to the process of creating a machine learning algorithm. Training involves using a deep-learning framework (e.g., TensorFlow) and training dataset (see the left-hand side of the above figure). IoT data provides a source of training data that data scientists and engineers can use to train machine learning models for various cases, from failure detection to consumer intelligence." }, { "code": null, "e": 2494, "s": 2147, "text": "Inference: Inference refers to the process of using a trained machine-learning algorithm to make a prediction. IoT data can be used as the input to a trained machine learning model, enabling predictions that can guide decision logic on the device, at the edge gateway, or elsewhere in the IoT system (see the right-hand side of the above figure)." }, { "code": null, "e": 2797, "s": 2494, "text": "TensorFlow Lite is an open-source deep learning framework that enables on-device machine learning inference with low latency and small binary size. It is designed to make it easy to perform machine learning on devices, “at the edge” of the network, instead of sending data back and forth from a server." }, { "code": null, "e": 2856, "s": 2797, "text": "Performing machine learning on-device can help to improve:" }, { "code": null, "e": 2899, "s": 2856, "text": "Latency: there’s no round-trip to a server" }, { "code": null, "e": 2942, "s": 2899, "text": "Privacy: no data needs to leave the device" }, { "code": null, "e": 2994, "s": 2942, "text": "Connectivity: an Internet connection isn’t required" }, { "code": null, "e": 3050, "s": 2994, "text": "Power consumption: network connections are power-hungry" }, { "code": null, "e": 3108, "s": 3050, "text": "TensorFlow Lite (TFLite) consists of two main components:" }, { "code": null, "e": 3286, "s": 3108, "text": "The TFLite converter, which converts TensorFlow models into an efficient form for use by the interpreter, and can introduce optimizations to improve binary size and performance." }, { "code": null, "e": 3451, "s": 3286, "text": "The TFLite interpreter runs with specially optimized models on many different hardware types, including mobile phones, embedded Linux devices, and microcontrollers." }, { "code": null, "e": 3720, "s": 3451, "text": "In summary, a trained and saved TensorFlow model (like model.h5) can be converted using TFLite Converter in a TFLite FlatBuffer (like model.tflite) that will be used by TF Lite Interpreter inside the Edge device (as a Raspberry Pi), to perform inference on a new data." }, { "code": null, "e": 4285, "s": 3720, "text": "For example, I trained from scratch a simple CNN Image Classification model in my Mac (the “Server” on the above figure). The final model had 225,610 parameters to be trained, using as input the CIFAR10 dataset: 60,000 images (shape: 32, 32, 3). The trained model (cifar10_model.h5) had a size of 2.7Mb. Using the TFLite Converter, the model used on Raspberry Pi (model_cifar10.tflite) became with 905Kb (around 1/3 of original size). Making inference with both models (.h5 at Mac and .tflite at RPi) leaves the same results. Both notebooks can be found at GitHub." }, { "code": null, "e": 4511, "s": 4285, "text": "It is also possible to train models from scratch at Raspberry Pi, and for that, the full TensorFlow package is needed. But once what we will do is only the inference part, we will install just the TensorFlow Lite interpreter." }, { "code": null, "e": 4764, "s": 4511, "text": "The interpreter-only package is a fraction the size of the full TensorFlow package and includes the bare minimum code required to run inferences with TensorFlow Lite. It includes only the tf.lite.InterpreterPython class, used to execute .tflite models." }, { "code": null, "e": 5044, "s": 4764, "text": "Let’s open the terminal at Raspberry Pi and install the Python wheel needed for your specific system configuration. The options can be found on this link: Python Quickstart. For example, in my case, I am running Linux ARM32 (Raspbian Buster — Python 3.7), so the command line is:" }, { "code": null, "e": 5154, "s": 5044, "text": "$ sudo pip3 install https://dl.google.com/coral/python/tflite_runtime-2.1.0.post1-cp37-cp37m-linux_armv7l.whl" }, { "code": null, "e": 5246, "s": 5154, "text": "If you want to double-check what OS version you have in your Raspberry Pi, run the command:" }, { "code": null, "e": 5256, "s": 5246, "text": "$ uname -" }, { "code": null, "e": 5345, "s": 5256, "text": "As shown on image below, if you get ...arm7l..., the operating system is a 32bits Linux." }, { "code": null, "e": 5604, "s": 5345, "text": "Installing the Python wheel is the only requirement for having TFLite interpreter working in a Raspberry Pi. It is possible to double-check if the installation is OK, calling the TFLite interpreter at the terminal, as below. If no errors appear, we are good." }, { "code": null, "e": 6091, "s": 5604, "text": "One of the more classic tasks of IA applied to Computer Vision (CV) is Image Classification. Starting on 2012, IA and Deep Learning (DL) changed forever, when a convolutional neural network (CNN) called AlexNet (in honor of its leading developer, Alex Krizhevsky), achieved a top-5 error of 15.3% in the ImageNet 2012 Challenge. According to The Economist, “Suddenly people started to pay attention (in DL), not just within the AI community but across the technology industry as a whole" }, { "code": null, "e": 6386, "s": 6091, "text": "This project, almost eight years after Alex Krizhevsk, a more modern architecture (MobileNet), was also pre-trained over millions of images, using the same dataset ImageNet, resulting in 1,000 different classes. This pre-trained and quantized model was so, converted in a .tflite and used here." }, { "code": null, "e": 6568, "s": 6386, "text": "First, let’s on Raspberry Pi move to a working directory (for example, Image_Recognition). Next, it is essential to create two subdirectories, one for models and another for images:" }, { "code": null, "e": 6597, "s": 6568, "text": "$ mkdir images$ mkdir models" }, { "code": null, "e": 6916, "s": 6597, "text": "Once inside the model’s directory, let’s download the pre-trained model (in this link, it is possible to download several different models). We will use a quantized Mobilenet V1 model, pre-trained with images of 224x224 pixels. The zip file that can be downloaded from TensorFlow Lite Image classification, using wget:" }, { "code": null, "e": 7045, "s": 6916, "text": "$ cd models$ wget https://storage.googleapis.com/download.tensorflow.org/models/tflite/mobilenet_v1_1.0_224_quant_and_labels.zip" }, { "code": null, "e": 7067, "s": 7045, "text": "Next, unzip the file:" }, { "code": null, "e": 7113, "s": 7067, "text": "$ unzip mobilenet_v1_1.0_224_quant_and_labels" }, { "code": null, "e": 7139, "s": 7113, "text": "Two files are downloaded:" }, { "code": null, "e": 7208, "s": 7139, "text": "mobilenet_v1_1.0_224_quant.tflite: TensorFlow-Lite transformed model" }, { "code": null, "e": 7285, "s": 7208, "text": "labels_mobilenet_quant_v1_224.txt: The ImageNet dataset 1,000 Classes Labels" }, { "code": null, "e": 7382, "s": 7285, "text": "Now, get some images (for example, .png, .jpg) and save them on the created images subdirectory." }, { "code": null, "e": 7450, "s": 7382, "text": "On GitHub, it is possible to find the images used on this tutorial." }, { "code": null, "e": 7747, "s": 7450, "text": "OpenCV (Open Source Computer Vision Library) is an open-source computer vision and machine learning software library. It is beneficial as a support when working with images. If very simple to install it on a Mac or PC is a little bit “trick” to do it on a Raspberry Pi, but I recommend to use it." }, { "code": null, "e": 7993, "s": 7747, "text": "Please follow this great tutorial from Q-Engineering to install OpenCV on your Raspberry Pi: Install OpenCV 4.4.0 on Raspberry Pi 4. Although written for the Raspberry Pi 4, the guide can also be used without any change for the Raspberry 3 or 2." }, { "code": null, "e": 8062, "s": 7993, "text": "Next, Install Jupyter Notebook. It will be our development platform." }, { "code": null, "e": 8108, "s": 8062, "text": "$ sudo pip3 install jupyter$ jupyter notebook" }, { "code": null, "e": 8216, "s": 8108, "text": "Also, during OpenCV installation, NumPy should have been installed, if not do it now, same with MatPlotLib." }, { "code": null, "e": 8283, "s": 8216, "text": "$ sudo pip3 install numpy$ sudo apt-get install python3-matplotlib" }, { "code": null, "e": 8364, "s": 8283, "text": "And it is done! We have everything in place to start our AI journey to the Edge!" }, { "code": null, "e": 8468, "s": 8364, "text": "Create a fresh Jupyter Notebook and follow bellow steps, or download the complete notebook from GitHub." }, { "code": null, "e": 8486, "s": 8468, "text": "Import Libraries:" }, { "code": null, "e": 8589, "s": 8486, "text": "import numpy as npimport matplotlib.pyplot as pltimport cv2import tflite_runtime.interpreter as tflite" }, { "code": null, "e": 8629, "s": 8589, "text": "Load TFLite model and allocate tensors:" }, { "code": null, "e": 8749, "s": 8629, "text": "interpreter = tflite.Interpreter(model_path=’./models/mobilenet_v1_1.0_224_quant.tflite’)interpreter.allocate_tensors()" }, { "code": null, "e": 8779, "s": 8749, "text": "Get input and output tensors:" }, { "code": null, "e": 8876, "s": 8779, "text": "input_details = interpreter.get_input_details()output_details = interpreter.get_output_details()" }, { "code": null, "e": 8970, "s": 8876, "text": "input details will give you the info needed about how the model should be feed with an image:" }, { "code": null, "e": 9157, "s": 8970, "text": "The shape of (1, 224x224x3), informs that an image with dimensions: (224x224x3) should be input one by one (Batch Dimension: 1). The dtype uint8, tells that the values are 8bits integers" }, { "code": null, "e": 9399, "s": 9157, "text": "The output details show that the inference will result in an array of 1,001 integer values (8 bits). Those values are the result of the image classification, where each value is the probability of that specific label be related to the image." }, { "code": null, "e": 9685, "s": 9399, "text": "For example, suppose that we want to classify an image wich shape is (1220, 1200, 3). First, we will need to reshape it to (224, 224, 3) and add a batch dimension of 1, as defined on input details: (1, 224, 224, 3). The inference result will be an array with 1001 size, as shown below:" }, { "code": null, "e": 9725, "s": 9685, "text": "The steps to code those operations are:" }, { "code": null, "e": 9791, "s": 9725, "text": "Input image and convert it to RGB (OpenCV reads an image as BGR):" }, { "code": null, "e": 9857, "s": 9791, "text": "Input image and convert it to RGB (OpenCV reads an image as BGR):" }, { "code": null, "e": 9965, "s": 9857, "text": "image_path = './images/cat_2.jpg'image = cv2.imread(image_path)img = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)" }, { "code": null, "e": 10029, "s": 9965, "text": "2. Pre-process the image, reshaping and adding batch dimension:" }, { "code": null, "e": 10103, "s": 10029, "text": "img = cv2.resize(img, (224, 224))input_data = np.expand_dims(img, axis=0)" }, { "code": null, "e": 10169, "s": 10103, "text": "3. Point the data to be used for testing and run the interpreter:" }, { "code": null, "e": 10251, "s": 10169, "text": "interpreter.set_tensor(input_details[0]['index'], input_data)interpreter.invoke()" }, { "code": null, "e": 10298, "s": 10251, "text": "4. Obtain results and map them to the classes:" }, { "code": null, "e": 10366, "s": 10298, "text": "predictions = interpreter.get_tensor(output_details[0][‘index’])[0]" }, { "code": null, "e": 10649, "s": 10366, "text": "The output values (predictions) varies from 0 to 255 (max value of an 8bit integer). To obtain a prediction that will range from 0 to 1, the output value should be divided by 255. The array’s index, related to the highest value, is the most probable classification of such an image." }, { "code": null, "e": 10839, "s": 10649, "text": "Having the index, we must find to what class it appoint (such as car, cat, or dog). The text file downloaded with the model has a label associated with each index that goes from 0 to 1,000." }, { "code": null, "e": 10908, "s": 10839, "text": "Let’s first create a function to load the .txt file as a dictionary:" }, { "code": null, "e": 11033, "s": 10908, "text": "def load_labels(path): with open(path, 'r') as f: return {i: line.strip() for i, line in enumerate(f.readlines())}" }, { "code": null, "e": 11099, "s": 11033, "text": "And create a dictionary named labels and inspecting some of them:" }, { "code": null, "e": 11166, "s": 11099, "text": "labels = load_labels('./models/labels_mobilenet_quant_v1_224.txt')" }, { "code": null, "e": 11245, "s": 11166, "text": "Returning to our example, let’s get the top 3 results (highest probabilities):" }, { "code": null, "e": 11324, "s": 11245, "text": "top_k_indices = 3top_k_indices = np.argsort(predictions)[::-1][:top_k_results]" }, { "code": null, "e": 11614, "s": 11324, "text": "We can see that the 3 top indices are related to cats. The prediction content is the probability associated with each one of the labels. As explained before, dividing by 255., we can get a value from 0 to 1. Let’s create a loop to go over the top results, printing label and probabilities:" }, { "code": null, "e": 11770, "s": 11614, "text": "for i in range(top_k_results): print(\"\\t{:20}: {}%\".format( labels[top_k_indices[i]], int((predictions[top_k_indices[i]] / 255.0) * 100)))" }, { "code": null, "e": 11846, "s": 11770, "text": "Let’s create a function, to perform inference on different images smoothly:" }, { "code": null, "e": 12512, "s": 11846, "text": "def image_classification(image_path, labels, top_k_results=3): image = cv2.imread(image_path) img = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) plt.imshow(img)img = cv2.resize(img, (w, h)) input_data = np.expand_dims(img, axis=0)interpreter.set_tensor(input_details[0]['index'], input_data) interpreter.invoke() predictions = interpreter.get_tensor(output_details[0]['index'])[0]top_k_indices = np.argsort(predictions)[::-1][:top_k_results]print(\"\\n\\t[PREDICTION] [Prob]\\n\") for i in range(top_k_results): print(\"\\t{:20}: {}%\".format( labels[top_k_indices[i]], int((predictions[top_k_indices[i]] / 255.0) * 100)))" }, { "code": null, "e": 12566, "s": 12512, "text": "The figure below shows some tests using the function:" }, { "code": null, "e": 12789, "s": 12566, "text": "The overall performance is astonishing! From the instant that you enter with the image path in the memory card, until the time that that result is printed out, all process took less than half a second, with high precision!" }, { "code": null, "e": 12961, "s": 12789, "text": "The function can be easily applied to frames on videos or live camera. The notebook for that and the complete code discussed in this section can be downloaded from GitHub." }, { "code": null, "e": 13184, "s": 12961, "text": "With Image Classification, we can detect what the dominant subject of such an image is. But what happens if several objects are dominant and of interest on the same image? To solve it, we can use an Object Detection model!" }, { "code": null, "e": 13370, "s": 13184, "text": "Given an image or a video stream, an object detection model can identify which of a known set of objects might be present and provide information about their positions within the image." }, { "code": null, "e": 13556, "s": 13370, "text": "For this task, we will download a Mobilenet V1 model pre-trained using the COCO (Common Objects in Context) dataset. This dataset has more than 200,000 labeled images, in 91 categories." }, { "code": null, "e": 13596, "s": 13556, "text": "On Raspberry terminal run the commands:" }, { "code": null, "e": 13925, "s": 13596, "text": "$ cd ./models $ curl -O http://storage.googleapis.com/download.tensorflow.org/models/tflite/coco_ssd_mobilenet_v1_1.0_quant_2018_06_29.zip$ unzip coco_ssd_mobilenet_v1_1.0_quant_2018_06_29.zip$ curl -O https://dl.google.com/coral/canned_models/coco_labels.txt$ rm coco_ssd_mobilenet_v1_1.0_quant_2018_06_29.zip$ rm labelmap.txt" }, { "code": null, "e": 13981, "s": 13925, "text": "On models subdirectory, we should end with 2 new files:" }, { "code": null, "e": 14012, "s": 13981, "text": "coco_labels.txt detect.tflite" }, { "code": null, "e": 14130, "s": 14012, "text": "The steps to perform inference on a new image, are very similar to those done with Image Classification, except that:" }, { "code": null, "e": 14179, "s": 14130, "text": "input: image must have a shape of 300x300 pixels" }, { "code": null, "e": 14341, "s": 14179, "text": "output: include not only label and probability (“score”), but also the relative window position (“ Bounding Box”) about where the object is located on the image." }, { "code": null, "e": 14401, "s": 14341, "text": "Now, we must load the labels and model, allocating tensors." }, { "code": null, "e": 14531, "s": 14401, "text": "labels = load_labels('./models/coco_labels.txt')interpreter = Interpreter('./models/detect.tflite')interpreter.allocate_tensors()" }, { "code": null, "e": 14687, "s": 14531, "text": "The input pre-process is the same as we did before, but the output should be worked to get a more readable output. The functions below will help with that:" }, { "code": null, "e": 15155, "s": 14687, "text": "def set_input_tensor(interpreter, image): \"\"\"Sets the input tensor.\"\"\" tensor_index = interpreter.get_input_details()[0]['index'] input_tensor = interpreter.tensor(tensor_index)()[0] input_tensor[:, :] = imagedef get_output_tensor(interpreter, index): \"\"\"Returns the output tensor at the given index.\"\"\" output_details = interpreter.get_output_details()[index] tensor = np.squeeze(interpreter.get_tensor(output_details['index'])) return tensor" }, { "code": null, "e": 15245, "s": 15155, "text": "With the help of the above functions, detect_objects() will return the inference results:" }, { "code": null, "e": 15261, "s": 15245, "text": "object label id" }, { "code": null, "e": 15267, "s": 15261, "text": "score" }, { "code": null, "e": 15329, "s": 15267, "text": "the bounding box, that will show where the object is located." }, { "code": null, "e": 15465, "s": 15329, "text": "We have included a ‘threshold’ to avoid objects with a low probability of being correct. Usually, we should consider a score above 50%." }, { "code": null, "e": 16077, "s": 15465, "text": "def detect_objects(interpreter, image, threshold): set_input_tensor(interpreter, image) interpreter.invoke() # Get all output details boxes = get_output_tensor(interpreter, 0) classes = get_output_tensor(interpreter, 1) scores = get_output_tensor(interpreter, 2) count = int(get_output_tensor(interpreter, 3)) results = [] for i in range(count): if scores[i] >= threshold: result = { 'bounding_box': boxes[i], 'class_id': classes[i], 'score': scores[i] } results.append(result) return results" }, { "code": null, "e": 16185, "s": 16077, "text": "If we apply the above function to a reshaped image (same as used on classification example), we should get:" }, { "code": null, "e": 16432, "s": 16185, "text": "Great! In less than 200ms with 77% probability, an object with id 16 was detected on an area delimited by a ‘bounding box’: (0.028011084, 0.020121813, 0.9886069, 0.802299). Those four numbers are respectively related to ymin, xmin, ymax and xmax." }, { "code": null, "e": 16579, "s": 16432, "text": "Take into consideration that y goes from the top (ymin) to bottom (ymax) and x goes from left (xmin) to the right (xmax) as shown in figure below:" }, { "code": null, "e": 16809, "s": 16579, "text": "Having the bounding box four values, we have, in fact, the coordinates of the top/left corner and the bottom/right one. With both edges and knowing the shape of the picture, it is possible to draw the rectangle around the object." }, { "code": null, "e": 17067, "s": 16809, "text": "Next, we should find what class_id equal to 16 means. Opening the file coco_labels.txt, as a dictionary, each of its elements has an index associated, and inspecting index 16, we get as expected, ‘cat.’ The probability is the value returning from the score." }, { "code": null, "e": 17329, "s": 17067, "text": "Let’s create a general function to detect multiple objects on a single picture. The first function, starting from an image path, will execute the inference, returning the resized image and the results (multiples ids, each one with its scores and bounding boxes:" }, { "code": null, "e": 17687, "s": 17329, "text": "def detectObjImg_2(image_path, threshold = 0.51):img = cv2.imread(image_path) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) image = cv2.resize(img, (width, height), fx=0.5, fy=0.5, interpolation=cv2.INTER_AREA) results = detect_objects(interpreter, image, threshold)return img, results" }, { "code": null, "e": 17860, "s": 17687, "text": "Having the reshaped image, and inference results, the below function can be used to draw a rectangle around the objects, specifying for each one, its label and probability:" }, { "code": null, "e": 18792, "s": 17860, "text": "def detect_mult_object_picture(img, results): HEIGHT, WIDTH, _ = img.shape aspect = WIDTH / HEIGHT WIDTH = 640 HEIGHT = int(640 / aspect) dim = (WIDTH, HEIGHT) img = cv2.resize(img, dim, interpolation=cv2.INTER_AREA) for i in range(len(results)): id = int(results[i]['class_id']) prob = int(round(results[i]['score'], 2) * 100) ymin, xmin, ymax, xmax = results[i]['bounding_box'] xmin = int(xmin * WIDTH) xmax = int(xmax * WIDTH) ymin = int(ymin * HEIGHT) ymax = int(ymax * HEIGHT) text = \"{}: {}%\".format(labels[id], prob) if ymin > 10: ytxt = ymin - 10 else: ytxt = ymin + 15 img = cv2.rectangle(img, (xmin, ymin), (xmax, ymax), COLORS[id], thickness=2) img = cv2.putText(img, text, (xmin + 3, ytxt), FONT, 0.5, COLORS[id], 2) return img" }, { "code": null, "e": 18812, "s": 18792, "text": "Below some results:" }, { "code": null, "e": 18854, "s": 18812, "text": "The complete code can be found at GitHub." }, { "code": null, "e": 19140, "s": 18854, "text": "If you have a PiCam connected to Raspberry Pi, it is possible to capture a video and perform object recognition, frame by frame, using the same functions defined before. Please follow this tutorial if you do not have a working camera in your Pi: Getting started with the Camera Module." }, { "code": null, "e": 19246, "s": 19140, "text": "First, it is essential to define the size of the frame to be captured by the camera. We will use 640x480." }, { "code": null, "e": 19270, "s": 19246, "text": "WIDTH = 640HEIGHT = 480" }, { "code": null, "e": 19306, "s": 19270, "text": "Next, you must iniciate the camera:" }, { "code": null, "e": 19367, "s": 19306, "text": "cap = cv2.VideoCapture(0)cap.set(3, WIDTH)cap.set(4, HEIGHT)" }, { "code": null, "e": 19553, "s": 19367, "text": "And run the below code in a loop. Until the key ‘q’ is pressed, the camera will capture the video, frame by frame, drawing the bounding box with its respective labels and probabilities." }, { "code": null, "e": 20393, "s": 19553, "text": "while True: timer = cv2.getTickCount() success, img = cap.read() img = cv2.flip(img, 0) img = cv2.flip(img, 1) fps = cv2.getTickFrequency() / (cv2.getTickCount() - timer) cv2.putText(img, \"FPS: \" + str(int(fps)), (10, 470), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2) image = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) image = cv2.resize(image, (width, height), fx=0.5, fy=0.5, interpolation=cv2.INTER_AREA) start_time = time.time() results = detect_objects(interpreter, image, 0.55) elapsed_ms = (time.time() - start_time) * 1000 img = detect_mult_object_picture(img, results) cv2.imshow(\"Image Recognition ==> Press [q] to Exit\", img)if cv2.waitKey(1) & 0xFF == ord('q'): breakcap.release()cv2.destroyAllWindows()" }, { "code": null, "e": 20560, "s": 20393, "text": "Below is possible to see the video running in real-time on the Raspberry Pi screen. Note that the video runs around 60 FPS (frames per second), which is pretty good!." }, { "code": null, "e": 20601, "s": 20560, "text": "Here one screen-shot of the above video:" }, { "code": null, "e": 20643, "s": 20601, "text": "The complete code is available on GitHub." }, { "code": null, "e": 21081, "s": 20643, "text": "One of the more exciting and critical areas of AI is to estimate a person’s real-time pose, enabling machines to understand what people are doing in images and videos. Pose estimation was deeply explored in my article Realtime Multiple Person 2D Pose Estimation using TensorFlow2.x, but here at the Edge, with a Raspberry Pi and with the help of TensorFlow Lite, it is possible to easily replicate almost the same that was done on a Mac." }, { "code": null, "e": 21671, "s": 21081, "text": "The model that we will use in this project is the PoseNet. We will do inference the same way done for Image Classification and Object Detection, where an image is fed through a pre-trained model. PoseNet comes with a few different versions of the model, corresponding to variances of MobileNet v1 architecture and ResNet50 architecture. In this project, the version pre-trained is the MobileNet V1, which is smaller, faster, but less accurate than ResNet. Also, there are separate models for single and multiple person pose detection. We will explore the model trained for a single person." }, { "code": null, "e": 21788, "s": 21671, "text": "In this site is possible to explore in real time and using a live camera, several PoseNet models and configurations." }, { "code": null, "e": 21932, "s": 21788, "text": "The libraries to execute Pose Estimation on a Raspberry Pi are the same used before. NumPy, MatPlotLib, OpenCV and TensorFlow Lite Interpreter." }, { "code": null, "e": 22178, "s": 21932, "text": "The pre-trained model is the posenet_mobilenet_v1_100_257x257_multi_kpt_stripped.tflite, which can be downloaded from the above link or the TensorFlow Lite — Pose Estimation Overview website. The model should be saved in the models subdirectory." }, { "code": null, "e": 22229, "s": 22178, "text": "Start loading TFLite model and allocating tensors:" }, { "code": null, "e": 22374, "s": 22229, "text": "interpreter = tflite.Interpreter(model_path='./models/posenet_mobilenet_v1_100_257x257_multi_kpt_stripped.tflite')interpreter.allocate_tensors()" }, { "code": null, "e": 22404, "s": 22374, "text": "Get input and output tensors:" }, { "code": null, "e": 22501, "s": 22404, "text": "input_details = interpreter.get_input_details()output_details = interpreter.get_output_details()" }, { "code": null, "e": 22711, "s": 22501, "text": "Same as we did before, looking into the input_details, it is possible to see that the image to be used to pose estimation should be (1, 257, 257, 3), which means that images must be reshaped to 257x257 pixels." }, { "code": null, "e": 22787, "s": 22711, "text": "Let’s take as input a simple human figure, that will help us to analyze it:" }, { "code": null, "e": 23002, "s": 22787, "text": "The first step is to pre-process the image. This particular model was not quantized, which means that the dtype is float32. This information is essential to pre-process the input image, as shown with the below code" }, { "code": null, "e": 23172, "s": 23002, "text": "image = cv2.resize(image, size) input_data = np.expand_dims(image, axis=0)input_data = input_data.astype(np.float32)input_data = (np.float32(input_data) - 127.5) / 127.5" }, { "code": null, "e": 23309, "s": 23172, "text": "Having the image pre-processed, now it is time to perform the inference, feeding the tensor with the image and invoking the interpreter:" }, { "code": null, "e": 23391, "s": 23309, "text": "interpreter.set_tensor(input_details[0]['index'], input_data)interpreter.invoke()" }, { "code": null, "e": 23630, "s": 23391, "text": "An article that helps a lot to understand how to work with PoseNet is the Ivan Kunyakin tutorial’s Pose estimation and matching with TensorFlow lite. There Ivan comments that on the output vector, what matters to find the key points, are:" }, { "code": null, "e": 23866, "s": 23630, "text": "Heatmaps 3D tensor of size (9,9,17), that corresponds to the probability of appearance of each one of the 17 keypoints (body joints) in the particular part of the image (9,9). It is used to locate the approximate position of the joint." }, { "code": null, "e": 24122, "s": 23866, "text": "Offset Vectors: 3D tensor of size (9,9,34) that is called offset vectors. It is used for more exact calculation of the keypoint’s position. The First 17 of the third dimension correspond to the x coordinates and the second 17 of them to the y coordinates." }, { "code": null, "e": 24366, "s": 24122, "text": "output_details = interpreter.get_output_details()[0]heatmaps = np.squeeze(interpreter.get_tensor(output_details['index']))output_details = interpreter.get_output_details()[1]offsets = np.squeeze(interpreter.get_tensor(output_details['index']))" }, { "code": null, "e": 24490, "s": 24366, "text": "Let’s create a function that will return an array with all 17 keypoints (or person's joints) based on heatmaps and offsets." }, { "code": null, "e": 25239, "s": 24490, "text": "def get_keypoints(heatmaps, offsets): joint_num = heatmaps.shape[-1] pose_kps = np.zeros((joint_num, 2), np.uint32) max_prob = np.zeros((joint_num, 1)) for i in range(joint_num): joint_heatmap = heatmaps[:,:,i] max_val_pos = np.squeeze( np.argwhere(joint_heatmap == np.max(joint_heatmap))) remap_pos = np.array(max_val_pos / 8 * 257, dtype=np.int32) pose_kps[i, 0] = int(remap_pos[0] + offsets[max_val_pos[0], max_val_pos[1], i]) pose_kps[i, 1] = int(remap_pos[1] + offsets[max_val_pos[0], max_val_pos[1], i + joint_num]) max_prob[i] = np.amax(joint_heatmap) return pose_kps, max_prob" }, { "code": null, "e": 25387, "s": 25239, "text": "Using the above function with the heatmaps and offset vectors that were extracted from the output tensor, resultant of the image inference, we get:" }, { "code": null, "e": 25686, "s": 25387, "text": "The resultant array shows all 17 coordinates (y, x) regarding where the joints are located on an image of 257 x 257 pixels. Using the code below. It is possible to plot each one of the joints over the resized image. For reference, the array index is annotated, so it is easy to identify each joint:" }, { "code": null, "e": 26076, "s": 25686, "text": "y,x = zip(*keypts_array)plt.figure(figsize=(10,10))plt.axis([0, image.shape[1], 0, image.shape[0]]) plt.scatter(x,y, s=300, color='orange', alpha=0.6)img = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)plt.imshow(img)ax=plt.gca() ax.set_ylim(ax.get_ylim()[::-1]) ax.xaxis.tick_top() plt.grid();for i, txt in enumerate(keypts_array): ax.annotate(i, (keypts_array[i][1]-3, keypts_array[i][0]+1))" }, { "code": null, "e": 26108, "s": 26076, "text": "As a result, we get the picure:" }, { "code": null, "e": 26400, "s": 26108, "text": "Great, now it is time to create a general function to draw “the bones”, which is the joints’ connection. The bones will be drawn as lines, which are the connections among keypoints 5 to 16, as shown in the above figure. Independent circles will be used for keypoints 0 to 4, related to head:" }, { "code": null, "e": 27152, "s": 26400, "text": "def join_point(img, kps, color='white', bone_size=1): if color == 'blue' : color=(255, 0, 0) elif color == 'green': color=(0, 255, 0) elif color == 'red': color=(0, 0, 255) elif color == 'white': color=(255, 255, 255) else: color=(0, 0, 0) body_parts = [(5, 6), (5, 7), (6, 8), (7, 9), (8, 10), (11, 12), (5, 11), (6, 12), (11, 13), (12, 14), (13, 15), (14, 16)] for part in body_parts: cv2.line(img, (kps[part[0]][1], kps[part[0]][0]), (kps[part[1]][1], kps[part[1]][0]), color=color, lineType=cv2.LINE_AA, thickness=bone_size) for i in range(0,len(kps)): cv2.circle(img,(kps[i,1],kps[i,0]),2,(255,0,0),-1)" }, { "code": null, "e": 27227, "s": 27152, "text": "Calling the function, we have the estimated pose of the body in the image:" }, { "code": null, "e": 27313, "s": 27227, "text": "join_point(img, keypts_array, bone_size=2)plt.figure(figsize=(10,10))plt.imshow(img);" }, { "code": null, "e": 27422, "s": 27313, "text": "And last but not least, let’s create a general function to estimate posture having an image path as a start:" }, { "code": null, "e": 28827, "s": 27422, "text": "def plot_pose(img, keypts_array, joint_color='red', bone_color='blue', bone_size=1): join_point(img, keypts_array, bone_color, bone_size) y,x = zip(*keypts_array) plt.figure(figsize=(10,10)) plt.axis([0, img.shape[1], 0, img.shape[0]]) plt.scatter(x,y, s=100, color=joint_color) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) plt.imshow(img) ax=plt.gca() ax.set_ylim(ax.get_ylim()[::-1]) ax.xaxis.tick_top() plt.grid(); return imgdef get_plot_pose(image_path, size, joint_color='red', bone_color='blue', bone_size=1): image_original = cv2.imread(image_path) image = cv2.resize(image_original, size) input_data = np.expand_dims(image, axis=0) input_data = input_data.astype(np.float32) input_data = (np.float32(input_data) - 127.5) / 127.5 interpreter.set_tensor(input_details[0]['index'], input_data) interpreter.invoke() output_details = interpreter.get_output_details()[0] heatmaps = np.squeeze(interpreter.get_tensor(output_details['index'])) output_details = interpreter.get_output_details()[1] offsets = np.squeeze(interpreter.get_tensor(output_details['index'])) keypts_array, max_prob = get_keypoints(heatmaps,offsets) orig_kps = get_original_pose_keypoints(image_original, keypts_array, size) img = plot_pose(image_original, orig_kps, joint_color, bone_color, bone_size) return orig_kps, max_prob, img" }, { "code": null, "e": 28910, "s": 28827, "text": "At this point with only one line of code, it is possible to detect pose on images:" }, { "code": null, "e": 28986, "s": 28910, "text": "keypts_array, max_prob, img = get_plot_pose(image_path, size, bone_size=3)" }, { "code": null, "e": 29045, "s": 28986, "text": "All code developed on this section is available on GitHub." }, { "code": null, "e": 29156, "s": 29045, "text": "Another easy step is to apply the function to frames from videos and live camera. I will leave it for you! ;-)" }, { "code": null, "e": 29446, "s": 29156, "text": "TensorFlow Lite is a great framework to implement Artificial Intelligence (more precisely, ML) at the Edge. Here we explored ML models working on a Raspberry Pi, but TFLite is now more and more used at the \"edge of the edge\", on very small microcontrollers, in what has been called TinyML." }, { "code": null, "e": 29544, "s": 29446, "text": "As always, I hope this article can inspire others to find their way in the fantastic world of AI!" }, { "code": null, "e": 29648, "s": 29544, "text": "All the codes used in this article are available for download on project GitHub: TFLite_IA_at_the_Edge." }, { "code": null, "e": 29685, "s": 29648, "text": "Regards from the South of the World!" } ]
C++ Library - <unordered_set>
It is an associative container that store unique elements in no particular order, and which allow for fast retrieval of individual elements based on their value. Below is definition of std::unordered_set template < class Key, class Hash = hash<Key>, class Pred = equal_to<Key>, class Alloc = allocator<Key> > class unordered_set; Key − It defines the type of element. Key − It defines the type of element. Hash − It is a unary function object. Hash − It is a unary function object. Pred − It is a binary predicate that takes two arguments of the same type as the elements and returns a bool. Pred − It is a binary predicate that takes two arguments of the same type as the elements and returns a bool. Alloc − It defines the type of allowcater. Alloc − It defines the type of allowcater. Following member types can be used as parameters or return type by member functions. Below is list of member functions It constructs unordered_set. It destroys unordered_set. It is used to assign the content. It is used to test whether container is empty. It returns container size. It returns maximum size. It returns iterator to beginning. It returns iterator to end. It returns const_iterator to beginning. It return const_iterator to end. It is used to get iterator to element. It is used to count elements with a specific key. It is used to get range of elements with a specific key. It is used to construct and insert element. It is used to construct and insert element with hint. It is used to insert elements. It is used to erase elements. It is used to clear content. It is used to swap content. It returns number of buckets. It returns maximum number of buckets. It returns bucket size. It locates element's bucket. It returns load factor. It is used to get or set maximum load factor. It is used to set number of buckets. It gives a request to capacity chage of backets It is used to get hash function. It is used to get key equivalence predicate. It is used to get allocator. It is used to get hash function. It exchanges contents of two unordered_set containers. It is used to get hash function. It exchanges contents of two unordered_set containers. Print Add Notes Bookmark this page
[ { "code": null, "e": 2765, "s": 2603, "text": "It is an associative container that store unique elements in no particular order, and which allow for fast retrieval of individual elements based on their value." }, { "code": null, "e": 2807, "s": 2765, "text": "Below is definition of std::unordered_set" }, { "code": null, "e": 3016, "s": 2807, "text": "template < class Key, \n class Hash = hash<Key>, \n class Pred = equal_to<Key>, \n class Alloc = allocator<Key> \n > class unordered_set;" }, { "code": null, "e": 3054, "s": 3016, "text": "Key − It defines the type of element." }, { "code": null, "e": 3092, "s": 3054, "text": "Key − It defines the type of element." }, { "code": null, "e": 3130, "s": 3092, "text": "Hash − It is a unary function object." }, { "code": null, "e": 3168, "s": 3130, "text": "Hash − It is a unary function object." }, { "code": null, "e": 3278, "s": 3168, "text": "Pred − It is a binary predicate that takes two arguments of the same type as the elements and returns a bool." }, { "code": null, "e": 3388, "s": 3278, "text": "Pred − It is a binary predicate that takes two arguments of the same type as the elements and returns a bool." }, { "code": null, "e": 3431, "s": 3388, "text": "Alloc − It defines the type of allowcater." }, { "code": null, "e": 3474, "s": 3431, "text": "Alloc − It defines the type of allowcater." }, { "code": null, "e": 3559, "s": 3474, "text": "Following member types can be used as parameters or return type by member functions." }, { "code": null, "e": 3593, "s": 3559, "text": "Below is list of member functions" }, { "code": null, "e": 3622, "s": 3593, "text": "It constructs unordered_set." }, { "code": null, "e": 3649, "s": 3622, "text": "It destroys unordered_set." }, { "code": null, "e": 3683, "s": 3649, "text": "It is used to assign the content." }, { "code": null, "e": 3730, "s": 3683, "text": "It is used to test whether container is empty." }, { "code": null, "e": 3757, "s": 3730, "text": "It returns container size." }, { "code": null, "e": 3782, "s": 3757, "text": "It returns maximum size." }, { "code": null, "e": 3816, "s": 3782, "text": "It returns iterator to beginning." }, { "code": null, "e": 3844, "s": 3816, "text": "It returns iterator to end." }, { "code": null, "e": 3884, "s": 3844, "text": "It returns const_iterator to beginning." }, { "code": null, "e": 3917, "s": 3884, "text": "It return const_iterator to end." }, { "code": null, "e": 3956, "s": 3917, "text": "It is used to get iterator to element." }, { "code": null, "e": 4006, "s": 3956, "text": "It is used to count elements with a specific key." }, { "code": null, "e": 4063, "s": 4006, "text": "It is used to get range of elements with a specific key." }, { "code": null, "e": 4107, "s": 4063, "text": "It is used to construct and insert element." }, { "code": null, "e": 4161, "s": 4107, "text": "It is used to construct and insert element with hint." }, { "code": null, "e": 4192, "s": 4161, "text": "It is used to insert elements." }, { "code": null, "e": 4222, "s": 4192, "text": "It is used to erase elements." }, { "code": null, "e": 4251, "s": 4222, "text": "It is used to clear content." }, { "code": null, "e": 4279, "s": 4251, "text": "It is used to swap content." }, { "code": null, "e": 4309, "s": 4279, "text": "It returns number of buckets." }, { "code": null, "e": 4347, "s": 4309, "text": "It returns maximum number of buckets." }, { "code": null, "e": 4371, "s": 4347, "text": "It returns bucket size." }, { "code": null, "e": 4400, "s": 4371, "text": "It locates element's bucket." }, { "code": null, "e": 4424, "s": 4400, "text": "It returns load factor." }, { "code": null, "e": 4470, "s": 4424, "text": "It is used to get or set maximum load factor." }, { "code": null, "e": 4507, "s": 4470, "text": "It is used to set number of buckets." }, { "code": null, "e": 4555, "s": 4507, "text": "It gives a request to capacity chage of backets" }, { "code": null, "e": 4588, "s": 4555, "text": "It is used to get hash function." }, { "code": null, "e": 4633, "s": 4588, "text": "It is used to get key equivalence predicate." }, { "code": null, "e": 4662, "s": 4633, "text": "It is used to get allocator." }, { "code": null, "e": 4695, "s": 4662, "text": "It is used to get hash function." }, { "code": null, "e": 4750, "s": 4695, "text": "It exchanges contents of two unordered_set containers." }, { "code": null, "e": 4783, "s": 4750, "text": "It is used to get hash function." }, { "code": null, "e": 4838, "s": 4783, "text": "It exchanges contents of two unordered_set containers." }, { "code": null, "e": 4845, "s": 4838, "text": " Print" }, { "code": null, "e": 4856, "s": 4845, "text": " Add Notes" } ]
C# program to create an empty string array
To create an empty string array − string[] str = new string[] {}; Above, we haven’t added elements to the array, since it is empty. Even if we will loop though the array, it won’t display anything as shown below − Live Demo using System; public class Demo { public static void Main() { string[] str = new string[] {}; Console.WriteLine("String Array elements won't get displayed since it's empty..."); for (int i = 0; i < str.Length; i++) { string res = str[i]; Console.WriteLine(res); } } } String Array elements won't get displayed since it's empty...
[ { "code": null, "e": 1096, "s": 1062, "text": "To create an empty string array −" }, { "code": null, "e": 1128, "s": 1096, "text": "string[] str = new string[] {};" }, { "code": null, "e": 1194, "s": 1128, "text": "Above, we haven’t added elements to the array, since it is empty." }, { "code": null, "e": 1276, "s": 1194, "text": "Even if we will loop though the array, it won’t display anything as shown below −" }, { "code": null, "e": 1287, "s": 1276, "text": " Live Demo" }, { "code": null, "e": 1604, "s": 1287, "text": "using System;\n\npublic class Demo {\n public static void Main() {\n string[] str = new string[] {};\n Console.WriteLine(\"String Array elements won't get displayed since it's empty...\");\n for (int i = 0; i < str.Length; i++) {\n string res = str[i];\n Console.WriteLine(res);\n }\n }\n}" }, { "code": null, "e": 1666, "s": 1604, "text": "String Array elements won't get displayed since it's empty..." } ]
What is the difference between single-line and multi-line comments in JavaScript?
Single Line comment The following is a single line comment in JavaScript. Any text between a // and the end of a line is treated as a comment and is ignored by JavaScript. // This is a comment. It is similar to comments in C++ Multi-Line comment The following is a multi-line comment in JavaScript. /* * This is a multiline comment in JavaScript * It is very similar to comments in C Programming */
[ { "code": null, "e": 1082, "s": 1062, "text": "Single Line comment" }, { "code": null, "e": 1234, "s": 1082, "text": "The following is a single line comment in JavaScript. Any text between a // and the end of a line is treated as a comment and is ignored by JavaScript." }, { "code": null, "e": 1289, "s": 1234, "text": "// This is a comment. It is similar to comments in C++" }, { "code": null, "e": 1308, "s": 1289, "text": "Multi-Line comment" }, { "code": null, "e": 1361, "s": 1308, "text": "The following is a multi-line comment in JavaScript." }, { "code": null, "e": 1467, "s": 1361, "text": "/*\n * This is a multiline comment in JavaScript\n * It is very similar to comments in C Programming\n*/" } ]
Debugging in R Programming - GeeksforGeeks
10 May, 2020 Debugging is a process of cleaning a program code from bugs to run it successfully. While writing codes, some mistakes or problems automatically appears after the compilation of code and are harder to diagnose. So, fixing it takes a lot of time and after multiple levels of calls. Debugging in R is through warnings, messages, and errors. Debugging in R means debugging functions. Various debugging functions are: Editor breakpoint traceback() browser() recover() Editor Breakpoints can be added in RStudio by clicking to the left of the line in RStudio or pressing Shift+F9 with the cursor on your line. A breakpoint is same as browser() but it doesn’t involve changing codes. Breakpoints are denoted by a red circle on the left side, indicating that debug mode will be entered at this line after the source is run. The traceback() function is used to give all the information on how your function arrived at an error. It will display all the functions called before the error arrived called the “call stack” in many languages, R favors calling traceback. Example: # Function 1function_1 <- function(a){ a + 5} # Function 2function_2 <- function(b) { function_1(b)} # Calling functionfunction_2("s") # Call traceback()traceback() Output: 2: function_1(b) at #1 1: function_2("s") traceback() function displays the error during evaluations. The call stack is read from the function that was run(at the bottom) to the function that was running(at the top). Also we can use traceback() as an error handler which will display error immediately without calling of traceback. # Function 1function_1 <- function(a){ a + 5} # Function 2function_2 <- function(b){ function_1(b)} # Calling error handleroptions(error = traceback)function_2("s") Output: Error in a + 5 : non-numeric argument to binary operator 2: function_1(b) at #1 1: function_2("s") browser() function is inserted into functions to open R interactive debugger. It will stop the execution of function() and you can examine the function with the environment of itself. In debug mode, we can modify objects, look at the objects in the current environment, and also continue executing. Example: browser[1]> command in consoles confirms that you are in debug mode. Some commands to follow: ls(): Objects available in current environment. print(): To evaluate objects. n: To examine the next statement. s: To examine the next statement by stepping into function calls. where: To print a stack trace. c: To leave debugger and continue with execution. C: To exit debugger and go back to R prompt. Also, debug() statement automatically inserts browser() statement at the beginning of the function. recover() statement is used as an error handler and not like the direct statement. In recover(), R prints the whole call stack and lets you select which function browser you would like to enter. Then debugging session starts at the selected location. Example: # Calling recoveroptions(error = recover) # Function 1function_1 <- function(a){ a + 5} # Function 2function_2 <- function(b) { function_1(b)} # Calling functionfunction_2("s") Output: Enter a frame number, or 0 to exit 1: function_2("s") 2: #2: function_1(b) Selection: The debugging session starts at the selected location. Picked R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Change column name of a given DataFrame in R How to Replace specific values in column in R DataFrame ? Adding elements in a vector in R programming - append() method Filter data by multiple conditions in R using Dplyr Loops in R (for, while, repeat) Change Color of Bars in Barchart using ggplot2 in R How to change Row Names of DataFrame in R ? Convert Factor to Numeric and Numeric to Factor in R Programming Remove rows with NA in one column of R DataFrame How to Change Axis Scales in R Plots?
[ { "code": null, "e": 29069, "s": 29041, "text": "\n10 May, 2020" }, { "code": null, "e": 29350, "s": 29069, "text": "Debugging is a process of cleaning a program code from bugs to run it successfully. While writing codes, some mistakes or problems automatically appears after the compilation of code and are harder to diagnose. So, fixing it takes a lot of time and after multiple levels of calls." }, { "code": null, "e": 29483, "s": 29350, "text": "Debugging in R is through warnings, messages, and errors. Debugging in R means debugging functions. Various debugging functions are:" }, { "code": null, "e": 29501, "s": 29483, "text": "Editor breakpoint" }, { "code": null, "e": 29513, "s": 29501, "text": "traceback()" }, { "code": null, "e": 29523, "s": 29513, "text": "browser()" }, { "code": null, "e": 29533, "s": 29523, "text": "recover()" }, { "code": null, "e": 29886, "s": 29533, "text": "Editor Breakpoints can be added in RStudio by clicking to the left of the line in RStudio or pressing Shift+F9 with the cursor on your line. A breakpoint is same as browser() but it doesn’t involve changing codes. Breakpoints are denoted by a red circle on the left side, indicating that debug mode will be entered at this line after the source is run." }, { "code": null, "e": 30126, "s": 29886, "text": "The traceback() function is used to give all the information on how your function arrived at an error. It will display all the functions called before the error arrived called the “call stack” in many languages, R favors calling traceback." }, { "code": null, "e": 30135, "s": 30126, "text": "Example:" }, { "code": "# Function 1function_1 <- function(a){ a + 5} # Function 2function_2 <- function(b) { function_1(b)} # Calling functionfunction_2(\"s\") # Call traceback()traceback()", "e": 30303, "s": 30135, "text": null }, { "code": null, "e": 30311, "s": 30303, "text": "Output:" }, { "code": null, "e": 30354, "s": 30311, "text": "2: function_1(b) at #1\n1: function_2(\"s\")\n" }, { "code": null, "e": 30644, "s": 30354, "text": "traceback() function displays the error during evaluations. The call stack is read from the function that was run(at the bottom) to the function that was running(at the top). Also we can use traceback() as an error handler which will display error immediately without calling of traceback." }, { "code": "# Function 1function_1 <- function(a){ a + 5} # Function 2function_2 <- function(b){ function_1(b)} # Calling error handleroptions(error = traceback)function_2(\"s\")", "e": 30811, "s": 30644, "text": null }, { "code": null, "e": 30819, "s": 30811, "text": "Output:" }, { "code": null, "e": 30919, "s": 30819, "text": "Error in a + 5 : non-numeric argument to binary operator\n2: function_1(b) at #1\n1: function_2(\"s\")\n" }, { "code": null, "e": 31218, "s": 30919, "text": "browser() function is inserted into functions to open R interactive debugger. It will stop the execution of function() and you can examine the function with the environment of itself. In debug mode, we can modify objects, look at the objects in the current environment, and also continue executing." }, { "code": null, "e": 31227, "s": 31218, "text": "Example:" }, { "code": null, "e": 31321, "s": 31227, "text": "browser[1]> command in consoles confirms that you are in debug mode. Some commands to follow:" }, { "code": null, "e": 31369, "s": 31321, "text": "ls(): Objects available in current environment." }, { "code": null, "e": 31399, "s": 31369, "text": "print(): To evaluate objects." }, { "code": null, "e": 31433, "s": 31399, "text": "n: To examine the next statement." }, { "code": null, "e": 31499, "s": 31433, "text": "s: To examine the next statement by stepping into function calls." }, { "code": null, "e": 31530, "s": 31499, "text": "where: To print a stack trace." }, { "code": null, "e": 31580, "s": 31530, "text": "c: To leave debugger and continue with execution." }, { "code": null, "e": 31625, "s": 31580, "text": "C: To exit debugger and go back to R prompt." }, { "code": null, "e": 31725, "s": 31625, "text": "Also, debug() statement automatically inserts browser() statement at the beginning of the function." }, { "code": null, "e": 31976, "s": 31725, "text": "recover() statement is used as an error handler and not like the direct statement. In recover(), R prints the whole call stack and lets you select which function browser you would like to enter. Then debugging session starts at the selected location." }, { "code": null, "e": 31985, "s": 31976, "text": "Example:" }, { "code": "# Calling recoveroptions(error = recover) # Function 1function_1 <- function(a){ a + 5} # Function 2function_2 <- function(b) { function_1(b)} # Calling functionfunction_2(\"s\")", "e": 32165, "s": 31985, "text": null }, { "code": null, "e": 32173, "s": 32165, "text": "Output:" }, { "code": null, "e": 32266, "s": 32173, "text": "Enter a frame number, or 0 to exit \n\n1: function_2(\"s\")\n2: #2: function_1(b)\n\nSelection: \n" }, { "code": null, "e": 32321, "s": 32266, "text": "The debugging session starts at the selected location." }, { "code": null, "e": 32328, "s": 32321, "text": "Picked" }, { "code": null, "e": 32339, "s": 32328, "text": "R Language" }, { "code": null, "e": 32437, "s": 32339, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32446, "s": 32437, "text": "Comments" }, { "code": null, "e": 32459, "s": 32446, "text": "Old Comments" }, { "code": null, "e": 32504, "s": 32459, "text": "Change column name of a given DataFrame in R" }, { "code": null, "e": 32562, "s": 32504, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 32625, "s": 32562, "text": "Adding elements in a vector in R programming - append() method" }, { "code": null, "e": 32677, "s": 32625, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 32709, "s": 32677, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 32761, "s": 32709, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 32805, "s": 32761, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 32870, "s": 32805, "text": "Convert Factor to Numeric and Numeric to Factor in R Programming" }, { "code": null, "e": 32919, "s": 32870, "text": "Remove rows with NA in one column of R DataFrame" } ]
How to generate pyramid of numbers using Python?
There are multiple variations of generating pyramids using numbers in Python. Let's look at the 2 simplest forms for i in range(5): for j in range(i + 1): print(j + 1, end="") print("") This will give the output 1 12 123 1234 12345 You can also print numbers continuously using start = 1 for i in range(5): for j in range(i + 1): print(start, end=" ") start += 1 print("") This will give the output 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 You can also print these numbers in reverse using start = 15 for i in range(5): for j in range(i + 1): print(start, end=" ") start -= 1 print("") This will give the output 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
[ { "code": null, "e": 1175, "s": 1062, "text": "There are multiple variations of generating pyramids using numbers in Python. Let's look at the 2 simplest forms" }, { "code": null, "e": 1260, "s": 1175, "text": "for i in range(5):\n for j in range(i + 1):\n print(j + 1, end=\"\")\n print(\"\")" }, { "code": null, "e": 1286, "s": 1260, "text": "This will give the output" }, { "code": null, "e": 1306, "s": 1286, "text": "1\n12\n123\n1234\n12345" }, { "code": null, "e": 1352, "s": 1306, "text": "You can also print numbers continuously using" }, { "code": null, "e": 1462, "s": 1352, "text": "start = 1\nfor i in range(5):\n for j in range(i + 1):\n print(start, end=\" \")\n start += 1\nprint(\"\")" }, { "code": null, "e": 1488, "s": 1462, "text": "This will give the output" }, { "code": null, "e": 1524, "s": 1488, "text": "1\n2 3\n4 5 6\n7 8 9 10\n11 12 13 14 15" }, { "code": null, "e": 1574, "s": 1524, "text": "You can also print these numbers in reverse using" }, { "code": null, "e": 1679, "s": 1574, "text": "start = 15\nfor i in range(5):\n for j in range(i + 1):\n print(start, end=\" \")\n start -= 1\nprint(\"\")" }, { "code": null, "e": 1705, "s": 1679, "text": "This will give the output" }, { "code": null, "e": 1741, "s": 1705, "text": "15\n14 13\n12 11 10\n9 8 7 6\n5 4 3 2 1" } ]
How to assign same value to multiple variables in single statement in C#?
To assign same value to multiple variables in a single line, use the = operator − val1 = val2 = 20; The above statement assigns 20 to the variables val1 and val2 as shown in the following code − Live Demo using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Demo { class MyApplication { static void Main(string[] args) { int val1, val2; val1 = val2 = 20; Console.WriteLine("Value1 = "+val1); Console.WriteLine("Value2 = "+val2); } } } Value1 = 20 Value2 = 20
[ { "code": null, "e": 1144, "s": 1062, "text": "To assign same value to multiple variables in a single line, use the = operator −" }, { "code": null, "e": 1162, "s": 1144, "text": "val1 = val2 = 20;" }, { "code": null, "e": 1257, "s": 1162, "text": "The above statement assigns 20 to the variables val1 and val2 as shown in the following code −" }, { "code": null, "e": 1268, "s": 1257, "text": " Live Demo" }, { "code": null, "e": 1596, "s": 1268, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace Demo {\n class MyApplication {\n static void Main(string[] args) {\n int val1, val2;\n val1 = val2 = 20;\n Console.WriteLine(\"Value1 = \"+val1);\n Console.WriteLine(\"Value2 = \"+val2);\n }\n }\n}" }, { "code": null, "e": 1620, "s": 1596, "text": "Value1 = 20\nValue2 = 20" } ]
7 Tips To Increase Your Productivity in Python | by Bharath K | Towards Data Science
Python is a fantastic programming language for almost all programmers of any skill level. Python is one of the most popular language choices in the modern generation, and it will probably remain so for the upcoming decade. In this article, we will focus on 7 essential tips that will help us to improve our overall productivity with Python as well as achieve better results while using this fabulous programming language. The seven tips are a combination of both technical and practical points of implementation. The main topic of the article assumes at least a brief introductory understanding of the Python language. If you have a decent grasp of the programming language, you can feel free to skip ahead to the tips section of the article. However, if you are still new to Python and want to briefly learn more about it, then refer to the next couple of sections to understand what is Python and why exactly we make use of this programming language. What is Python? Python is an object-oriented, high-level programming language that was released way back in 1991. Python is highly interpretable and efficient. Python is versatile, and thanks to its resourcefulness, it is a suitable fit for Data Science. I initially started with languages like C, C++, and Java. When I finally encountered Python, I found it to be quite elegant, simple to learn, and easy to use. Python is the best way for anyone, even people with no prior experience with programming or coding languages, to get started with machine learning. Despite having some flaws, like being considered a “slow” language, Python is still one of the best languages for AI and machine learning. Although there are a variety of other languages such as Julia, Golang, etc., which might be quite competitive against Python in the future years, the latter remains the better choice at this point. Why Python? The main reasons for the popularity of Python for Data Science and Artificial Intelligence, alongside various other applications, despite other languages like Java, JavaScript, R, etc., is as follows — As mentioned previously, Python is a simple language and is overall consistent.The rapid increase in popularity in comparison to other programming languages makes it a suitable pick for beginner-level programmers.Has extensive resources concerning a wide range of libraries and frameworks for supporting Data Science.Versatility and platform independence, which means Python can import essential modules built in other programming languages as well.It has a great community with continuous updates. The Python community, in general, is filled with amazing people, with constant updates made to improve Python. As mentioned previously, Python is a simple language and is overall consistent. The rapid increase in popularity in comparison to other programming languages makes it a suitable pick for beginner-level programmers. Has extensive resources concerning a wide range of libraries and frameworks for supporting Data Science. Versatility and platform independence, which means Python can import essential modules built in other programming languages as well. It has a great community with continuous updates. The Python community, in general, is filled with amazing people, with constant updates made to improve Python. To get started with Python, you can download it from here. With that simple introduction out of the way, let us understand the seven essential tips to improve your overall coding and achieve better results in the Python programming language. An Integrated Development Environment (IDE) is a software application that provides comprehensive facilities to computer programmers for software development. An IDE normally consists of at least a source code editor, build automation tools and a debugger. I strongly believe that beginners to Python should use either the Python IDLE or an editor like the Sublime Text 3 without any additional installations. This method helps to achieve a better understanding of the python programming language as you tend to make more mistakes, you have to work hard to figure out on your own what these blunders exactly are. However, when you become more of an expert in Python, want to start achieving faster typing and better results, using an IDE for this purpose poses no harm. In the hindsight, it can be extremely useful to use an IDE for performing and solving complex problem statements in Python. It is also beneficial for building more advanced Python projects as well. Since python is a popular language of the modern era, it has a wide array of the development software available such as Pycharm, visual studio code, Jupyter notebooks, etc. These are three main editors that I use on a regular basis. The main reason for this is because Pycharm is specifically developed for Python it has every extensive feature and additional support that you desire. These include code completion, code inspections, error-highlighting, and fixes, debugging, version control system and code refactoring. The Jupyter Notebook is an open-source web application that allows you to create and share documents that contain live code, equations, visualizations and narrative text. Uses include: data cleaning and transformation, numerical simulation, statistical modeling, data visualization, machine learning, and much more. The Jupyter Notebook is an absolutely fantastic option to get started with data science and machine learning. These Notebooks can be shared with anyone and helps to collaborate code more efficiently and effectively. I would highly recommend using the Jupyter Notebook as well because you can use each code block separately and you also have the option to use markdowns. It is widely used in lots of profitable companies. Visual Studio Code is a free source-code editor made by Microsoft for Windows, Linux, and macOS. Features include support for debugging, syntax highlighting, intelligent code completion, snippets, code refactoring, and embedded Git. It supports various programming languages including python. You might need a few additional installations to get started with Python but it is quite simple. It has continuous updates and is one of the best platforms for Python and other programming languages. I use this a lot and would highly recommend it as well. To have a more in-depth understanding of the various Integrated Development Environments that you can use for programming your Python projects, I would highly recommend all of you to check out my article on a concise list of more than Ten such editor options available from the following link provided below. towardsdatascience.com Lists are a type of data structures and can be used effectively to solve a variety of complex structures. Before moving further ahead, let us understand what data structures and lists are in more detail. Data Structures are a collection of data elements that are structured in some way. Data Structures are the core of any programming language, and this holds true for python as well. There are many built-in data structures in python. A list is a mutable ordered sequence of elements. Mutable means that the list can be modified or changed. Lists are enclosed within Square Brackets ‘[ ]’. Lists are a type of sequenced data structure with each element in the list being assigned a specific index number by which it can be accessed. Each item or element in a list is separated by a comma. (,) Solving a variety of tasks with the help of lists and its wide range of function choices available is a suitable choice for most problems. However, you should highly considering using the procedure of list comprehensions to improve productivity and achieve better results. List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition. To understand the concept of list comprehensions with the help of a simple example, let us consider the below code block. In the above code block, the list with the name “squares” was created. Using an iterative “for” loop and the append function, we were able to calculate the squares of the numbers ranging from one to ten. However, the same problem can be solved in a single line with the help of list comprehensions as shown below. The above code block shows the representation of how a list comprehension can simplify a code of a few lines to just a single line while getting the exact same output faster. The only issue with list comprehensions is sometimes it could be hard for the reader to understand the code. By using the approach of nested list comprehensions, you can also solve more complex tasks. Overall, list comprehensions prove to be extremely useful for solving tasks and computations while consuming lesser space and time complexities for general problems. Refer to my article on Mastering Lists with Python from the following link provided below for a more concise and detailed understanding of this topic discussed. towardsdatascience.com Let us briefly understand what classes and functions exactly are in a bit more detail, and then we can dive into why making better use of these can yield better productive results. Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. Each class instance can have attributes attached to it for maintaining its state. Class instances can also have methods (defined by its class) for modifying its state. Compared with other programming languages, Python’s class mechanism adds classes with a minimum of new syntax and semantics. It is a mixture of the class mechanisms found in C++ and Modula-3. Python classes provide all the standard features of Object Oriented Programming: the class inheritance mechanism allows multiple base classes, a derived class can override any methods of its base class or classes, and a method can call the method of a base class with the same name. Objects can contain arbitrary amounts and kinds of data. As is true for modules, classes partake of the dynamic nature of Python: they are created at runtime, and can be modified further after creation. Functions are a block of code that is written in a program so that they can be recalled multiple times. The main utility of a function is so that it can be repeatedly called numerous times in the same program, and you don’t need to write the same codes over and over again. However, you can also use it to provide more structure and an overall better look to your programs. Functions are defined using the keyword ‘def,’ which can be called with defined or undefined parameters. When you call the particular the particular function, then whatever the value is to be returned is interpreted by the python compiler. Scope of a variable is the portion of a program where the variable is recognized. Parameters and variables defined inside a function are not visible from outside the function. Hence, they have a local scope. The lifetime of a variable is the period throughout which the variable exits in the memory. The lifetime of variables inside a function is as long as the function executes. They are destroyed once we return from the function. Hence, a function does not remember the value of a variable from its previous calls. Classes are a mechanism to organize your code into generic, reusable pieces of code. At their best they are reusable code snippets that will be used over and over again with little or no modification. The class concept was inspired by biological collections of features (attributes) and abilities (methods). Functions are great to use when data is critical to the work being done. Classes are great when you need to represent a collection of attributes and methods that will be used repeatedly in other places. Generally, if you end up writing functions inside of functions you should consider writing a class instead. If you only have only one function in a class then better stick with just writing a function. A good reason to move from functions to classes in your programming is to write classes using composition over inheritance. To learn more information on each of these topics, I would highly recommend checking out the official documentation of Python, which explains all of these concepts in further detail. The best part about working with any programming language is the eventual errors that you will encounter. When you run into these bugs, you could easily decipher if it is a silly blunder, or you can end up having a hard time finding out your mistake. However, to solve an error that you have no clue why it occurred and researching in detail on how to fix the following bug that you just encountered, can be a complicated task. The best approach to dealing with these types of bugs is to make use of the browser and search engine of your preferred choice. By searching for the solutions to the error that you need to fix, there is a high chance you will be able to solve it. The internet is a wonderful place, and websites like Stack overflow, Data stack exchange, and GitHub, are some of the most popular sites to receive in-depth solutions and answers to the problems or errors that you are encountering with the running or installation of your program or the respective code blocks. To be able to decode the error on your own by constant effort is one of the greatest feelings ever. And for helping you to achieve this task successfully your web browser and search engine are some of the best tools at your disposal. Hence, it is essential to utilize these tools effectively to improve your overall productivity in Python. In Python, an anonymous function is a function that is defined without a name. While normal functions are defined using the def keyword in Python, anonymous functions are defined using the lambda keyword. Hence, anonymous functions are sometimes also referred to as lambda functions, and they are often used interchangeably. The syntax for the function is as follows: lambda arguments: expression The main advantage of using the lambda function is executing a lambda function that evaluates its expression and then automatically returns its result. So there’s always an implicit return statement. That’s why some people refer to lambdas as single expression functions. It is very useful in most scenarios to simplify code and is an integral part of the programming language. Most times, lambda functions are good, but the times you should consider not using them is if utilizing these functions make the single line code longer than anticipated, and it becomes hard for the user to read. Basically, you should consider not to use lambda functions when the readability of your code decreases. For a more detailed explanation on this topic with more concise codes and details, I would highly recommend the viewers to check out the following article on advanced functions in Python from the following link provided below. towardsdatascience.com It is not uncommon in programming to get stuck on a problem that you are working on for a long time. The best part is python as mentioned earlier is that is has a brilliant community with very helpful people and lots of resources at your disposal for your benefit. Effective interaction is a key concept for most things in life and also in most jobs as well. Especially in the field of programming, communication skills play a key role. To perform a complex project efficiently while coordinating and communicating effectively is a must requirement for every python programmer. Stack Overflow, discord channels, YouTube videos, free online code camps, GitHub, towards data science, etc. are all helpful resources that are available for all of us to utilize and improve our skills. I thought it was best to find all the solutions to these problems on my own. I considered this was the best practice for a long time, and that is only partially right. Sometimes you may have misunderstood a concept or aren’t doing something perfectly alright. After trying by yourself, if you still have confusion, it is a good practice to ask your friends or experts who can help you out! Communication with other people and experts while sharing ideas is a great way to learn more. Not effectively communicating can lead to quite a few issues like misleading understandings in queries you might have about a particular topic. Also, talking to people is extremely helpful to share your views, as well as gain knowledge. By talking to more people, you develop better ideas and most importantly interactivity, which will be very useful while working in a company with a team on data science projects. The interesting part about python is the wide array of options it offers you. Also, the best part is, with each mistake you make, you learn something new and what you did wrong, provided you find a solution by looking it up on the internet or cracking it by yourself. This feeling makes the overall experience even more satisfactory. There are tons of practical projects and ideas available to implement. Just pick one project of your choice and start working on it. Doing more projects is the best way to keep learning! Find more projects and continuously upgrade your skills! Practice becomes significantly to keep yourself updated with all the latest trends and process the on-going techniques in this tremendous subject. There is a lot of scope in every aspect with continuous developments. So, keep coding and keep working on practical implementations! Try to actively participate in competitions on websites. Kaggle is one such site that hosts some of the best data science, related competitions. Don’t worry about which place you finish. It does not matter much as long as you learn something new. As discussed earlier, there are a lot of websites to improve your coding as well as participate in competitions like HackerRank, which you should consider. Involving in the community is helpful to consistently learn more from fellow data science enthusiasts. Every model you construct and every project you complete in data science has a lot of room for improvement. It is always a good practice to consider alternatives and various other methods or improvements that you can make to achieve better results. So, Keep Practicing! In this article, we have discussed about the seven tips, which are in my opinion, some of the best ways to achieve better results with the Python programming language. I hope the tips discussed in this article will help you in improving your code. From my experience, the tips suggested in this article are extremely useful in achieving better overall results and also help in improving your productivity in performing tasks at a high-level to obtain the necessary solutions. The most significant aspect of any programming language is to keep continuously creating new projects, building your profile or resume, and practice on a daily basis to stay in touch with the various concepts of the language. If you have any queries about the topic addressed in this article, then please feel free to let me in the comments below, and I will try to reply back as soon as possible. Check out some of my other articles that you might enjoy reading! towardsdatascience.com towardsdatascience.com towardsdatascience.com towardsdatascience.com towardsdatascience.com Thank you all for sticking on till the end. I hope you guys enjoyed reading this article. I wish you all have a wonderful day ahead!
[ { "code": null, "e": 395, "s": 172, "text": "Python is a fantastic programming language for almost all programmers of any skill level. Python is one of the most popular language choices in the modern generation, and it will probably remain so for the upcoming decade." }, { "code": null, "e": 685, "s": 395, "text": "In this article, we will focus on 7 essential tips that will help us to improve our overall productivity with Python as well as achieve better results while using this fabulous programming language. The seven tips are a combination of both technical and practical points of implementation." }, { "code": null, "e": 915, "s": 685, "text": "The main topic of the article assumes at least a brief introductory understanding of the Python language. If you have a decent grasp of the programming language, you can feel free to skip ahead to the tips section of the article." }, { "code": null, "e": 1125, "s": 915, "text": "However, if you are still new to Python and want to briefly learn more about it, then refer to the next couple of sections to understand what is Python and why exactly we make use of this programming language." }, { "code": null, "e": 1141, "s": 1125, "text": "What is Python?" }, { "code": null, "e": 1539, "s": 1141, "text": "Python is an object-oriented, high-level programming language that was released way back in 1991. Python is highly interpretable and efficient. Python is versatile, and thanks to its resourcefulness, it is a suitable fit for Data Science. I initially started with languages like C, C++, and Java. When I finally encountered Python, I found it to be quite elegant, simple to learn, and easy to use." }, { "code": null, "e": 1826, "s": 1539, "text": "Python is the best way for anyone, even people with no prior experience with programming or coding languages, to get started with machine learning. Despite having some flaws, like being considered a “slow” language, Python is still one of the best languages for AI and machine learning." }, { "code": null, "e": 2024, "s": 1826, "text": "Although there are a variety of other languages such as Julia, Golang, etc., which might be quite competitive against Python in the future years, the latter remains the better choice at this point." }, { "code": null, "e": 2036, "s": 2024, "text": "Why Python?" }, { "code": null, "e": 2238, "s": 2036, "text": "The main reasons for the popularity of Python for Data Science and Artificial Intelligence, alongside various other applications, despite other languages like Java, JavaScript, R, etc., is as follows —" }, { "code": null, "e": 2848, "s": 2238, "text": "As mentioned previously, Python is a simple language and is overall consistent.The rapid increase in popularity in comparison to other programming languages makes it a suitable pick for beginner-level programmers.Has extensive resources concerning a wide range of libraries and frameworks for supporting Data Science.Versatility and platform independence, which means Python can import essential modules built in other programming languages as well.It has a great community with continuous updates. The Python community, in general, is filled with amazing people, with constant updates made to improve Python." }, { "code": null, "e": 2928, "s": 2848, "text": "As mentioned previously, Python is a simple language and is overall consistent." }, { "code": null, "e": 3063, "s": 2928, "text": "The rapid increase in popularity in comparison to other programming languages makes it a suitable pick for beginner-level programmers." }, { "code": null, "e": 3168, "s": 3063, "text": "Has extensive resources concerning a wide range of libraries and frameworks for supporting Data Science." }, { "code": null, "e": 3301, "s": 3168, "text": "Versatility and platform independence, which means Python can import essential modules built in other programming languages as well." }, { "code": null, "e": 3462, "s": 3301, "text": "It has a great community with continuous updates. The Python community, in general, is filled with amazing people, with constant updates made to improve Python." }, { "code": null, "e": 3521, "s": 3462, "text": "To get started with Python, you can download it from here." }, { "code": null, "e": 3704, "s": 3521, "text": "With that simple introduction out of the way, let us understand the seven essential tips to improve your overall coding and achieve better results in the Python programming language." }, { "code": null, "e": 3961, "s": 3704, "text": "An Integrated Development Environment (IDE) is a software application that provides comprehensive facilities to computer programmers for software development. An IDE normally consists of at least a source code editor, build automation tools and a debugger." }, { "code": null, "e": 4317, "s": 3961, "text": "I strongly believe that beginners to Python should use either the Python IDLE or an editor like the Sublime Text 3 without any additional installations. This method helps to achieve a better understanding of the python programming language as you tend to make more mistakes, you have to work hard to figure out on your own what these blunders exactly are." }, { "code": null, "e": 4672, "s": 4317, "text": "However, when you become more of an expert in Python, want to start achieving faster typing and better results, using an IDE for this purpose poses no harm. In the hindsight, it can be extremely useful to use an IDE for performing and solving complex problem statements in Python. It is also beneficial for building more advanced Python projects as well." }, { "code": null, "e": 4905, "s": 4672, "text": "Since python is a popular language of the modern era, it has a wide array of the development software available such as Pycharm, visual studio code, Jupyter notebooks, etc. These are three main editors that I use on a regular basis." }, { "code": null, "e": 5193, "s": 4905, "text": "The main reason for this is because Pycharm is specifically developed for Python it has every extensive feature and additional support that you desire. These include code completion, code inspections, error-highlighting, and fixes, debugging, version control system and code refactoring." }, { "code": null, "e": 5619, "s": 5193, "text": "The Jupyter Notebook is an open-source web application that allows you to create and share documents that contain live code, equations, visualizations and narrative text. Uses include: data cleaning and transformation, numerical simulation, statistical modeling, data visualization, machine learning, and much more. The Jupyter Notebook is an absolutely fantastic option to get started with data science and machine learning." }, { "code": null, "e": 5930, "s": 5619, "text": "These Notebooks can be shared with anyone and helps to collaborate code more efficiently and effectively. I would highly recommend using the Jupyter Notebook as well because you can use each code block separately and you also have the option to use markdowns. It is widely used in lots of profitable companies." }, { "code": null, "e": 6163, "s": 5930, "text": "Visual Studio Code is a free source-code editor made by Microsoft for Windows, Linux, and macOS. Features include support for debugging, syntax highlighting, intelligent code completion, snippets, code refactoring, and embedded Git." }, { "code": null, "e": 6479, "s": 6163, "text": "It supports various programming languages including python. You might need a few additional installations to get started with Python but it is quite simple. It has continuous updates and is one of the best platforms for Python and other programming languages. I use this a lot and would highly recommend it as well." }, { "code": null, "e": 6788, "s": 6479, "text": "To have a more in-depth understanding of the various Integrated Development Environments that you can use for programming your Python projects, I would highly recommend all of you to check out my article on a concise list of more than Ten such editor options available from the following link provided below." }, { "code": null, "e": 6811, "s": 6788, "text": "towardsdatascience.com" }, { "code": null, "e": 7015, "s": 6811, "text": "Lists are a type of data structures and can be used effectively to solve a variety of complex structures. Before moving further ahead, let us understand what data structures and lists are in more detail." }, { "code": null, "e": 7247, "s": 7015, "text": "Data Structures are a collection of data elements that are structured in some way. Data Structures are the core of any programming language, and this holds true for python as well. There are many built-in data structures in python." }, { "code": null, "e": 7605, "s": 7247, "text": "A list is a mutable ordered sequence of elements. Mutable means that the list can be modified or changed. Lists are enclosed within Square Brackets ‘[ ]’. Lists are a type of sequenced data structure with each element in the list being assigned a specific index number by which it can be accessed. Each item or element in a list is separated by a comma. (,)" }, { "code": null, "e": 7878, "s": 7605, "text": "Solving a variety of tasks with the help of lists and its wide range of function choices available is a suitable choice for most problems. However, you should highly considering using the procedure of list comprehensions to improve productivity and achieve better results." }, { "code": null, "e": 8166, "s": 7878, "text": "List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition." }, { "code": null, "e": 8288, "s": 8166, "text": "To understand the concept of list comprehensions with the help of a simple example, let us consider the below code block." }, { "code": null, "e": 8602, "s": 8288, "text": "In the above code block, the list with the name “squares” was created. Using an iterative “for” loop and the append function, we were able to calculate the squares of the numbers ranging from one to ten. However, the same problem can be solved in a single line with the help of list comprehensions as shown below." }, { "code": null, "e": 8886, "s": 8602, "text": "The above code block shows the representation of how a list comprehension can simplify a code of a few lines to just a single line while getting the exact same output faster. The only issue with list comprehensions is sometimes it could be hard for the reader to understand the code." }, { "code": null, "e": 9144, "s": 8886, "text": "By using the approach of nested list comprehensions, you can also solve more complex tasks. Overall, list comprehensions prove to be extremely useful for solving tasks and computations while consuming lesser space and time complexities for general problems." }, { "code": null, "e": 9305, "s": 9144, "text": "Refer to my article on Mastering Lists with Python from the following link provided below for a more concise and detailed understanding of this topic discussed." }, { "code": null, "e": 9328, "s": 9305, "text": "towardsdatascience.com" }, { "code": null, "e": 9509, "s": 9328, "text": "Let us briefly understand what classes and functions exactly are in a bit more detail, and then we can dive into why making better use of these can yield better productive results." }, { "code": null, "e": 9845, "s": 9509, "text": "Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. Each class instance can have attributes attached to it for maintaining its state. Class instances can also have methods (defined by its class) for modifying its state." }, { "code": null, "e": 10037, "s": 9845, "text": "Compared with other programming languages, Python’s class mechanism adds classes with a minimum of new syntax and semantics. It is a mixture of the class mechanisms found in C++ and Modula-3." }, { "code": null, "e": 10320, "s": 10037, "text": "Python classes provide all the standard features of Object Oriented Programming: the class inheritance mechanism allows multiple base classes, a derived class can override any methods of its base class or classes, and a method can call the method of a base class with the same name." }, { "code": null, "e": 10523, "s": 10320, "text": "Objects can contain arbitrary amounts and kinds of data. As is true for modules, classes partake of the dynamic nature of Python: they are created at runtime, and can be modified further after creation." }, { "code": null, "e": 10897, "s": 10523, "text": "Functions are a block of code that is written in a program so that they can be recalled multiple times. The main utility of a function is so that it can be repeatedly called numerous times in the same program, and you don’t need to write the same codes over and over again. However, you can also use it to provide more structure and an overall better look to your programs." }, { "code": null, "e": 11137, "s": 10897, "text": "Functions are defined using the keyword ‘def,’ which can be called with defined or undefined parameters. When you call the particular the particular function, then whatever the value is to be returned is interpreted by the python compiler." }, { "code": null, "e": 11345, "s": 11137, "text": "Scope of a variable is the portion of a program where the variable is recognized. Parameters and variables defined inside a function are not visible from outside the function. Hence, they have a local scope." }, { "code": null, "e": 11656, "s": 11345, "text": "The lifetime of a variable is the period throughout which the variable exits in the memory. The lifetime of variables inside a function is as long as the function executes. They are destroyed once we return from the function. Hence, a function does not remember the value of a variable from its previous calls." }, { "code": null, "e": 11964, "s": 11656, "text": "Classes are a mechanism to organize your code into generic, reusable pieces of code. At their best they are reusable code snippets that will be used over and over again with little or no modification. The class concept was inspired by biological collections of features (attributes) and abilities (methods)." }, { "code": null, "e": 12167, "s": 11964, "text": "Functions are great to use when data is critical to the work being done. Classes are great when you need to represent a collection of attributes and methods that will be used repeatedly in other places." }, { "code": null, "e": 12493, "s": 12167, "text": "Generally, if you end up writing functions inside of functions you should consider writing a class instead. If you only have only one function in a class then better stick with just writing a function. A good reason to move from functions to classes in your programming is to write classes using composition over inheritance." }, { "code": null, "e": 12676, "s": 12493, "text": "To learn more information on each of these topics, I would highly recommend checking out the official documentation of Python, which explains all of these concepts in further detail." }, { "code": null, "e": 12927, "s": 12676, "text": "The best part about working with any programming language is the eventual errors that you will encounter. When you run into these bugs, you could easily decipher if it is a silly blunder, or you can end up having a hard time finding out your mistake." }, { "code": null, "e": 13104, "s": 12927, "text": "However, to solve an error that you have no clue why it occurred and researching in detail on how to fix the following bug that you just encountered, can be a complicated task." }, { "code": null, "e": 13351, "s": 13104, "text": "The best approach to dealing with these types of bugs is to make use of the browser and search engine of your preferred choice. By searching for the solutions to the error that you need to fix, there is a high chance you will be able to solve it." }, { "code": null, "e": 13662, "s": 13351, "text": "The internet is a wonderful place, and websites like Stack overflow, Data stack exchange, and GitHub, are some of the most popular sites to receive in-depth solutions and answers to the problems or errors that you are encountering with the running or installation of your program or the respective code blocks." }, { "code": null, "e": 14002, "s": 13662, "text": "To be able to decode the error on your own by constant effort is one of the greatest feelings ever. And for helping you to achieve this task successfully your web browser and search engine are some of the best tools at your disposal. Hence, it is essential to utilize these tools effectively to improve your overall productivity in Python." }, { "code": null, "e": 14207, "s": 14002, "text": "In Python, an anonymous function is a function that is defined without a name. While normal functions are defined using the def keyword in Python, anonymous functions are defined using the lambda keyword." }, { "code": null, "e": 14370, "s": 14207, "text": "Hence, anonymous functions are sometimes also referred to as lambda functions, and they are often used interchangeably. The syntax for the function is as follows:" }, { "code": null, "e": 14399, "s": 14370, "text": "lambda arguments: expression" }, { "code": null, "e": 14599, "s": 14399, "text": "The main advantage of using the lambda function is executing a lambda function that evaluates its expression and then automatically returns its result. So there’s always an implicit return statement." }, { "code": null, "e": 14777, "s": 14599, "text": "That’s why some people refer to lambdas as single expression functions. It is very useful in most scenarios to simplify code and is an integral part of the programming language." }, { "code": null, "e": 15094, "s": 14777, "text": "Most times, lambda functions are good, but the times you should consider not using them is if utilizing these functions make the single line code longer than anticipated, and it becomes hard for the user to read. Basically, you should consider not to use lambda functions when the readability of your code decreases." }, { "code": null, "e": 15321, "s": 15094, "text": "For a more detailed explanation on this topic with more concise codes and details, I would highly recommend the viewers to check out the following article on advanced functions in Python from the following link provided below." }, { "code": null, "e": 15344, "s": 15321, "text": "towardsdatascience.com" }, { "code": null, "e": 15609, "s": 15344, "text": "It is not uncommon in programming to get stuck on a problem that you are working on for a long time. The best part is python as mentioned earlier is that is has a brilliant community with very helpful people and lots of resources at your disposal for your benefit." }, { "code": null, "e": 15922, "s": 15609, "text": "Effective interaction is a key concept for most things in life and also in most jobs as well. Especially in the field of programming, communication skills play a key role. To perform a complex project efficiently while coordinating and communicating effectively is a must requirement for every python programmer." }, { "code": null, "e": 16125, "s": 15922, "text": "Stack Overflow, discord channels, YouTube videos, free online code camps, GitHub, towards data science, etc. are all helpful resources that are available for all of us to utilize and improve our skills." }, { "code": null, "e": 16515, "s": 16125, "text": "I thought it was best to find all the solutions to these problems on my own. I considered this was the best practice for a long time, and that is only partially right. Sometimes you may have misunderstood a concept or aren’t doing something perfectly alright. After trying by yourself, if you still have confusion, it is a good practice to ask your friends or experts who can help you out!" }, { "code": null, "e": 16753, "s": 16515, "text": "Communication with other people and experts while sharing ideas is a great way to learn more. Not effectively communicating can lead to quite a few issues like misleading understandings in queries you might have about a particular topic." }, { "code": null, "e": 17025, "s": 16753, "text": "Also, talking to people is extremely helpful to share your views, as well as gain knowledge. By talking to more people, you develop better ideas and most importantly interactivity, which will be very useful while working in a company with a team on data science projects." }, { "code": null, "e": 17359, "s": 17025, "text": "The interesting part about python is the wide array of options it offers you. Also, the best part is, with each mistake you make, you learn something new and what you did wrong, provided you find a solution by looking it up on the internet or cracking it by yourself. This feeling makes the overall experience even more satisfactory." }, { "code": null, "e": 17603, "s": 17359, "text": "There are tons of practical projects and ideas available to implement. Just pick one project of your choice and start working on it. Doing more projects is the best way to keep learning! Find more projects and continuously upgrade your skills!" }, { "code": null, "e": 17883, "s": 17603, "text": "Practice becomes significantly to keep yourself updated with all the latest trends and process the on-going techniques in this tremendous subject. There is a lot of scope in every aspect with continuous developments. So, keep coding and keep working on practical implementations!" }, { "code": null, "e": 18130, "s": 17883, "text": "Try to actively participate in competitions on websites. Kaggle is one such site that hosts some of the best data science, related competitions. Don’t worry about which place you finish. It does not matter much as long as you learn something new." }, { "code": null, "e": 18389, "s": 18130, "text": "As discussed earlier, there are a lot of websites to improve your coding as well as participate in competitions like HackerRank, which you should consider. Involving in the community is helpful to consistently learn more from fellow data science enthusiasts." }, { "code": null, "e": 18638, "s": 18389, "text": "Every model you construct and every project you complete in data science has a lot of room for improvement. It is always a good practice to consider alternatives and various other methods or improvements that you can make to achieve better results." }, { "code": null, "e": 18659, "s": 18638, "text": "So, Keep Practicing!" }, { "code": null, "e": 18907, "s": 18659, "text": "In this article, we have discussed about the seven tips, which are in my opinion, some of the best ways to achieve better results with the Python programming language. I hope the tips discussed in this article will help you in improving your code." }, { "code": null, "e": 19135, "s": 18907, "text": "From my experience, the tips suggested in this article are extremely useful in achieving better overall results and also help in improving your productivity in performing tasks at a high-level to obtain the necessary solutions." }, { "code": null, "e": 19361, "s": 19135, "text": "The most significant aspect of any programming language is to keep continuously creating new projects, building your profile or resume, and practice on a daily basis to stay in touch with the various concepts of the language." }, { "code": null, "e": 19533, "s": 19361, "text": "If you have any queries about the topic addressed in this article, then please feel free to let me in the comments below, and I will try to reply back as soon as possible." }, { "code": null, "e": 19599, "s": 19533, "text": "Check out some of my other articles that you might enjoy reading!" }, { "code": null, "e": 19622, "s": 19599, "text": "towardsdatascience.com" }, { "code": null, "e": 19645, "s": 19622, "text": "towardsdatascience.com" }, { "code": null, "e": 19668, "s": 19645, "text": "towardsdatascience.com" }, { "code": null, "e": 19691, "s": 19668, "text": "towardsdatascience.com" }, { "code": null, "e": 19714, "s": 19691, "text": "towardsdatascience.com" } ]
Virtual Functions in C++ - GeeksQuiz
10 Jul, 2021 In Base In Base In Base In Derived In Derived In Derived In Derived In Base In Base In Base In Base In Derived In Derived In Derived In Derived In Base // Not good code as destructor is not virtual #include<iostream> using namespace std; class Base { public: Base() { cout << "Constructor: Base" << endl; } ~Base() { cout << "Destructor : Base" << endl; } }; class Derived: public Base { public: Derived() { cout << "Constructor: Derived" << endl; } ~Derived() { cout << "Destructor : Derived" << endl; } }; int main() { Base *Var = new Derived(); delete Var; return 0; } Output on GCC: Constructor: Base Constructor: Derived Destructor : Base Constructor: Base Constructor: Derived Destructor : Derived Destructor : Base Constructor: Base Constructor: Derived Destructor : Base Constructor: Base Constructor: Derived Destructor : Derived Constructor: Derived Destructor : Derived Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Must Do Coding Questions for Product Based Companies Microsoft Interview Experience for Internship (Via Engage) Difference between var, let and const keywords in JavaScript Array of Objects in C++ with Examples How to Replace Values in Column Based on Condition in Pandas? How to Fix: SyntaxError: positional argument follows keyword argument in Python C Program to read contents of Whole File Insert Image in a Jupyter Notebook How to Replace Values in a List in Python? How to Read Text Files with Pandas?
[ { "code": null, "e": 27219, "s": 27191, "text": "\n10 Jul, 2021" }, { "code": null, "e": 27237, "s": 27219, "text": "In Base \nIn Base " }, { "code": null, "e": 27257, "s": 27237, "text": "In Base \nIn Derived" }, { "code": null, "e": 27279, "s": 27257, "text": "In Derived\nIn Derived" }, { "code": null, "e": 27299, "s": 27279, "text": "In Derived\nIn Base " }, { "code": null, "e": 27318, "s": 27299, "text": "In Base \nIn Base \n" }, { "code": null, "e": 27339, "s": 27318, "text": "In Base \nIn Derived\n" }, { "code": null, "e": 27362, "s": 27339, "text": "In Derived\nIn Derived\n" }, { "code": null, "e": 27383, "s": 27362, "text": "In Derived\nIn Base \n" }, { "code": null, "e": 27919, "s": 27383, "text": "// Not good code as destructor is not virtual\n#include<iostream>\nusing namespace std;\n\nclass Base {\npublic:\n Base() { cout << \"Constructor: Base\" << endl; }\n ~Base() { cout << \"Destructor : Base\" << endl; }\n};\n\nclass Derived: public Base {\npublic:\n Derived() { cout << \"Constructor: Derived\" << endl; }\n ~Derived() { cout << \"Destructor : Derived\" << endl; }\n};\n\nint main() {\n Base *Var = new Derived();\n delete Var;\n return 0;\n}\n\nOutput on GCC:\nConstructor: Base\nConstructor: Derived\nDestructor : Base\n" }, { "code": null, "e": 27997, "s": 27919, "text": "Constructor: Base\nConstructor: Derived\nDestructor : Derived\nDestructor : Base" }, { "code": null, "e": 28054, "s": 27997, "text": "Constructor: Base\nConstructor: Derived\nDestructor : Base" }, { "code": null, "e": 28114, "s": 28054, "text": "Constructor: Base\nConstructor: Derived\nDestructor : Derived" }, { "code": null, "e": 28156, "s": 28114, "text": "Constructor: Derived\nDestructor : Derived" }, { "code": null, "e": 28254, "s": 28156, "text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here." }, { "code": null, "e": 28263, "s": 28254, "text": "Comments" }, { "code": null, "e": 28276, "s": 28263, "text": "Old Comments" }, { "code": null, "e": 28329, "s": 28276, "text": "Must Do Coding Questions for Product Based Companies" }, { "code": null, "e": 28388, "s": 28329, "text": "Microsoft Interview Experience for Internship (Via Engage)" }, { "code": null, "e": 28449, "s": 28388, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28487, "s": 28449, "text": "Array of Objects in C++ with Examples" }, { "code": null, "e": 28549, "s": 28487, "text": "How to Replace Values in Column Based on Condition in Pandas?" }, { "code": null, "e": 28629, "s": 28549, "text": "How to Fix: SyntaxError: positional argument follows keyword argument in Python" }, { "code": null, "e": 28670, "s": 28629, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 28705, "s": 28670, "text": "Insert Image in a Jupyter Notebook" }, { "code": null, "e": 28748, "s": 28705, "text": "How to Replace Values in a List in Python?" } ]
Palindrome Partitioning
In this algorithm, the input is a string, a partitioning of that string is palindrome partitioning when every substring of the partition is a palindrome. In this algorithm, we have to find the minimum cuts are needed to palindrome partitioning the given string. Input: A string. Say “ababbbabbababa” Output: Minimum cut to partition as palindrome. Here 3 cuts are needed. The palindromes are: a | babbbab | b | ababa minPalPart(str) Input: The given string. Output: Minimum number of palindromic partitioning from the string. Begin n := length of str define cut matrix and pal matrix each of order n x n for i := 0 to n, do pal[i, i] := true cut[i, i] := 0 done for len in range 2 to n, do for i in range 0 to n – len, do j := i + len – 1 if len = 2, then if str[i] = str[j] pal[i, j] := true else if str[i] = str[j] and pal[i+1, j-1] ≠ 0 pal[i, j] := true if pal[i, j] is true, then cut[i, j] := 0 else cut[i, j] := ∞ for k in range i to j-1, do cut[i, j] := minimum of cut[i, j] and (cut[i, k]+ cut[k+1, j+1]+1) done done done return cut[0, n-1] End #include <iostream> using namespace std; int min (int a, int b) { return (a < b)? a : b; } int minPalPartion(string str) { int n = str.size(); int cut[n][n]; bool pal[n][n]; //true when palindrome present for i to jth element for (int i=0; i<n; i++) { pal[i][i] = true; //substring of length 1 is plaindrome cut[i][i] = 0; } for (int len=2; len<=n; len++) { for (int i=0; i<n-len+1; i++) { //find all substrings of length len int j = i+len-1; // Set ending index if (len == 2) //for two character string pal[i][j] = (str[i] == str[j]); else //for string of more than two characters pal[i][j] = (str[i] == str[j]) && pal[i+1][j-1]; if (pal[i][j] == true) cut[i][j] = 0; else { cut[i][j] = INT_MAX; //initially set as infinity for (int k=i; k<=j-1; k++) cut[i][j] = min(cut[i][j], cut[i][k] + cut[k+1][j]+1); } } } return cut[0][n-1]; } int main() { string str= "ababbbabbababa"; cout << "Min cuts for Palindrome Partitioning is:" << minPalPartion(str); } Min cuts for Palindrome Partitioning is: 3
[ { "code": null, "e": 1216, "s": 1062, "text": "In this algorithm, the input is a string, a partitioning of that string is palindrome partitioning when every substring of the partition is a palindrome." }, { "code": null, "e": 1324, "s": 1216, "text": "In this algorithm, we have to find the minimum cuts are needed to palindrome partitioning the given string." }, { "code": null, "e": 1479, "s": 1324, "text": "Input:\nA string. Say “ababbbabbababa”\nOutput:\nMinimum cut to partition as palindrome. Here 3 cuts are needed.\nThe palindromes are: a | babbbab | b | ababa" }, { "code": null, "e": 1495, "s": 1479, "text": "minPalPart(str)" }, { "code": null, "e": 1520, "s": 1495, "text": "Input: The given string." }, { "code": null, "e": 1588, "s": 1520, "text": "Output: Minimum number of palindromic partitioning from the string." }, { "code": null, "e": 2326, "s": 1588, "text": "Begin\n n := length of str\n define cut matrix and pal matrix each of order n x n\n\n for i := 0 to n, do\n pal[i, i] := true\n cut[i, i] := 0\n done\n\n for len in range 2 to n, do\n for i in range 0 to n – len, do\n j := i + len – 1\n if len = 2, then\n if str[i] = str[j]\n pal[i, j] := true\n else\n if str[i] = str[j] and pal[i+1, j-1] ≠ 0\n pal[i, j] := true\n\n if pal[i, j] is true, then\n cut[i, j] := 0\n else\n\n cut[i, j] := ∞\n for k in range i to j-1, do\n cut[i, j] := minimum of cut[i, j] and (cut[i, k]+ cut[k+1, j+1]+1)\n done\n done\n done\n return cut[0, n-1]\nEnd" }, { "code": null, "e": 3558, "s": 2326, "text": "#include <iostream>\nusing namespace std;\n\nint min (int a, int b) {\n return (a < b)? a : b;\n}\n\nint minPalPartion(string str) {\n int n = str.size();\n\n int cut[n][n];\n bool pal[n][n]; //true when palindrome present for i to jth element\n\n for (int i=0; i<n; i++) {\n pal[i][i] = true; //substring of length 1 is plaindrome\n cut[i][i] = 0;\n }\n\n for (int len=2; len<=n; len++) {\n for (int i=0; i<n-len+1; i++) { //find all substrings of length len\n\n int j = i+len-1; // Set ending index\n if (len == 2) //for two character string\n pal[i][j] = (str[i] == str[j]);\n else //for string of more than two characters\n pal[i][j] = (str[i] == str[j]) && pal[i+1][j-1];\n\n if (pal[i][j] == true)\n cut[i][j] = 0;\n else {\n cut[i][j] = INT_MAX; //initially set as infinity\n for (int k=i; k<=j-1; k++)\n cut[i][j] = min(cut[i][j], cut[i][k] + cut[k+1][j]+1);\n }\n }\n }\n return cut[0][n-1];\n}\n\nint main() {\n string str= \"ababbbabbababa\";\n cout << \"Min cuts for Palindrome Partitioning is:\" << minPalPartion(str);\n}" }, { "code": null, "e": 3601, "s": 3558, "text": "Min cuts for Palindrome Partitioning is: 3" } ]
Demystifying Scrapy Item Loaders. Automate scrapy data cleaning and... | by Aaron S | Towards Data Science
When scraping data from websites it can be messy and incomplete. Now most tutorials on scrapy introduce the concept of Items. Items provide the containers for the data scrapped. But where do item loaders come into this? They provide the mechanism for populating the item containers. Item loaders automate common tasks like parsing the data before item containers. It also provides a cleaner way to manage extracted data as you scale your spider up. To follow along please read up about Items in the scrapy documentation. It’s necessary to have an understanding of this before continuing! In this article, we will define what an item loader is in comparison to Items. We will then talk about how Item Loaders do this work by processors. These processors are built-in or custom made. They provide us the ability to parse the data we get before populating the Item fields. We will then walk you how item loaders make the extracting of data much cleaner. This is before transferred to the processors. We will explain how to make our own processors beyond the built-in functions to alter our data to how we see fit. We will go through how to extend the ItemLoader. This allows us to scale up the functionality of our spiders when websites change. Defining ItemLoaders roleDefine input and output processors, the powerhouse of ItemLoadersDefine ItemLoaders methods. This is how ItemLoaders gets the data for the processorsDefining Item Loader contexts. This is a way for keys and values to get shared between processors and is usefulDefine the built-in processors Identity(), TakeFirst() , Join() , Compose() , MapCompose()How to define the specific input and out processors you need for your ItemLoader. This provides you with flexibility. You can choose different inputs and output processors for different Item fields.Define the NestedLoader. This is a way for cleaning the way we code our ItemLoader when all the data is in a chunk of HTML.How to extend the ItemLoader and add in functionality. Useful for scalability and when websites change. Defining ItemLoaders role Define input and output processors, the powerhouse of ItemLoaders Define ItemLoaders methods. This is how ItemLoaders gets the data for the processors Defining Item Loader contexts. This is a way for keys and values to get shared between processors and is useful Define the built-in processors Identity(), TakeFirst() , Join() , Compose() , MapCompose() How to define the specific input and out processors you need for your ItemLoader. This provides you with flexibility. You can choose different inputs and output processors for different Item fields. Define the NestedLoader. This is a way for cleaning the way we code our ItemLoader when all the data is in a chunk of HTML. How to extend the ItemLoader and add in functionality. Useful for scalability and when websites change. Let’s get behind the scenes of the item loaders. To make use of this, we have to create an ItemLoader. It’s a class called Scrapy.Loader.Itemloader. It has three main arguments. Item: Specifies an item or items we create for our spider to populate with the ItemLoader. If one is not specified scrapy makes a new item object called default_item_classSelector: Use a selector for the Itemloaders methods . If one is not specified, Scrapy makes a new selector class. The variable default_selector_class is then assigned.Response Used to construct a selector using default_selector_class Item: Specifies an item or items we create for our spider to populate with the ItemLoader. If one is not specified scrapy makes a new item object called default_item_class Selector: Use a selector for the Itemloaders methods . If one is not specified, Scrapy makes a new selector class. The variable default_selector_class is then assigned. Response Used to construct a selector using default_selector_class ItemLoader([item,selector,response,] **kwargs) To start using the ItemLoader we import it into our spider. We then import our Items we specify in our spiders items.py from scrapy.loader import ItemLoaderfrom myproject.items import Product Now let’s see how we would start the ItemLoader, note we don’t specify a selector here. Itemloader will actually populate a default selector if we don’t define it. def parse(self,response): l = ItemLoader(Product(), response) Notes 1. We start with the parse function this is where the ItemLoader instance gets formed. 2. We assign a variable l to our ItemLoader class instance. We specifying our product() items instance we define this in our spiders Items.py and the response. The next step of using ItemLoader class is the ItemLoader methods. This gives us the ability to grab data from our websites and allows us to manipulate it. We manipulate it through something called processors. An ItemLoader has an input processor and an output processor per each item field. They deal with the extracted data as soon as it’s received. The processors get defined in the ItemLoad methods to parse the data (Next section). Once we have manipulated data with our input processor. It then appends any data given to it to an internal list within the ItemLoader. Because this data gets put into a list this allows ItemLoader to have several values for one Item field. The results of this internal list are then fed to the output processor. Then the results of the output processor get assigned to the Item field. Processors are objects which get called with the data to parse and return a parsed value. With that, we can use any function as an input or output processor. The only condition is that the processor function’s first argument must be an iterable. Scrapy also comes with processors built-in which we will talk about in this article. We can now talk about the ItemLoader methods where the real magic happens! The ItemLoader class has methods that allow us to change our data before getting used in the item fields. We will talk about e important methods here. Please refer to the documentation for further details. If we have a look at the ItemLoader Class it has several functions to deal with extracting data. The three commonest are add_xpath() , add_css(), add_value(). They all accept an Item field name and then either an xpath selector, css selector or string value. It also allows for use of processors to alter the data. add_xpath(field_name, xpath,*processors,**kwargs) add_css(field_name,css, processors,**kwargs) add_value(field_name,value,processors,**kwargs) The heart of what an ItemLoader can do is through the input processor. Its why the ItemLoader Methods gives you the option to specify it. You change the extracted data by specifying your own input processor. Now if a processor is not specified a default processor is. This then returns only the values of the extracted data. Now the output processor takes this collected internal list. This may or may not have got changed by our own input processor. This provides new values to get populated. To populate the Item field with our extracted data we use the load_item() method. This populates the item field once it has been through the processors. Let’s see how this works in practice now with a simple example. def parse(self,response): l = ItemLoader(Product(), response) l.add_xpath('Title', //*[@itemprop="name"][1]/text()') return l.load_item() Notes 1. We define our ItemLoader with our item we defined product() and response 2. We use the add_xpath method specifying the Item field title and the xpath selector for the title. 3. We then populate this item field using the load_item() method Before getting into the built-in processors. It’s important to talk about Item Loader context. These are keys and values that can get shared. The ItemLoader we create has the defined items/selector/response assigned to loader_context. They can then get used to change the input/output processors. Some built-in processors can use it and is important to know. A loader_context argument in the processor function allows the processor to share data. A simple of example def parse_length(text,loader_context): unit = loader_context.get('unit','m')#length parsing code goes herereturn parse_length Now you can change Item Loader context values in several ways. Modifying the currently active item loader context Modifying the currently active item loader context loader = ItemLoader(product)loader.context['unit'] = 'cm' 2. On Item loader instantiation (as a keyword argument) loader = ItemLoader(product, unit='cm') 3. On Item loader declaration for input/output processors eg MapCompose class ProductLoader(ItemLoader): length_out = MapCompose(parse_length, unit='cm') ItemLoader contexts are useful for passing keys and values that we want to use in our processors. Now we have the basics of the ItemLoader nailed. Let’s move onto some of the boilerplate that Scrapy provides us. In the Scrapy code base, the classes of the built-in processors are in a separate file called processes.py. We have to import them to be able to use them. from scrapy.loader.processors import BUILTIN PROCESSORS There are six built-in processors Scrapy providesIdentity(), TakeFirst(), Join() , Compose() , MapCompose() , SelectJmes() . We will take you through the first five. Identity() is the simplest processor, it returns the value unchanged. from scrapy.loader.processors import Identityproc = Identity()proc(['one','two','three']) Output: ['one,'two','three'] This built-in processor you already have used it without knowing. The identity class instance gets assigned the variable default_input_processor and default_output_processor when no processors get specified in the ItemLoader methods we discussed. This means if when we don’t specify a processor, the ItemLoader returns the values unchanged. Takefirst() returns the first non-null/empty value from the values it receives. It gets used as an output processor to single-valued fields. from scrapy.loader.processors import TakeFirstproc = TakeFirst()proc(['', 'One','Two','Three']) Output: 'one' Join(separator=u’ ’) returns the values joined together. A separator can get used to put an expression between each item. The default being u’’. In the example below we input <br> . from scrapy.loader.processors import Joinproc = Join() proc(['One, 'Two', 'Three'])proc2 = Join('<br>')proc2(['One', 'Two','Three']) Output: 'one two three''one<br>two<br>three' Compose() takes an input value and passes it to a function specified in the argument. If another function gets specified the results get passed onto that function. This keeps going until the last function returns the output value of this processor. This function is something we create to change the input value. Compose() gets used as an input processor. The syntax iscompose(*functions,**default_loader_context) Now each function can receive a loader_context parameter. This will pass the active loader context key and value through to the processor. Now if no loader_context gets specified, a default_loader_context variable does. This passes nothing through. from scrapy.loader.processor import Composeproc = Compose(Lambda v: v[0], str.upper)proc(['hello','world]) Output: 'HELLO' Notes The compose builtin processor gets called onProc gets defined by our compose class which we specify with functions. A lambda function in this case and the string upper method. Each list item gets changed from lower case to upper case. The compose builtin processor gets called on Proc gets defined by our compose class which we specify with functions. A lambda function in this case and the string upper method. Each list item gets changed from lower case to upper case. Much like compose() but gets handled in a different way. The input values get iterated and the first function gets applied to each element. The results get concatenated to construct a new iterable. This is then used on the second function. The output values of the last function concatenated together and form the output. This provides a convenient way to create functions that only work with single values. This gets used as an input processor as string objects get extracted from selectors. def filter_world(x): return None if x == 'world else xfrom scrapy.loader.processors import MapComposeproc = MapCompose(filter_world, str.upper)proc(['hello', 'world', 'this','is', 'scrapy']) Output ['HELLO, 'THIS', 'IS', 'SCRAPY'] Notes. 1.We create a simple function calledfilter_world 2. Mapcompose gets imported 3. Proc gets assigned MapCompose. Two functions filter_world and the str method which acts like a function. 4. Proc is then fed an iterable and each item gets passed to filter_world and then has a string method applied to it. 5. Note see how the second item‘world’ gets fed to the filter_world function. This returns none, and the output of that function gets ignored. Further processing can now occur in the next item. It is this that gives us the output as it is, the item ‘world’ gets filtered out. We can declare ItemLoaders processors like Items. That is by using the class definition syntax. from scrapy.loader import ItemLoaderfrom scrapy.loader.processors import TakeFirst, MapCompose, Joinclass ProductLoader(ItemLoader): default_output_processor = Takefirst() name_in = MapCompose(unicode.title) name_out = Join() price_in = MapCompose(unicode.strip) Notes. The ProductLoader class extends the ItemLoader class_in suffix defines the input processor and _out suffix declares the output processor. We put the Item field (name in this case) before the suffix to define which field we want the process to work on.name_in assigns a MapCompose instance and has the defined function unicode.title. This will get used on the name Item Field.name_out gets defined as the Join() class instanceprice_in gets defined as a Mapcompose instance. The function unicode.strip gets defined for the prices Item field. The ProductLoader class extends the ItemLoader class _in suffix defines the input processor and _out suffix declares the output processor. We put the Item field (name in this case) before the suffix to define which field we want the process to work on. name_in assigns a MapCompose instance and has the defined function unicode.title. This will get used on the name Item Field. name_out gets defined as the Join() class instance price_in gets defined as a Mapcompose instance. The function unicode.strip gets defined for the prices Item field. It is also possible to declare processors in the Item Fields lets see how that works. import scrapy from scrapy.loader.processors import Join, MapCompose, Takefirstfrom w3lib.html import remove_tagsdef filter_price(value): if value.isdigit(): return valueclass Product(scrapy.Item): name = scrapy.Field(input_processor=MapCompose(remove_tags), outputprocessor=Join(),) price = scrapy.Field(input_processor=MapCompose(remove_tags, filter_price), outprocessor=Takefirst(),) Notes We import the builtin processors and another package that removes tags.We define the filter_pricefunction, if the input is a digit it gets returned.We then define the items by extending the Scrapy.Item class.Name gets defined as an ItemField. We specify which input and output processors should get used.Price gets defined as an ItemField. We specify which input and output processors should get used.Price has two functions called upon, the remove_tags and filter_price. The filter_price is the function we defined. We import the builtin processors and another package that removes tags. We define the filter_pricefunction, if the input is a digit it gets returned. We then define the items by extending the Scrapy.Item class. Name gets defined as an ItemField. We specify which input and output processors should get used. Price gets defined as an ItemField. We specify which input and output processors should get used. Price has two functions called upon, the remove_tags and filter_price. The filter_price is the function we defined. Now we can use an ItemLoader instance in our data.py file of our spider. Note we have specified our input and output processors through our items.py from our spider. from scrapy.loader import ItemLoader il = ItemLoader(item=Product())il.add_value('name',[u'Welcome to my', u'<strong>website</strong>'])il.add_value('price', [u'&euro;', u'<span>1000</span>'])il.load_item() Output: {'name': u'Welcome to my website', 'price': u'1000'} Notes 1. We now import the ItemLoader class 2. We define the Itemloader with the Item fields we created 3. We use the add_value method, define the name Item field and we pass along a list with a string in it. 4. We use the add_value method to define the price item field and pass another list with two items. 5. When we add the first value string, this gets its tags removed and both items get joined together 6. When we add the second value, the first item gets ignored as it is not a string and we turn the number 1000. 7. The load_item()method gives us a dictionary of Item field names and our modified data. This gets inputted into the Item fields. Now there is a precedence order for input and output processors from number 1 to number 3. 1. Item loader field-specific attributes field_in and field_out 2. Field metadata (input_processor and output_processor keyword arguments) 3. Item Loader defaults itemLoad.default_input_processor()and itemLoad.default_output_processor() When the information you want to scrape is in a big block we can use a nested loader for readability. It allows us to shorten the ItemLoader methods paths by making a relative path. This can make your scrappy projects a bit easier to read but don’t overuse it! Loader = ItemLoader(item=Item())footer_loader = loader.nested_xpath('//footer/)footer_loader.add_xpath('social','a[@class="social"]/@href')loader.load_item() Notes We instantiate an Itemloader class like beforeWe define a variable for our nested loader. We specify the nested_xpath() method, it accepts a selector. In this case we give it //footer/.We use footer_loader to access the ItemLoader methods. This means we don't have to specify the footer selector several times. In this case we call on the add_xpath() method, define the item field and the relative xpath selector we want. This way we don’t have to keep writing the //footer/ part of the xpath selector We instantiate an Itemloader class like before We define a variable for our nested loader. We specify the nested_xpath() method, it accepts a selector. In this case we give it //footer/. We use footer_loader to access the ItemLoader methods. This means we don't have to specify the footer selector several times. In this case we call on the add_xpath() method, define the item field and the relative xpath selector we want. This way we don’t have to keep writing the //footer/ part of the xpath selector 4. We call upon the load_item() method as before to input this into our Item Field social. We can use the property of inheritance to extend our ItemLoaders. This provides functionality without having to create a separate ItemLoader. This becomes particularly important when websites change. This is the power of ItemLoaders, we can scale up when websites change. We tend to extend the ItemLoader class when needing different input processors. It is more custom to use the Item.py, to define the output processor. from scrapy.loader.processors import MapComposefrom myproduct.ItemLoaders import ProductLoaderdef strip_dashes(x): return x.strip('-')class SiteSpecificLoader(ProductLoader): name_in = MapCompose(strip_dashes, ProductLoader.name_in) Notes We import the MapCompose processesWe also import a ProductLoader, this is our ItemLoader we define We import the MapCompose processes We also import a ProductLoader, this is our ItemLoader we define 3. We then create a function strip_dashes to remove dashes 4. We then extend the ProductLoader in a SiteSpecificLoader 5. We define the name field input processor as MapCompose. We pass in the strip_dash function and call upon the ProductLoader name_in method. We can then use the name_in input processor in our SiteSpecificLoader. With all the other boilerplate of the ProductLoader. Scrapy gives you the ability to extend and reuse your ItemLoader for different sites or data. Here you have learned what the relationship between Items and Itemloader is. We have shown how processors get used to be able to parse the data we have extracted. ItemLoader methods are the way we grab data to change from our websites. We have talked through the different built-in processors scrapy has. This also us to specify either built-in or new processors for the Item fields. towardsdatascience.com towardsdatascience.com I am a medical doctor who has a keen interest in teaching, python, technology and healthcare. I am based in the UK, I teach online clinical education as well as running the websites www.coding-medics.com. You can contact me on [email protected] or on twitter here, all comments and recommendations welcome! If you want to chat about any projects or to collaborate that would be great. For more tech/coding related content please sign up to my newsletter here.
[ { "code": null, "e": 455, "s": 172, "text": "When scraping data from websites it can be messy and incomplete. Now most tutorials on scrapy introduce the concept of Items. Items provide the containers for the data scrapped. But where do item loaders come into this? They provide the mechanism for populating the item containers." }, { "code": null, "e": 621, "s": 455, "text": "Item loaders automate common tasks like parsing the data before item containers. It also provides a cleaner way to manage extracted data as you scale your spider up." }, { "code": null, "e": 760, "s": 621, "text": "To follow along please read up about Items in the scrapy documentation. It’s necessary to have an understanding of this before continuing!" }, { "code": null, "e": 1414, "s": 760, "text": "In this article, we will define what an item loader is in comparison to Items. We will then talk about how Item Loaders do this work by processors. These processors are built-in or custom made. They provide us the ability to parse the data we get before populating the Item fields. We will then walk you how item loaders make the extracting of data much cleaner. This is before transferred to the processors. We will explain how to make our own processors beyond the built-in functions to alter our data to how we see fit. We will go through how to extend the ItemLoader. This allows us to scale up the functionality of our spiders when websites change." }, { "code": null, "e": 2214, "s": 1414, "text": "Defining ItemLoaders roleDefine input and output processors, the powerhouse of ItemLoadersDefine ItemLoaders methods. This is how ItemLoaders gets the data for the processorsDefining Item Loader contexts. This is a way for keys and values to get shared between processors and is usefulDefine the built-in processors Identity(), TakeFirst() , Join() , Compose() , MapCompose()How to define the specific input and out processors you need for your ItemLoader. This provides you with flexibility. You can choose different inputs and output processors for different Item fields.Define the NestedLoader. This is a way for cleaning the way we code our ItemLoader when all the data is in a chunk of HTML.How to extend the ItemLoader and add in functionality. Useful for scalability and when websites change." }, { "code": null, "e": 2240, "s": 2214, "text": "Defining ItemLoaders role" }, { "code": null, "e": 2306, "s": 2240, "text": "Define input and output processors, the powerhouse of ItemLoaders" }, { "code": null, "e": 2391, "s": 2306, "text": "Define ItemLoaders methods. This is how ItemLoaders gets the data for the processors" }, { "code": null, "e": 2503, "s": 2391, "text": "Defining Item Loader contexts. This is a way for keys and values to get shared between processors and is useful" }, { "code": null, "e": 2594, "s": 2503, "text": "Define the built-in processors Identity(), TakeFirst() , Join() , Compose() , MapCompose()" }, { "code": null, "e": 2793, "s": 2594, "text": "How to define the specific input and out processors you need for your ItemLoader. This provides you with flexibility. You can choose different inputs and output processors for different Item fields." }, { "code": null, "e": 2917, "s": 2793, "text": "Define the NestedLoader. This is a way for cleaning the way we code our ItemLoader when all the data is in a chunk of HTML." }, { "code": null, "e": 3021, "s": 2917, "text": "How to extend the ItemLoader and add in functionality. Useful for scalability and when websites change." }, { "code": null, "e": 3199, "s": 3021, "text": "Let’s get behind the scenes of the item loaders. To make use of this, we have to create an ItemLoader. It’s a class called Scrapy.Loader.Itemloader. It has three main arguments." }, { "code": null, "e": 3605, "s": 3199, "text": "Item: Specifies an item or items we create for our spider to populate with the ItemLoader. If one is not specified scrapy makes a new item object called default_item_classSelector: Use a selector for the Itemloaders methods . If one is not specified, Scrapy makes a new selector class. The variable default_selector_class is then assigned.Response Used to construct a selector using default_selector_class" }, { "code": null, "e": 3777, "s": 3605, "text": "Item: Specifies an item or items we create for our spider to populate with the ItemLoader. If one is not specified scrapy makes a new item object called default_item_class" }, { "code": null, "e": 3946, "s": 3777, "text": "Selector: Use a selector for the Itemloaders methods . If one is not specified, Scrapy makes a new selector class. The variable default_selector_class is then assigned." }, { "code": null, "e": 4013, "s": 3946, "text": "Response Used to construct a selector using default_selector_class" }, { "code": null, "e": 4060, "s": 4013, "text": "ItemLoader([item,selector,response,] **kwargs)" }, { "code": null, "e": 4180, "s": 4060, "text": "To start using the ItemLoader we import it into our spider. We then import our Items we specify in our spiders items.py" }, { "code": null, "e": 4252, "s": 4180, "text": "from scrapy.loader import ItemLoaderfrom myproject.items import Product" }, { "code": null, "e": 4416, "s": 4252, "text": "Now let’s see how we would start the ItemLoader, note we don’t specify a selector here. Itemloader will actually populate a default selector if we don’t define it." }, { "code": null, "e": 4481, "s": 4416, "text": "def parse(self,response): l = ItemLoader(Product(), response)" }, { "code": null, "e": 4574, "s": 4481, "text": "Notes 1. We start with the parse function this is where the ItemLoader instance gets formed." }, { "code": null, "e": 4734, "s": 4574, "text": "2. We assign a variable l to our ItemLoader class instance. We specifying our product() items instance we define this in our spiders Items.py and the response." }, { "code": null, "e": 4944, "s": 4734, "text": "The next step of using ItemLoader class is the ItemLoader methods. This gives us the ability to grab data from our websites and allows us to manipulate it. We manipulate it through something called processors." }, { "code": null, "e": 5171, "s": 4944, "text": "An ItemLoader has an input processor and an output processor per each item field. They deal with the extracted data as soon as it’s received. The processors get defined in the ItemLoad methods to parse the data (Next section)." }, { "code": null, "e": 5557, "s": 5171, "text": "Once we have manipulated data with our input processor. It then appends any data given to it to an internal list within the ItemLoader. Because this data gets put into a list this allows ItemLoader to have several values for one Item field. The results of this internal list are then fed to the output processor. Then the results of the output processor get assigned to the Item field." }, { "code": null, "e": 5803, "s": 5557, "text": "Processors are objects which get called with the data to parse and return a parsed value. With that, we can use any function as an input or output processor. The only condition is that the processor function’s first argument must be an iterable." }, { "code": null, "e": 5888, "s": 5803, "text": "Scrapy also comes with processors built-in which we will talk about in this article." }, { "code": null, "e": 5963, "s": 5888, "text": "We can now talk about the ItemLoader methods where the real magic happens!" }, { "code": null, "e": 6169, "s": 5963, "text": "The ItemLoader class has methods that allow us to change our data before getting used in the item fields. We will talk about e important methods here. Please refer to the documentation for further details." }, { "code": null, "e": 6328, "s": 6169, "text": "If we have a look at the ItemLoader Class it has several functions to deal with extracting data. The three commonest are add_xpath() , add_css(), add_value()." }, { "code": null, "e": 6484, "s": 6328, "text": "They all accept an Item field name and then either an xpath selector, css selector or string value. It also allows for use of processors to alter the data." }, { "code": null, "e": 6534, "s": 6484, "text": "add_xpath(field_name, xpath,*processors,**kwargs)" }, { "code": null, "e": 6579, "s": 6534, "text": "add_css(field_name,css, processors,**kwargs)" }, { "code": null, "e": 6627, "s": 6579, "text": "add_value(field_name,value,processors,**kwargs)" }, { "code": null, "e": 6765, "s": 6627, "text": "The heart of what an ItemLoader can do is through the input processor. Its why the ItemLoader Methods gives you the option to specify it." }, { "code": null, "e": 6952, "s": 6765, "text": "You change the extracted data by specifying your own input processor. Now if a processor is not specified a default processor is. This then returns only the values of the extracted data." }, { "code": null, "e": 7121, "s": 6952, "text": "Now the output processor takes this collected internal list. This may or may not have got changed by our own input processor. This provides new values to get populated." }, { "code": null, "e": 7274, "s": 7121, "text": "To populate the Item field with our extracted data we use the load_item() method. This populates the item field once it has been through the processors." }, { "code": null, "e": 7338, "s": 7274, "text": "Let’s see how this works in practice now with a simple example." }, { "code": null, "e": 7485, "s": 7338, "text": "def parse(self,response): l = ItemLoader(Product(), response) l.add_xpath('Title', //*[@itemprop=\"name\"][1]/text()') return l.load_item()" }, { "code": null, "e": 7491, "s": 7485, "text": "Notes" }, { "code": null, "e": 7567, "s": 7491, "text": "1. We define our ItemLoader with our item we defined product() and response" }, { "code": null, "e": 7668, "s": 7567, "text": "2. We use the add_xpath method specifying the Item field title and the xpath selector for the title." }, { "code": null, "e": 7733, "s": 7668, "text": "3. We then populate this item field using the load_item() method" }, { "code": null, "e": 8030, "s": 7733, "text": "Before getting into the built-in processors. It’s important to talk about Item Loader context. These are keys and values that can get shared. The ItemLoader we create has the defined items/selector/response assigned to loader_context. They can then get used to change the input/output processors." }, { "code": null, "e": 8092, "s": 8030, "text": "Some built-in processors can use it and is important to know." }, { "code": null, "e": 8180, "s": 8092, "text": "A loader_context argument in the processor function allows the processor to share data." }, { "code": null, "e": 8200, "s": 8180, "text": "A simple of example" }, { "code": null, "e": 8329, "s": 8200, "text": "def parse_length(text,loader_context): unit = loader_context.get('unit','m')#length parsing code goes herereturn parse_length" }, { "code": null, "e": 8392, "s": 8329, "text": "Now you can change Item Loader context values in several ways." }, { "code": null, "e": 8443, "s": 8392, "text": "Modifying the currently active item loader context" }, { "code": null, "e": 8494, "s": 8443, "text": "Modifying the currently active item loader context" }, { "code": null, "e": 8552, "s": 8494, "text": "loader = ItemLoader(product)loader.context['unit'] = 'cm'" }, { "code": null, "e": 8608, "s": 8552, "text": "2. On Item loader instantiation (as a keyword argument)" }, { "code": null, "e": 8648, "s": 8608, "text": "loader = ItemLoader(product, unit='cm')" }, { "code": null, "e": 8720, "s": 8648, "text": "3. On Item loader declaration for input/output processors eg MapCompose" }, { "code": null, "e": 8805, "s": 8720, "text": "class ProductLoader(ItemLoader): length_out = MapCompose(parse_length, unit='cm')" }, { "code": null, "e": 8903, "s": 8805, "text": "ItemLoader contexts are useful for passing keys and values that we want to use in our processors." }, { "code": null, "e": 9017, "s": 8903, "text": "Now we have the basics of the ItemLoader nailed. Let’s move onto some of the boilerplate that Scrapy provides us." }, { "code": null, "e": 9172, "s": 9017, "text": "In the Scrapy code base, the classes of the built-in processors are in a separate file called processes.py. We have to import them to be able to use them." }, { "code": null, "e": 9228, "s": 9172, "text": "from scrapy.loader.processors import BUILTIN PROCESSORS" }, { "code": null, "e": 9394, "s": 9228, "text": "There are six built-in processors Scrapy providesIdentity(), TakeFirst(), Join() , Compose() , MapCompose() , SelectJmes() . We will take you through the first five." }, { "code": null, "e": 9464, "s": 9394, "text": "Identity() is the simplest processor, it returns the value unchanged." }, { "code": null, "e": 9554, "s": 9464, "text": "from scrapy.loader.processors import Identityproc = Identity()proc(['one','two','three'])" }, { "code": null, "e": 9562, "s": 9554, "text": "Output:" }, { "code": null, "e": 9583, "s": 9562, "text": "['one,'two','three']" }, { "code": null, "e": 9924, "s": 9583, "text": "This built-in processor you already have used it without knowing. The identity class instance gets assigned the variable default_input_processor and default_output_processor when no processors get specified in the ItemLoader methods we discussed. This means if when we don’t specify a processor, the ItemLoader returns the values unchanged." }, { "code": null, "e": 10065, "s": 9924, "text": "Takefirst() returns the first non-null/empty value from the values it receives. It gets used as an output processor to single-valued fields." }, { "code": null, "e": 10161, "s": 10065, "text": "from scrapy.loader.processors import TakeFirstproc = TakeFirst()proc(['', 'One','Two','Three'])" }, { "code": null, "e": 10169, "s": 10161, "text": "Output:" }, { "code": null, "e": 10175, "s": 10169, "text": "'one'" }, { "code": null, "e": 10357, "s": 10175, "text": "Join(separator=u’ ’) returns the values joined together. A separator can get used to put an expression between each item. The default being u’’. In the example below we input <br> ." }, { "code": null, "e": 10490, "s": 10357, "text": "from scrapy.loader.processors import Joinproc = Join() proc(['One, 'Two', 'Three'])proc2 = Join('<br>')proc2(['One', 'Two','Three'])" }, { "code": null, "e": 10498, "s": 10490, "text": "Output:" }, { "code": null, "e": 10535, "s": 10498, "text": "'one two three''one<br>two<br>three'" }, { "code": null, "e": 10891, "s": 10535, "text": "Compose() takes an input value and passes it to a function specified in the argument. If another function gets specified the results get passed onto that function. This keeps going until the last function returns the output value of this processor. This function is something we create to change the input value. Compose() gets used as an input processor." }, { "code": null, "e": 10949, "s": 10891, "text": "The syntax iscompose(*functions,**default_loader_context)" }, { "code": null, "e": 11198, "s": 10949, "text": "Now each function can receive a loader_context parameter. This will pass the active loader context key and value through to the processor. Now if no loader_context gets specified, a default_loader_context variable does. This passes nothing through." }, { "code": null, "e": 11305, "s": 11198, "text": "from scrapy.loader.processor import Composeproc = Compose(Lambda v: v[0], str.upper)proc(['hello','world])" }, { "code": null, "e": 11313, "s": 11305, "text": "Output:" }, { "code": null, "e": 11321, "s": 11313, "text": "'HELLO'" }, { "code": null, "e": 11327, "s": 11321, "text": "Notes" }, { "code": null, "e": 11562, "s": 11327, "text": "The compose builtin processor gets called onProc gets defined by our compose class which we specify with functions. A lambda function in this case and the string upper method. Each list item gets changed from lower case to upper case." }, { "code": null, "e": 11607, "s": 11562, "text": "The compose builtin processor gets called on" }, { "code": null, "e": 11798, "s": 11607, "text": "Proc gets defined by our compose class which we specify with functions. A lambda function in this case and the string upper method. Each list item gets changed from lower case to upper case." }, { "code": null, "e": 12120, "s": 11798, "text": "Much like compose() but gets handled in a different way. The input values get iterated and the first function gets applied to each element. The results get concatenated to construct a new iterable. This is then used on the second function. The output values of the last function concatenated together and form the output." }, { "code": null, "e": 12291, "s": 12120, "text": "This provides a convenient way to create functions that only work with single values. This gets used as an input processor as string objects get extracted from selectors." }, { "code": null, "e": 12485, "s": 12291, "text": "def filter_world(x): return None if x == 'world else xfrom scrapy.loader.processors import MapComposeproc = MapCompose(filter_world, str.upper)proc(['hello', 'world', 'this','is', 'scrapy'])" }, { "code": null, "e": 12492, "s": 12485, "text": "Output" }, { "code": null, "e": 12525, "s": 12492, "text": "['HELLO, 'THIS', 'IS', 'SCRAPY']" }, { "code": null, "e": 12532, "s": 12525, "text": "Notes." }, { "code": null, "e": 12581, "s": 12532, "text": "1.We create a simple function calledfilter_world" }, { "code": null, "e": 12609, "s": 12581, "text": "2. Mapcompose gets imported" }, { "code": null, "e": 12717, "s": 12609, "text": "3. Proc gets assigned MapCompose. Two functions filter_world and the str method which acts like a function." }, { "code": null, "e": 12835, "s": 12717, "text": "4. Proc is then fed an iterable and each item gets passed to filter_world and then has a string method applied to it." }, { "code": null, "e": 13111, "s": 12835, "text": "5. Note see how the second item‘world’ gets fed to the filter_world function. This returns none, and the output of that function gets ignored. Further processing can now occur in the next item. It is this that gives us the output as it is, the item ‘world’ gets filtered out." }, { "code": null, "e": 13207, "s": 13111, "text": "We can declare ItemLoaders processors like Items. That is by using the class definition syntax." }, { "code": null, "e": 13482, "s": 13207, "text": "from scrapy.loader import ItemLoaderfrom scrapy.loader.processors import TakeFirst, MapCompose, Joinclass ProductLoader(ItemLoader): default_output_processor = Takefirst() name_in = MapCompose(unicode.title) name_out = Join() price_in = MapCompose(unicode.strip)" }, { "code": null, "e": 13489, "s": 13482, "text": "Notes." }, { "code": null, "e": 14029, "s": 13489, "text": "The ProductLoader class extends the ItemLoader class_in suffix defines the input processor and _out suffix declares the output processor. We put the Item field (name in this case) before the suffix to define which field we want the process to work on.name_in assigns a MapCompose instance and has the defined function unicode.title. This will get used on the name Item Field.name_out gets defined as the Join() class instanceprice_in gets defined as a Mapcompose instance. The function unicode.strip gets defined for the prices Item field." }, { "code": null, "e": 14082, "s": 14029, "text": "The ProductLoader class extends the ItemLoader class" }, { "code": null, "e": 14282, "s": 14082, "text": "_in suffix defines the input processor and _out suffix declares the output processor. We put the Item field (name in this case) before the suffix to define which field we want the process to work on." }, { "code": null, "e": 14407, "s": 14282, "text": "name_in assigns a MapCompose instance and has the defined function unicode.title. This will get used on the name Item Field." }, { "code": null, "e": 14458, "s": 14407, "text": "name_out gets defined as the Join() class instance" }, { "code": null, "e": 14573, "s": 14458, "text": "price_in gets defined as a Mapcompose instance. The function unicode.strip gets defined for the prices Item field." }, { "code": null, "e": 14659, "s": 14573, "text": "It is also possible to declare processors in the Item Fields lets see how that works." }, { "code": null, "e": 15063, "s": 14659, "text": "import scrapy from scrapy.loader.processors import Join, MapCompose, Takefirstfrom w3lib.html import remove_tagsdef filter_price(value): if value.isdigit(): return valueclass Product(scrapy.Item): name = scrapy.Field(input_processor=MapCompose(remove_tags), outputprocessor=Join(),) price = scrapy.Field(input_processor=MapCompose(remove_tags, filter_price), outprocessor=Takefirst(),)" }, { "code": null, "e": 15069, "s": 15063, "text": "Notes" }, { "code": null, "e": 15586, "s": 15069, "text": "We import the builtin processors and another package that removes tags.We define the filter_pricefunction, if the input is a digit it gets returned.We then define the items by extending the Scrapy.Item class.Name gets defined as an ItemField. We specify which input and output processors should get used.Price gets defined as an ItemField. We specify which input and output processors should get used.Price has two functions called upon, the remove_tags and filter_price. The filter_price is the function we defined." }, { "code": null, "e": 15658, "s": 15586, "text": "We import the builtin processors and another package that removes tags." }, { "code": null, "e": 15736, "s": 15658, "text": "We define the filter_pricefunction, if the input is a digit it gets returned." }, { "code": null, "e": 15797, "s": 15736, "text": "We then define the items by extending the Scrapy.Item class." }, { "code": null, "e": 15894, "s": 15797, "text": "Name gets defined as an ItemField. We specify which input and output processors should get used." }, { "code": null, "e": 15992, "s": 15894, "text": "Price gets defined as an ItemField. We specify which input and output processors should get used." }, { "code": null, "e": 16108, "s": 15992, "text": "Price has two functions called upon, the remove_tags and filter_price. The filter_price is the function we defined." }, { "code": null, "e": 16274, "s": 16108, "text": "Now we can use an ItemLoader instance in our data.py file of our spider. Note we have specified our input and output processors through our items.py from our spider." }, { "code": null, "e": 16484, "s": 16274, "text": "from scrapy.loader import ItemLoader il = ItemLoader(item=Product())il.add_value('name',[u'Welcome to my', u'<strong>website</strong>'])il.add_value('price', [u'&euro;', u'<span>1000</span>'])il.load_item()" }, { "code": null, "e": 16492, "s": 16484, "text": "Output:" }, { "code": null, "e": 16545, "s": 16492, "text": "{'name': u'Welcome to my website', 'price': u'1000'}" }, { "code": null, "e": 17198, "s": 16545, "text": "Notes 1. We now import the ItemLoader class 2. We define the Itemloader with the Item fields we created 3. We use the add_value method, define the name Item field and we pass along a list with a string in it. 4. We use the add_value method to define the price item field and pass another list with two items. 5. When we add the first value string, this gets its tags removed and both items get joined together 6. When we add the second value, the first item gets ignored as it is not a string and we turn the number 1000. 7. The load_item()method gives us a dictionary of Item field names and our modified data. This gets inputted into the Item fields." }, { "code": null, "e": 17289, "s": 17198, "text": "Now there is a precedence order for input and output processors from number 1 to number 3." }, { "code": null, "e": 17353, "s": 17289, "text": "1. Item loader field-specific attributes field_in and field_out" }, { "code": null, "e": 17428, "s": 17353, "text": "2. Field metadata (input_processor and output_processor keyword arguments)" }, { "code": null, "e": 17526, "s": 17428, "text": "3. Item Loader defaults itemLoad.default_input_processor()and itemLoad.default_output_processor()" }, { "code": null, "e": 17787, "s": 17526, "text": "When the information you want to scrape is in a big block we can use a nested loader for readability. It allows us to shorten the ItemLoader methods paths by making a relative path. This can make your scrappy projects a bit easier to read but don’t overuse it!" }, { "code": null, "e": 17945, "s": 17787, "text": "Loader = ItemLoader(item=Item())footer_loader = loader.nested_xpath('//footer/)footer_loader.add_xpath('social','a[@class=\"social\"]/@href')loader.load_item()" }, { "code": null, "e": 17951, "s": 17945, "text": "Notes" }, { "code": null, "e": 18453, "s": 17951, "text": "We instantiate an Itemloader class like beforeWe define a variable for our nested loader. We specify the nested_xpath() method, it accepts a selector. In this case we give it //footer/.We use footer_loader to access the ItemLoader methods. This means we don't have to specify the footer selector several times. In this case we call on the add_xpath() method, define the item field and the relative xpath selector we want. This way we don’t have to keep writing the //footer/ part of the xpath selector" }, { "code": null, "e": 18500, "s": 18453, "text": "We instantiate an Itemloader class like before" }, { "code": null, "e": 18640, "s": 18500, "text": "We define a variable for our nested loader. We specify the nested_xpath() method, it accepts a selector. In this case we give it //footer/." }, { "code": null, "e": 18957, "s": 18640, "text": "We use footer_loader to access the ItemLoader methods. This means we don't have to specify the footer selector several times. In this case we call on the add_xpath() method, define the item field and the relative xpath selector we want. This way we don’t have to keep writing the //footer/ part of the xpath selector" }, { "code": null, "e": 19048, "s": 18957, "text": "4. We call upon the load_item() method as before to input this into our Item Field social." }, { "code": null, "e": 19320, "s": 19048, "text": "We can use the property of inheritance to extend our ItemLoaders. This provides functionality without having to create a separate ItemLoader. This becomes particularly important when websites change. This is the power of ItemLoaders, we can scale up when websites change." }, { "code": null, "e": 19470, "s": 19320, "text": "We tend to extend the ItemLoader class when needing different input processors. It is more custom to use the Item.py, to define the output processor." }, { "code": null, "e": 19709, "s": 19470, "text": "from scrapy.loader.processors import MapComposefrom myproduct.ItemLoaders import ProductLoaderdef strip_dashes(x): return x.strip('-')class SiteSpecificLoader(ProductLoader): name_in = MapCompose(strip_dashes, ProductLoader.name_in)" }, { "code": null, "e": 19715, "s": 19709, "text": "Notes" }, { "code": null, "e": 19814, "s": 19715, "text": "We import the MapCompose processesWe also import a ProductLoader, this is our ItemLoader we define" }, { "code": null, "e": 19849, "s": 19814, "text": "We import the MapCompose processes" }, { "code": null, "e": 19914, "s": 19849, "text": "We also import a ProductLoader, this is our ItemLoader we define" }, { "code": null, "e": 19973, "s": 19914, "text": "3. We then create a function strip_dashes to remove dashes" }, { "code": null, "e": 20033, "s": 19973, "text": "4. We then extend the ProductLoader in a SiteSpecificLoader" }, { "code": null, "e": 20175, "s": 20033, "text": "5. We define the name field input processor as MapCompose. We pass in the strip_dash function and call upon the ProductLoader name_in method." }, { "code": null, "e": 20299, "s": 20175, "text": "We can then use the name_in input processor in our SiteSpecificLoader. With all the other boilerplate of the ProductLoader." }, { "code": null, "e": 20393, "s": 20299, "text": "Scrapy gives you the ability to extend and reuse your ItemLoader for different sites or data." }, { "code": null, "e": 20777, "s": 20393, "text": "Here you have learned what the relationship between Items and Itemloader is. We have shown how processors get used to be able to parse the data we have extracted. ItemLoader methods are the way we grab data to change from our websites. We have talked through the different built-in processors scrapy has. This also us to specify either built-in or new processors for the Item fields." }, { "code": null, "e": 20800, "s": 20777, "text": "towardsdatascience.com" }, { "code": null, "e": 20823, "s": 20800, "text": "towardsdatascience.com" }, { "code": null, "e": 21028, "s": 20823, "text": "I am a medical doctor who has a keen interest in teaching, python, technology and healthcare. I am based in the UK, I teach online clinical education as well as running the websites www.coding-medics.com." }, { "code": null, "e": 21208, "s": 21028, "text": "You can contact me on [email protected] or on twitter here, all comments and recommendations welcome! If you want to chat about any projects or to collaborate that would be great." } ]
Count the number of unique characters in a string in Python - GeeksforGeeks
06 Jul, 2021 Given a string S consisting of lowercase English alphabets, the task is to find the number of unique characters present in the string. Examples: Input: S = “geeksforgeeks”Output: 7Explanation: The given string “geeksforgeeks” contains 6 unique characters {‘g’, ‘e’, ‘k’, ‘s’, ‘f’, ‘o’, ‘r’}. Input: S = “madam”Output: 3 Approach: The idea to solve the given problem is to initialize a Set() in python to store all distinct characters of the given string and then, print the size of the set as the required answer. Below is the implementation of the above approach: Python3 # Python program for the above approach # Function to count the number of distinct# characters present in the string strdef countDis(str): # Stores all distinct characters s = set(str) # Return the size of the set return len(s) # Driver Codeif __name__ == "__main__": # Given string S S = "geeksforgeeks" print(countDis(S)) 7 Time Complexity: O(N)Auxiliary Space: O(1) Count the frequencies of all elements using Counter function and number of keys of this frequency dictionary gives the result. Below is the implementation: Python3 # Python program for the above approachfrom collections import Counter # Function to count the number of distinct# characters present in the string strdef countDis(str): # Stores all frequencies freq = Counter(str) # Return the size of the freq dictionary return len(freq) # Driver Codeif __name__ == "__main__": # Given string S S = "geeksforgeeks" print(countDis(S)) # This code is contributed by vikkycirus Output: 7 Time Complexity: O(N) Auxiliary Space: O(N) official_vivek vikkycirus arorakashish0911 HashSet python-set Hash Python Strings Technical Scripter python-set Hash Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Quadratic Probing in Hashing Rearrange an array such that arr[i] = i Hashing in Java Load Factor and Rehashing Hash Functions and list/types of Hash functions 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": 25078, "s": 25050, "text": "\n06 Jul, 2021" }, { "code": null, "e": 25213, "s": 25078, "text": "Given a string S consisting of lowercase English alphabets, the task is to find the number of unique characters present in the string." }, { "code": null, "e": 25223, "s": 25213, "text": "Examples:" }, { "code": null, "e": 25370, "s": 25223, "text": "Input: S = “geeksforgeeks”Output: 7Explanation: The given string “geeksforgeeks” contains 6 unique characters {‘g’, ‘e’, ‘k’, ‘s’, ‘f’, ‘o’, ‘r’}." }, { "code": null, "e": 25398, "s": 25370, "text": "Input: S = “madam”Output: 3" }, { "code": null, "e": 25592, "s": 25398, "text": "Approach: The idea to solve the given problem is to initialize a Set() in python to store all distinct characters of the given string and then, print the size of the set as the required answer." }, { "code": null, "e": 25643, "s": 25592, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 25651, "s": 25643, "text": "Python3" }, { "code": "# Python program for the above approach # Function to count the number of distinct# characters present in the string strdef countDis(str): # Stores all distinct characters s = set(str) # Return the size of the set return len(s) # Driver Codeif __name__ == \"__main__\": # Given string S S = \"geeksforgeeks\" print(countDis(S))", "e": 26001, "s": 25651, "text": null }, { "code": null, "e": 26003, "s": 26001, "text": "7" }, { "code": null, "e": 26048, "s": 26005, "text": "Time Complexity: O(N)Auxiliary Space: O(1)" }, { "code": null, "e": 26175, "s": 26048, "text": "Count the frequencies of all elements using Counter function and number of keys of this frequency dictionary gives the result." }, { "code": null, "e": 26204, "s": 26175, "text": "Below is the implementation:" }, { "code": null, "e": 26212, "s": 26204, "text": "Python3" }, { "code": "# Python program for the above approachfrom collections import Counter # Function to count the number of distinct# characters present in the string strdef countDis(str): # Stores all frequencies freq = Counter(str) # Return the size of the freq dictionary return len(freq) # Driver Codeif __name__ == \"__main__\": # Given string S S = \"geeksforgeeks\" print(countDis(S)) # This code is contributed by vikkycirus", "e": 26652, "s": 26212, "text": null }, { "code": null, "e": 26660, "s": 26652, "text": "Output:" }, { "code": null, "e": 26662, "s": 26660, "text": "7" }, { "code": null, "e": 26684, "s": 26662, "text": "Time Complexity: O(N)" }, { "code": null, "e": 26706, "s": 26684, "text": "Auxiliary Space: O(N)" }, { "code": null, "e": 26721, "s": 26706, "text": "official_vivek" }, { "code": null, "e": 26732, "s": 26721, "text": "vikkycirus" }, { "code": null, "e": 26749, "s": 26732, "text": "arorakashish0911" }, { "code": null, "e": 26757, "s": 26749, "text": "HashSet" }, { "code": null, "e": 26768, "s": 26757, "text": "python-set" }, { "code": null, "e": 26773, "s": 26768, "text": "Hash" }, { "code": null, "e": 26780, "s": 26773, "text": "Python" }, { "code": null, "e": 26788, "s": 26780, "text": "Strings" }, { "code": null, "e": 26807, "s": 26788, "text": "Technical Scripter" }, { "code": null, "e": 26818, "s": 26807, "text": "python-set" }, { "code": null, "e": 26823, "s": 26818, "text": "Hash" }, { "code": null, "e": 26831, "s": 26823, "text": "Strings" }, { "code": null, "e": 26929, "s": 26831, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26938, "s": 26929, "text": "Comments" }, { "code": null, "e": 26951, "s": 26938, "text": "Old Comments" }, { "code": null, "e": 26980, "s": 26951, "text": "Quadratic Probing in Hashing" }, { "code": null, "e": 27020, "s": 26980, "text": "Rearrange an array such that arr[i] = i" }, { "code": null, "e": 27036, "s": 27020, "text": "Hashing in Java" }, { "code": null, "e": 27062, "s": 27036, "text": "Load Factor and Rehashing" }, { "code": null, "e": 27110, "s": 27062, "text": "Hash Functions and list/types of Hash functions" }, { "code": null, "e": 27138, "s": 27110, "text": "Read JSON file using Python" }, { "code": null, "e": 27188, "s": 27138, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 27210, "s": 27188, "text": "Python map() function" } ]
MFC - Linked Lists
A linked list is a linear data structure where each element is a separate object. Each element (we will call it a node) of a list comprises two items — the data and a reference to the next node. The last node has a reference to null. A linked list is a data structure consisting of a group of nodes which together represent a sequence. It is a way to store data with structures so that the programmer can automatically create a new place to store data whenever necessary. Some of its salient features are − Linked List is a sequence of links which contains items. Linked List is a sequence of links which contains items. Each link contains a connection to another link. Each link contains a connection to another link. Each item in the list is called a node. Each item in the list is called a node. If the list contains at least one node, then a new node is positioned as the last element in the list. If the list contains at least one node, then a new node is positioned as the last element in the list. If the list has only one node, that node represents the first and the last item. If the list has only one node, that node represents the first and the last item. There are two types of link list − Singly Linked Lists are a type of data structure. In a singly linked list, each node in the list stores the contents of the node and a pointer or reference to the next node in the list. A doubly linked list is a linked data structure that consists of a set of sequentially linked records called nodes. Each node contains two fields that are references to the previous and to the next node in the sequence of nodes. MFC provides a class CList which is a template linked list implementation and works perfectly. CList lists behave like doubly-linked lists. A variable of type POSITION is a key for the list. You can use a POSITION variable as an iterator to traverse a list sequentially and as a bookmark to hold a place. AddHead Adds an element (or all the elements in another list) to the head of the list (makes a new head). AddTail Adds an element (or all the elements in another list) to the tail of the list (makes a new tail). Find Gets the position of an element specified by pointer value. FindIndex Gets the position of an element specified by a zero-based index. GetAt Gets the element at a given position. GetCount Returns the number of elements in this list. GetHead Returns the head element of the list (cannot be empty). GetHeadPosition Returns the position of the head element of the list. GetNext Gets the next element for iterating. GetPrev Gets the previous element for iterating. GetSize Returns the number of elements in this list. GetTail Returns the tail element of the list (cannot be empty). GetTailPosition Returns the position of the tail element of the list. InsertAfter Inserts a new element after a given position. InsertBefore Inserts a new element before a given position. IsEmpty Tests for the empty list condition (no elements). RemoveAll Removes all the elements from this list. RemoveAt Removes an element from this list, specified by position. RemoveHead Removes the element from the head of the list. RemoveTail Removes the element from the tail of the list. SetAt Sets the element at a given position. Following are the different operations on CList objects − To create a collection of CList values or objects, you must first decide the type of values of the collection. You can use one of the existing primitive data types such as int, CString, double etc. as shown below in the following code. CList<double, double>m_list; To add an item, you can use CList::AddTail() function. It adds an item at the end of the list. To add an element at the start of the list, you can use the CList::AddHead() function. In the OnInitDialog() CList, object is created and four values are added as shown in the following code. CList<double, double>m_list; //Add items to the list m_list.AddTail(100.75); m_list.AddTail(85.26); m_list.AddTail(95.78); m_list.AddTail(90.1); A variable of type POSITION is a key for the list. You can use a POSITION variable as an iterator to traverse a list sequentially. Step 1 − To retrieve the element from the list, we can use the following code which will retrieve all the values. //iterate the list POSITION pos = m_list.GetHeadPosition(); while (pos) { double nData = m_list.GetNext(pos); CString strVal; strVal.Format(L"%.2f\n", nData); m_strText.Append(strVal); } Step 2 − Here is the complete CMFCCListDemoDlg::OnInitDialog() function. BOOL CMFCCListDemoDlg::OnInitDialog() { CDialogEx::OnInitDialog(); // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon // TODO: Add extra initialization here CList<double, double>m_list; //Add items to the list m_list.AddTail(100.75); m_list.AddTail(85.26); m_list.AddTail(95.78); m_list.AddTail(90.1); //iterate the list POSITION pos = m_list.GetHeadPosition(); while (pos) { double nData = m_list.GetNext(pos); CString strVal; strVal.Format(L"%.f\n", nData); m_strText.Append(strVal); } UpdateData(FALSE); return TRUE; // return TRUE unless you set the focus to a control } Step 3 − When the above code is compiled and executed, you will see the following output. To add item in the middle of the list, you can use the CList::.InsertAfter() and CList::.InsertBefore() functions. It takes two paramerters — First, the position (where it can be added) and Second, the value. Step 1 − Let us insert a new item as shown in the followng code. BOOL CMFCCListDemoDlg::OnInitDialog() { CDialogEx::OnInitDialog(); // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon // TODO: Add extra initialization here CList<double, double>m_list; //Add items to the list m_list.AddTail(100.75); m_list.AddTail(85.26); m_list.AddTail(95.78); m_list.AddTail(90.1); POSITION position = m_list.Find(85.26); m_list.InsertBefore(position, 200.0); m_list.InsertAfter(position, 300.0); //iterate the list POSITION pos = m_list.GetHeadPosition(); while (pos) { double nData = m_list.GetNext(pos); CString strVal; strVal.Format(L"%.2f\n", nData); m_strText.Append(strVal); } UpdateData(FALSE); return TRUE; // return TRUE unless you set the focus to a control } Step 2 − You can now see see that we first retrieved the position of value 85.26 and then inserted one element before and one element after that value. Step 3 − When the above code is compiled and executed, you will see the following output. To update item at the middle of array, you can use the CArray::.SetAt() function. It takes two paramerters — First, the position and Second, the value. Let us update the 300.00 to 400 in the list as shown in the following code. BOOL CMFCCListDemoDlg::OnInitDialog() { CDialogEx::OnInitDialog(); // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon // TODO: Add extra initialization here CList<double, double>m_list; //Add items to the list m_list.AddTail(100.75); m_list.AddTail(85.26); m_list.AddTail(95.78); m_list.AddTail(90.1); POSITION position = m_list.Find(85.26); m_list.InsertBefore(position, 200.0); m_list.InsertAfter(position, 300.0); position = m_list.Find(300.00); m_list.SetAt(position, 400.00); //iterate the list POSITION pos = m_list.GetHeadPosition(); while (pos) { double nData = m_list.GetNext(pos); CString strVal; strVal.Format(L"%.2f\n", nData); m_strText.Append(strVal); } UpdateData(FALSE); return TRUE; // return TRUE unless you set the focus to a control } When the above code is compiled and executed, you will see the following output. You can now see that the value of 300.00 is updated to 400.00. To remove any particular item, you can use CList::RemoveAt() function. To remove all the element from the list, CList::RemoveAll() function can be used. Let us remove the element, which has 95.78 as its value. BOOL CMFCCListDemoDlg::OnInitDialog() { CDialogEx::OnInitDialog(); // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon // TODO: Add extra initialization here CList<double, double>m_list; //Add items to the list m_list.AddTail(100.75); m_list.AddTail(85.26); m_list.AddTail(95.78); m_list.AddTail(90.1); POSITION position = m_list.Find(85.26); m_list.InsertBefore(position, 200.0); m_list.InsertAfter(position, 300.0); position = m_list.Find(300.00); m_list.SetAt(position, 400.00); position = m_list.Find(95.78); m_list.RemoveAt(position); //iterate the list POSITION pos = m_list.GetHeadPosition(); while (pos) { double nData = m_list.GetNext(pos); CString strVal; strVal.Format(L"%.2f\n", nData); m_strText.Append(strVal); } UpdateData(FALSE); return TRUE; // return TRUE unless you set the focus to a control } When the above code is compiled and executed, you will see the following output. You can now see that the value of 95.78 is no longer part of the list. Print Add Notes Bookmark this page
[ { "code": null, "e": 2301, "s": 2067, "text": "A linked list is a linear data structure where each element is a separate object. Each element (we will call it a node) of a list comprises two items — the data and a reference to the next node. The last node has a reference to null." }, { "code": null, "e": 2574, "s": 2301, "text": "A linked list is a data structure consisting of a group of nodes which together represent a sequence. It is a way to store data with structures so that the programmer can automatically create a new place to store data whenever necessary. Some of its salient features are −" }, { "code": null, "e": 2631, "s": 2574, "text": "Linked List is a sequence of links which contains items." }, { "code": null, "e": 2688, "s": 2631, "text": "Linked List is a sequence of links which contains items." }, { "code": null, "e": 2737, "s": 2688, "text": "Each link contains a connection to another link." }, { "code": null, "e": 2786, "s": 2737, "text": "Each link contains a connection to another link." }, { "code": null, "e": 2826, "s": 2786, "text": "Each item in the list is called a node." }, { "code": null, "e": 2866, "s": 2826, "text": "Each item in the list is called a node." }, { "code": null, "e": 2969, "s": 2866, "text": "If the list contains at least one node, then a new node is positioned as the last element in the list." }, { "code": null, "e": 3072, "s": 2969, "text": "If the list contains at least one node, then a new node is positioned as the last element in the list." }, { "code": null, "e": 3153, "s": 3072, "text": "If the list has only one node, that node represents the first and the last item." }, { "code": null, "e": 3234, "s": 3153, "text": "If the list has only one node, that node represents the first and the last item." }, { "code": null, "e": 3269, "s": 3234, "text": "There are two types of link list −" }, { "code": null, "e": 3455, "s": 3269, "text": "Singly Linked Lists are a type of data structure. In a singly linked list, each node in the list stores the contents of the node and a pointer or reference to the next node in the list." }, { "code": null, "e": 3684, "s": 3455, "text": "A doubly linked list is a linked data structure that consists of a set of sequentially linked records called nodes. Each node contains two fields that are references to the previous and to the next node in the sequence of nodes." }, { "code": null, "e": 3989, "s": 3684, "text": "MFC provides a class CList which is a template linked list implementation and works perfectly. CList lists behave like doubly-linked lists. A variable of type POSITION is a key for the list. You can use a POSITION variable as an iterator to traverse a list sequentially and as a bookmark to hold a place." }, { "code": null, "e": 3997, "s": 3989, "text": "AddHead" }, { "code": null, "e": 4095, "s": 3997, "text": "Adds an element (or all the elements in another list) to the head of the list (makes a new head)." }, { "code": null, "e": 4103, "s": 4095, "text": "AddTail" }, { "code": null, "e": 4201, "s": 4103, "text": "Adds an element (or all the elements in another list) to the tail of the list (makes a new tail)." }, { "code": null, "e": 4206, "s": 4201, "text": "Find" }, { "code": null, "e": 4266, "s": 4206, "text": "Gets the position of an element specified by pointer value." }, { "code": null, "e": 4276, "s": 4266, "text": "FindIndex" }, { "code": null, "e": 4341, "s": 4276, "text": "Gets the position of an element specified by a zero-based index." }, { "code": null, "e": 4347, "s": 4341, "text": "GetAt" }, { "code": null, "e": 4385, "s": 4347, "text": "Gets the element at a given position." }, { "code": null, "e": 4394, "s": 4385, "text": "GetCount" }, { "code": null, "e": 4439, "s": 4394, "text": "Returns the number of elements in this list." }, { "code": null, "e": 4447, "s": 4439, "text": "GetHead" }, { "code": null, "e": 4503, "s": 4447, "text": "Returns the head element of the list (cannot be empty)." }, { "code": null, "e": 4519, "s": 4503, "text": "GetHeadPosition" }, { "code": null, "e": 4573, "s": 4519, "text": "Returns the position of the head element of the list." }, { "code": null, "e": 4581, "s": 4573, "text": "GetNext" }, { "code": null, "e": 4618, "s": 4581, "text": "Gets the next element for iterating." }, { "code": null, "e": 4626, "s": 4618, "text": "GetPrev" }, { "code": null, "e": 4667, "s": 4626, "text": "Gets the previous element for iterating." }, { "code": null, "e": 4675, "s": 4667, "text": "GetSize" }, { "code": null, "e": 4720, "s": 4675, "text": "Returns the number of elements in this list." }, { "code": null, "e": 4728, "s": 4720, "text": "GetTail" }, { "code": null, "e": 4784, "s": 4728, "text": "Returns the tail element of the list (cannot be empty)." }, { "code": null, "e": 4800, "s": 4784, "text": "GetTailPosition" }, { "code": null, "e": 4854, "s": 4800, "text": "Returns the position of the tail element of the list." }, { "code": null, "e": 4866, "s": 4854, "text": "InsertAfter" }, { "code": null, "e": 4912, "s": 4866, "text": "Inserts a new element after a given position." }, { "code": null, "e": 4925, "s": 4912, "text": "InsertBefore" }, { "code": null, "e": 4972, "s": 4925, "text": "Inserts a new element before a given position." }, { "code": null, "e": 4980, "s": 4972, "text": "IsEmpty" }, { "code": null, "e": 5030, "s": 4980, "text": "Tests for the empty list condition (no elements)." }, { "code": null, "e": 5040, "s": 5030, "text": "RemoveAll" }, { "code": null, "e": 5081, "s": 5040, "text": "Removes all the elements from this list." }, { "code": null, "e": 5090, "s": 5081, "text": "RemoveAt" }, { "code": null, "e": 5148, "s": 5090, "text": "Removes an element from this list, specified by position." }, { "code": null, "e": 5159, "s": 5148, "text": "RemoveHead" }, { "code": null, "e": 5206, "s": 5159, "text": "Removes the element from the head of the list." }, { "code": null, "e": 5217, "s": 5206, "text": "RemoveTail" }, { "code": null, "e": 5264, "s": 5217, "text": "Removes the element from the tail of the list." }, { "code": null, "e": 5270, "s": 5264, "text": "SetAt" }, { "code": null, "e": 5308, "s": 5270, "text": "Sets the element at a given position." }, { "code": null, "e": 5366, "s": 5308, "text": "Following are the different operations on CList objects −" }, { "code": null, "e": 5602, "s": 5366, "text": "To create a collection of CList values or objects, you must first decide the type of values of the collection. You can use one of the existing primitive data types such as int, CString, double etc. as shown below in the following code." }, { "code": null, "e": 5631, "s": 5602, "text": "CList<double, double>m_list;" }, { "code": null, "e": 5918, "s": 5631, "text": "To add an item, you can use CList::AddTail() function. It adds an item at the end of the list. To add an element at the start of the list, you can use the CList::AddHead() function. In the OnInitDialog() CList, object is created and four values are added as shown in the following code." }, { "code": null, "e": 6065, "s": 5918, "text": "CList<double, double>m_list;\n\n//Add items to the list\nm_list.AddTail(100.75);\nm_list.AddTail(85.26);\nm_list.AddTail(95.78);\nm_list.AddTail(90.1);\n" }, { "code": null, "e": 6196, "s": 6065, "text": "A variable of type POSITION is a key for the list. You can use a POSITION variable as an iterator to traverse a list sequentially." }, { "code": null, "e": 6310, "s": 6196, "text": "Step 1 − To retrieve the element from the list, we can use the following code which will retrieve all the values." }, { "code": null, "e": 6510, "s": 6310, "text": "//iterate the list\nPOSITION pos = m_list.GetHeadPosition();\nwhile (pos) { \n double nData = m_list.GetNext(pos);\n CString strVal;\n strVal.Format(L\"%.2f\\n\", nData);\n m_strText.Append(strVal);\n}" }, { "code": null, "e": 6583, "s": 6510, "text": "Step 2 − Here is the complete CMFCCListDemoDlg::OnInitDialog() function." }, { "code": null, "e": 7424, "s": 6583, "text": "BOOL CMFCCListDemoDlg::OnInitDialog() {\n CDialogEx::OnInitDialog();\n\n // Set the icon for this dialog. The framework does this automatically\n // when the application's main window is not a dialog\n SetIcon(m_hIcon, TRUE); // Set big icon\n SetIcon(m_hIcon, FALSE); // Set small icon\n\n // TODO: Add extra initialization here\n CList<double, double>m_list;\n\n //Add items to the list\n m_list.AddTail(100.75);\n m_list.AddTail(85.26);\n m_list.AddTail(95.78);\n m_list.AddTail(90.1);\n\n //iterate the list\n POSITION pos = m_list.GetHeadPosition();\n while (pos) {\n double nData = m_list.GetNext(pos);\n CString strVal;\n strVal.Format(L\"%.f\\n\", nData);\n m_strText.Append(strVal);\n }\n\n UpdateData(FALSE);\n \n return TRUE; // return TRUE unless you set the focus to a control\n}" }, { "code": null, "e": 7514, "s": 7424, "text": "Step 3 − When the above code is compiled and executed, you will see the following output." }, { "code": null, "e": 7723, "s": 7514, "text": "To add item in the middle of the list, you can use the CList::.InsertAfter() and CList::.InsertBefore() functions. It takes two paramerters — First, the position (where it can be added) and Second, the value." }, { "code": null, "e": 7788, "s": 7723, "text": "Step 1 − Let us insert a new item as shown in the followng code." }, { "code": null, "e": 8754, "s": 7788, "text": "BOOL CMFCCListDemoDlg::OnInitDialog() {\n CDialogEx::OnInitDialog();\n \n // Set the icon for this dialog. The framework does this automatically\n // when the application's main window is not a dialog\n SetIcon(m_hIcon, TRUE); // Set big icon\n SetIcon(m_hIcon, FALSE); // Set small icon\n\n // TODO: Add extra initialization here\n CList<double, double>m_list;\n\n //Add items to the list\n m_list.AddTail(100.75);\n m_list.AddTail(85.26);\n m_list.AddTail(95.78);\n m_list.AddTail(90.1);\n\n POSITION position = m_list.Find(85.26);\n m_list.InsertBefore(position, 200.0);\n m_list.InsertAfter(position, 300.0);\n\n //iterate the list\n POSITION pos = m_list.GetHeadPosition();\n while (pos) {\n double nData = m_list.GetNext(pos);\n CString strVal;\n strVal.Format(L\"%.2f\\n\", nData);\n m_strText.Append(strVal);\n }\n\n UpdateData(FALSE);\n\n return TRUE; // return TRUE unless you set the focus to a control\n}" }, { "code": null, "e": 8906, "s": 8754, "text": "Step 2 − You can now see see that we first retrieved the position of value 85.26 and then inserted one element before and one element after that value." }, { "code": null, "e": 8996, "s": 8906, "text": "Step 3 − When the above code is compiled and executed, you will see the following output." }, { "code": null, "e": 9148, "s": 8996, "text": "To update item at the middle of array, you can use the CArray::.SetAt() function. It takes two paramerters — First, the position and Second, the value." }, { "code": null, "e": 9224, "s": 9148, "text": "Let us update the 300.00 to 400 in the list as shown in the following code." }, { "code": null, "e": 10261, "s": 9224, "text": "BOOL CMFCCListDemoDlg::OnInitDialog() {\n CDialogEx::OnInitDialog();\n\n // Set the icon for this dialog. The framework does this automatically\n // when the application's main window is not a dialog\n SetIcon(m_hIcon, TRUE); // Set big icon\n SetIcon(m_hIcon, FALSE); // Set small icon\n\n // TODO: Add extra initialization here\n CList<double, double>m_list;\n\n //Add items to the list\n m_list.AddTail(100.75);\n m_list.AddTail(85.26);\n m_list.AddTail(95.78);\n m_list.AddTail(90.1);\n\n POSITION position = m_list.Find(85.26);\n m_list.InsertBefore(position, 200.0);\n m_list.InsertAfter(position, 300.0);\n\n position = m_list.Find(300.00);\n m_list.SetAt(position, 400.00);\n\n //iterate the list\n POSITION pos = m_list.GetHeadPosition();\n while (pos) {\n double nData = m_list.GetNext(pos);\n CString strVal;\n strVal.Format(L\"%.2f\\n\", nData);\n m_strText.Append(strVal);\n }\n\n UpdateData(FALSE);\n\n return TRUE; // return TRUE unless you set the focus to a control\n}" }, { "code": null, "e": 10405, "s": 10261, "text": "When the above code is compiled and executed, you will see the following output. You can now see that the value of 300.00 is updated to 400.00." }, { "code": null, "e": 10558, "s": 10405, "text": "To remove any particular item, you can use CList::RemoveAt() function. To remove all the element from the list, CList::RemoveAll() function can be used." }, { "code": null, "e": 10615, "s": 10558, "text": "Let us remove the element, which has 95.78 as its value." }, { "code": null, "e": 11723, "s": 10615, "text": "BOOL CMFCCListDemoDlg::OnInitDialog() {\n CDialogEx::OnInitDialog();\n\n // Set the icon for this dialog. The framework does this automatically\n // when the application's main window is not a dialog\n SetIcon(m_hIcon, TRUE); // Set big icon\n SetIcon(m_hIcon, FALSE); // Set small icon\n\n // TODO: Add extra initialization here\n CList<double, double>m_list;\n\n //Add items to the list\n m_list.AddTail(100.75);\n m_list.AddTail(85.26);\n m_list.AddTail(95.78);\n m_list.AddTail(90.1);\n\n POSITION position = m_list.Find(85.26);\n m_list.InsertBefore(position, 200.0);\n m_list.InsertAfter(position, 300.0);\n \n position = m_list.Find(300.00);\n m_list.SetAt(position, 400.00);\n\n position = m_list.Find(95.78);\n m_list.RemoveAt(position);\n\n //iterate the list\n POSITION pos = m_list.GetHeadPosition();\n while (pos) {\n double nData = m_list.GetNext(pos);\n CString strVal;\n strVal.Format(L\"%.2f\\n\", nData);\n m_strText.Append(strVal);\n }\n UpdateData(FALSE);\n \n return TRUE; // return TRUE unless you set the focus to a control\n}" }, { "code": null, "e": 11875, "s": 11723, "text": "When the above code is compiled and executed, you will see the following output. You can now see that the value of 95.78 is no longer part of the list." }, { "code": null, "e": 11882, "s": 11875, "text": " Print" }, { "code": null, "e": 11893, "s": 11882, "text": " Add Notes" } ]
How to Change Font of Toolbar Title in an Android App? - GeeksforGeeks
23 Feb, 2021 Google Fonts provide a wide variety of fonts that can be used to style the text in Android Studio. Appropriate fonts do not just enhance the user interface but they also signify and emphasize the purpose of the text. In this article, you will learn how to change the font-family of the Toolbar Title in an Android App. In an Android app, the toolbar title preset at the upper part of the application. Below is a sample image that shows you where the toolbar title is present. There are two ways to change the font of the Toolbar Title. In method 1 Just go to the activity_main.xml file and add a TextView in the toolbar widget with the font-family attribute. The complete code for the activity_main.xml file is given below. 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"> <androidx.appcompat.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="#0F9D58"> <TextView android:id="@+id/custom_title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:fontFamily="sans-serif-smallcaps" android:text="GeeksForGeeks" android:textColor="#FFFFFF" android:textSize="20sp" android:textStyle="bold" /> </androidx.appcompat.widget.Toolbar> </RelativeLayout> Output UI: First, add a font file in the src/main/assets/fonts/ of your project. Then create variables for Toolbar and text title and call the method findViewById(). Create a new Typeface from the specified font data. And at last setTypeface in text title. Below is the complete code for the MainActivity.java/MainActivity.kt file. Java Kotlin import android.graphics.Typeface;import android.os.Bundle;import android.widget.TextView;import androidx.appcompat.app.AppCompatActivity;import androidx.appcompat.widget.Toolbar; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = findViewById(R.id.toolbar); // Custom title TextView textCustomTitle = (TextView) findViewById(R.id.custom_title); // Custom font Typeface customFont = Typeface.createFromAsset(this.getAssets(), "fonts/sans-serif-smallcaps.ttf"); // Set textCustomTitle.setTypeface(customFont); setSupportActionBar(toolbar); }} import android.graphics.Typefaceimport android.os.Bundleimport android.widget.TextViewimport androidx.appcompat.app.AppCompatActivityimport androidx.appcompat.widget.Toolbar class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val toolbar: Toolbar = findViewById(R.id.toolbar) // Custom title val textCustomTitle: TextView = findViewById(R.id.custom_title) // Custom font val customFont = Typeface.createFromAsset(this.assets, "fonts/sans-serif-smallcaps.ttf") // Set textCustomTitle.typeface = customFont setSupportActionBar(toolbar) }} The corresponding activity_main.xml file is given below. 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"> <androidx.appcompat.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary"> <TextView android:id="@+id/custom_title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="GeeksForGeeks" android:textColor="#FFFFFF" android:textSize="20sp" android:textStyle="bold" /> </androidx.appcompat.widget.Toolbar> </RelativeLayout> Output UI: namanjha10 Android-Bars Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Create and Add Data to SQLite Database in Android? Broadcast Receiver in Android With Example Services in Android with Example Content Providers in Android with Example Android RecyclerView in Kotlin 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": 24902, "s": 24874, "text": "\n23 Feb, 2021" }, { "code": null, "e": 25378, "s": 24902, "text": "Google Fonts provide a wide variety of fonts that can be used to style the text in Android Studio. Appropriate fonts do not just enhance the user interface but they also signify and emphasize the purpose of the text. In this article, you will learn how to change the font-family of the Toolbar Title in an Android App. In an Android app, the toolbar title preset at the upper part of the application. Below is a sample image that shows you where the toolbar title is present." }, { "code": null, "e": 25438, "s": 25378, "text": "There are two ways to change the font of the Toolbar Title." }, { "code": null, "e": 25626, "s": 25438, "text": "In method 1 Just go to the activity_main.xml file and add a TextView in the toolbar widget with the font-family attribute. The complete code for the activity_main.xml file is given below." }, { "code": null, "e": 25630, "s": 25626, "text": "XML" }, { "code": "<?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\"> <androidx.appcompat.widget.Toolbar android:id=\"@+id/toolbar\" android:layout_width=\"match_parent\" android:layout_height=\"?attr/actionBarSize\" android:background=\"#0F9D58\"> <TextView android:id=\"@+id/custom_title\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:fontFamily=\"sans-serif-smallcaps\" android:text=\"GeeksForGeeks\" android:textColor=\"#FFFFFF\" android:textSize=\"20sp\" android:textStyle=\"bold\" /> </androidx.appcompat.widget.Toolbar> </RelativeLayout>", "e": 26537, "s": 25630, "text": null }, { "code": null, "e": 26548, "s": 26537, "text": "Output UI:" }, { "code": null, "e": 26871, "s": 26548, "text": "First, add a font file in the src/main/assets/fonts/ of your project. Then create variables for Toolbar and text title and call the method findViewById(). Create a new Typeface from the specified font data. And at last setTypeface in text title. Below is the complete code for the MainActivity.java/MainActivity.kt file. " }, { "code": null, "e": 26876, "s": 26871, "text": "Java" }, { "code": null, "e": 26883, "s": 26876, "text": "Kotlin" }, { "code": "import android.graphics.Typeface;import android.os.Bundle;import android.widget.TextView;import androidx.appcompat.app.AppCompatActivity;import androidx.appcompat.widget.Toolbar; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = findViewById(R.id.toolbar); // Custom title TextView textCustomTitle = (TextView) findViewById(R.id.custom_title); // Custom font Typeface customFont = Typeface.createFromAsset(this.getAssets(), \"fonts/sans-serif-smallcaps.ttf\"); // Set textCustomTitle.setTypeface(customFont); setSupportActionBar(toolbar); }}", "e": 27674, "s": 26883, "text": null }, { "code": "import android.graphics.Typefaceimport android.os.Bundleimport android.widget.TextViewimport androidx.appcompat.app.AppCompatActivityimport androidx.appcompat.widget.Toolbar class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val toolbar: Toolbar = findViewById(R.id.toolbar) // Custom title val textCustomTitle: TextView = findViewById(R.id.custom_title) // Custom font val customFont = Typeface.createFromAsset(this.assets, \"fonts/sans-serif-smallcaps.ttf\") // Set textCustomTitle.typeface = customFont setSupportActionBar(toolbar) }}", "e": 28414, "s": 27674, "text": null }, { "code": null, "e": 28473, "s": 28414, "text": "The corresponding activity_main.xml file is given below. " }, { "code": null, "e": 28477, "s": 28473, "text": "XML" }, { "code": "<?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\"> <androidx.appcompat.widget.Toolbar android:id=\"@+id/toolbar\" android:layout_width=\"match_parent\" android:layout_height=\"?attr/actionBarSize\" android:background=\"?attr/colorPrimary\"> <TextView android:id=\"@+id/custom_title\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"GeeksForGeeks\" android:textColor=\"#FFFFFF\" android:textSize=\"20sp\" android:textStyle=\"bold\" /> </androidx.appcompat.widget.Toolbar> </RelativeLayout>", "e": 29342, "s": 28477, "text": null }, { "code": null, "e": 29354, "s": 29342, "text": " Output UI:" }, { "code": null, "e": 29365, "s": 29354, "text": "namanjha10" }, { "code": null, "e": 29378, "s": 29365, "text": "Android-Bars" }, { "code": null, "e": 29386, "s": 29378, "text": "Android" }, { "code": null, "e": 29391, "s": 29386, "text": "Java" }, { "code": null, "e": 29396, "s": 29391, "text": "Java" }, { "code": null, "e": 29404, "s": 29396, "text": "Android" }, { "code": null, "e": 29502, "s": 29404, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29511, "s": 29502, "text": "Comments" }, { "code": null, "e": 29524, "s": 29511, "text": "Old Comments" }, { "code": null, "e": 29582, "s": 29524, "text": "How to Create and Add Data to SQLite Database in Android?" }, { "code": null, "e": 29625, "s": 29582, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 29658, "s": 29625, "text": "Services in Android with Example" }, { "code": null, "e": 29700, "s": 29658, "text": "Content Providers in Android with Example" }, { "code": null, "e": 29731, "s": 29700, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 29746, "s": 29731, "text": "Arrays in Java" }, { "code": null, "e": 29790, "s": 29746, "text": "Split() String method in Java with examples" }, { "code": null, "e": 29812, "s": 29790, "text": "For-each loop in Java" }, { "code": null, "e": 29848, "s": 29812, "text": "Arrays.sort() in Java with examples" } ]
Export CSV File without Row Names in R - GeeksforGeeks
09 May, 2021 In this article, we will learn how to export CSV files without row names in R Programming Language. In R language we use write.csv() function to create a CSV file from the data. Syntax: write.csv(df, path) Parameters: df: dataframe object path: local path on your system where .csv file will be written/saved. For this, we have to create a dataframe with the required values and then export values to a dataframe on the provided path. If the file doesn’t exist it firsts create it. If it does, it will be overwritten. By default, the data is exported with row names. Let us see an example to understand better. Example: R df <- data.frame(c1 = 20:24, c2 = c(2021,2020,2019,2018,2017), c3 = rep("GFG", 5)) write.csv(df, "dataframe.csv") Output: Now to export data without row names we simply have to pass row.names=FALSE as an argument in the write.csv() function. Example: R df <- data.frame(c1 = 20:24, c2 = c(2021,2020,2019,2018,2017), c3 = rep("GFG", 5)) write.csv(df, "dataframe.csv", row.names=FALSE) Output: Picked R-CSV R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Control Statements in R Programming Change Color of Bars in Barchart using ggplot2 in R Data Visualization in R Group by function in R using Dplyr How to Change Axis Scales in R Plots? Logistic Regression in R Programming How to change Colors in ggplot2 Line Plot in R ? How to filter R DataFrame by values in a column? Linear Discriminant Analysis in R Programming R - Operators
[ { "code": null, "e": 24851, "s": 24823, "text": "\n09 May, 2021" }, { "code": null, "e": 25030, "s": 24851, "text": "In this article, we will learn how to export CSV files without row names in R Programming Language. In R language we use write.csv() function to create a CSV file from the data. " }, { "code": null, "e": 25059, "s": 25030, "text": "Syntax: write.csv(df, path) " }, { "code": null, "e": 25071, "s": 25059, "text": "Parameters:" }, { "code": null, "e": 25092, "s": 25071, "text": "df: dataframe object" }, { "code": null, "e": 25163, "s": 25092, "text": "path: local path on your system where .csv file will be written/saved." }, { "code": null, "e": 25371, "s": 25163, "text": "For this, we have to create a dataframe with the required values and then export values to a dataframe on the provided path. If the file doesn’t exist it firsts create it. If it does, it will be overwritten." }, { "code": null, "e": 25464, "s": 25371, "text": "By default, the data is exported with row names. Let us see an example to understand better." }, { "code": null, "e": 25473, "s": 25464, "text": "Example:" }, { "code": null, "e": 25475, "s": 25473, "text": "R" }, { "code": "df <- data.frame(c1 = 20:24, c2 = c(2021,2020,2019,2018,2017), c3 = rep(\"GFG\", 5)) write.csv(df, \"dataframe.csv\")", "e": 25645, "s": 25475, "text": null }, { "code": null, "e": 25653, "s": 25645, "text": "Output:" }, { "code": null, "e": 25773, "s": 25653, "text": "Now to export data without row names we simply have to pass row.names=FALSE as an argument in the write.csv() function." }, { "code": null, "e": 25782, "s": 25773, "text": "Example:" }, { "code": null, "e": 25784, "s": 25782, "text": "R" }, { "code": "df <- data.frame(c1 = 20:24, c2 = c(2021,2020,2019,2018,2017), c3 = rep(\"GFG\", 5)) write.csv(df, \"dataframe.csv\", row.names=FALSE)", "e": 25971, "s": 25784, "text": null }, { "code": null, "e": 25979, "s": 25971, "text": "Output:" }, { "code": null, "e": 25986, "s": 25979, "text": "Picked" }, { "code": null, "e": 25992, "s": 25986, "text": "R-CSV" }, { "code": null, "e": 26003, "s": 25992, "text": "R Language" }, { "code": null, "e": 26101, "s": 26003, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26110, "s": 26101, "text": "Comments" }, { "code": null, "e": 26123, "s": 26110, "text": "Old Comments" }, { "code": null, "e": 26159, "s": 26123, "text": "Control Statements in R Programming" }, { "code": null, "e": 26211, "s": 26159, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 26235, "s": 26211, "text": "Data Visualization in R" }, { "code": null, "e": 26270, "s": 26235, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 26308, "s": 26270, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 26345, "s": 26308, "text": "Logistic Regression in R Programming" }, { "code": null, "e": 26394, "s": 26345, "text": "How to change Colors in ggplot2 Line Plot in R ?" }, { "code": null, "e": 26443, "s": 26394, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 26489, "s": 26443, "text": "Linear Discriminant Analysis in R Programming" } ]
How to create a hyperlink to link another document in HTML?
Use the <a> tag to create a hyperlink. The HTML <a> tag is used for creating a hyperlink either to another document, or somewhere within the current document. The following are the attributes − You can try to run the following code to create a link − <!DOCTYPE html> <html> <head> <title>HTML a Tag</title> </head> <body> <p>This is a link to <a href = "https://qries.com">Qries.com</a></p> </body> </html>
[ { "code": null, "e": 1221, "s": 1062, "text": "Use the <a> tag to create a hyperlink. The HTML <a> tag is used for creating a hyperlink either to another document, or somewhere within the current document." }, { "code": null, "e": 1256, "s": 1221, "text": "The following are the attributes −" }, { "code": null, "e": 1313, "s": 1256, "text": "You can try to run the following code to create a link −" }, { "code": null, "e": 1493, "s": 1313, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>HTML a Tag</title>\n </head>\n <body>\n <p>This is a link to <a href = \"https://qries.com\">Qries.com</a></p>\n </body>\n</html>" } ]
Most Important Pandas Functions(Full Tutorial)| Towards Data Science | Towards Data Science
Pandas is one of the most popular python libraries used for data manipulation and analysis. It enables a variety of reading functions for a wide range of data formats, commands to best select the subset you want to analyze. It provides a variety of tools for data manipulation such as merging, joining and concatenation. In this post, we will focus on discovering pandas most important functions and commands which are most used to explore the dataset and unveil the underlying relationships among variables. This post is an attempt to mark out the different functions and commands available by the library all in a single post . Importing DataViewing & Selecting DataStatistics & Simple Data OperationsDealing with Missing valuesData Manipulation Importing Data Viewing & Selecting Data Statistics & Simple Data Operations Dealing with Missing values Data Manipulation I will use a customer churn dataset for the examples. The first step is to read the dataset into a pandas data frame. Before starting going through functions and implementations, I would like to emphasize the importance of Understanding the Axis and the Inplace parameter. A DataFrame object has two axes: “axis 0” and “axis 1”: axis 0: Wherever you see this -> it represents rows axis 1: Wherever you see this -> it represents columns Understanding the “inplace” parameter can help us a lot of time and memory! When inplace = False -> which is the default, then the operation is performed and it returns a copy of the object. You then need to save it to something. temp=df.set_index(‘CustomerId’)# here by Default inplace = Falsetemp While , When inplace = True -> the data is modified in place, which means it will return nothing and the dataframe is now updated. df.set_index(‘CustomerId’,inplace=True)df import pandas as pdimport numpy as nppd.set_option('display.max_columns', None)pd.set_option("display.precision", 2) df = pd.read_csv("Churn_Modelling.csv") # import from a CSV Use these commands to take a look at specific sections of your pandas DataFrame or Series. df.head(5) -> First 5 rows of the DataFrame df.tail(5) -> Last 5 rows of the DataFrame df.shape -> Return the number of rows and columns df.info() ->Return Index, Datatype and Memory information Now, Let‘s find out which functions and commands are best used to select a specific subset of your data. df['Gender'] or df.Gender ->Returns column with label col as Series df[['Gender', 'Age','Balance]] -> Returns columns as a new DataFrame loc is label-based, which means that we have to specify the name of the rows and columns that we need to filter out. df.loc[1:5] -> Select a range of rows using loc. Note: if the indices are not numbers, then we cannot slice our data frame. In that case, we need to use the iloc function. df.loc[df.Age>=45] -> Select only required columns with a condition # Some more examples- df.loc[0] # forst row details - df.loc[:,"Gender"] # Selects all rows of the Gender column as a series- df.loc[:,"Balance":"HasCrCard"] # Selects all rows of the columns going from Balance to HasCrCard iloc is integer index-based , we have to specify rows and columns by their integer index. df.iloc[[100,200]] -> Selecting Rows 100 & 200 Note that: Another thing to remember in iloc are the indexes: for instance: df.iloc[1:5] - 1 is inclusive - 5 is exclusive, meaning it won’t print it the 5th row instead it will return the the previous row -> it will go from 1 to (5–1);check out the below example df.iloc[15:20,3:7]-> Select a range of rows and columns using iloc df.iloc[20][2]-> Accessing the [3rd ]element of the [20th] row # Some more examples- df.iloc[0:3] # 0 is inclusive and 3 is exclusive - df.iloc[15:20,'Gender':] -> the latter will give an error since we are passing a label rather than index Use these commands to perform descriptive statistical analysis. df.describe() -> Summary statistics for numerical columns df.mean() -> Returns the mean of all columns df.corr() -> Returns the correlation between columns in theDataFrame df.count() -> Returns the number of non-null values in each DataFrame column df['Geography'].unique() -> Return the list of unique values in the column df['Geography'].nunique() ->Return how many unique values are present in such feature/column df['Gender'].value_counts(dropna=False) | View unique values and counts df.sample(n=10) -> Randomly select 10 rows df.nlargest(5,'Balance') ->Select and order top n entries. df.nsmallest(5,'EstimatedSalary')->Select and order bottom n entries df.query("(Gender=='Male') and (Age<23)") ->Query the columns of a DataFrame with a boolean expression Where function will replace values where your condition is False. It is useful when you have values that do not meet criteria, and they need replacing. df['Age'].where(df['Age']>40,"too Young") -> if df[‘Age’]>40 is false it will substitute with ‘Less than fourty’ df['Age']=df['Age'].astype(float) -> Convert the datatype of the Age “series” to float64 df['HasCrCard'].replace(1,'yes') -> Replace all values equal to 1 with 'yes' df.rename('columns={'Geography':'Nation'}) -> renaming the Geography column into Nation df.reset_index() ->reset index of DataFrame to row numbers, moving index to columns. Let‘s find out which functions and commands are best used to deal with missing values. df.isnull()or df.isna() -> Checks for null Values, Returns Boolean Arrray df.notnull() or df.notna()-> Opposite of df.isnull() df.isnull().sum() -> returns the sum of null values of every single feature/column The Dataset we are currently using as we see above has got no missing values. Use these commands and functions to drop columns and raws with missing values, dropping duplicates and columns. df.dropna()-> Drop all rows that contain null values df.dropna(axis=1) -> Drop all columns that contain null values df.dropna(axis=1,thresh=n) -> Drop all rows have have less than n non null values df.drop_duplicates() -> Remove duplicate rows (only considers columns). df.drop(['RowNumber', 'Surname'],axis=1, inplace=True).head(5) -> Return the dataframe after dropping the the two specified columns df.fillna(x) -> Replace all null values with x Use these commands to sort, filter and group your data. df.sort_values('Balance') -> Sort values of the Balance column in ascending order df.sort_values('EstimatedSalary',ascending=False) -> Sort values in descending order pd.Dataframe(df.sort_values(['Balance','EstimatedSalary'],ascending=[True,False])) -> Sort “Balance” column in ascending order & and Sort “EstimatedSalary” in descending order df[(df['CreditScore] > 700) & (df['CreditScore] < 900)].sort_values(['CreditScore'],ascending=True) — > Filter out CreditScore raws where values are from 700 to 900 and present them in ascending order Pandas Groupby function is a versatile and easy-to-use function that helps to get an overview of the data. df[['Gender','NumOfProducts']].groupby('Gender).mean() Data Aggregations refer to any data transformation that produces scalar values from arrays: (mean, count, min, and sum). df[['Gender','EstimatedSalary','Balance]].groupby(['Geography]).agg(['mean','max']) In order to group by multiple columns, we simply pass a list to our groupby function with the columns we want to groupby: df[['Gender','EstimatedSalary','Balance]].groupby(['Gender','Geography']).agg(['mean','count']) df.pivot_table(index='CreditScore',values=['Age','Balance']) -> Create a pivot table that groups by CreditScore and calculates the mean of Age and Balance pd.melt(df) -> Gather columns into rows Discretize variable into equal-sized buckets based on rank or based on sample quantiles. -Create a new Column[‘Salary_level”] using “pd.qcut” splitting EstimatedSalary into 5 different levels:[‘Bronze’, ‘Silver’, ‘Gold’, ‘Platinum’, ‘Diamond’] bin_labels_5 = [‘Bronze’, ‘Silver’, ‘Gold’, ‘Platinum’, ‘Diamond’]df[‘Salary_level’] = pd.qcut(df[‘EstimatedSalary’],q=[0, .2, .4, .6, .8, 1], labels=bin_labels_5) Use these commands to combine multiple data frames into a single one. df1.append(df2) -> Add the rows in df1 to the end of df2 (columns should be identical) pd.concat([df1, df2],axis=1) -> Add the columns in df1 to the end of df2 where rows are identical df1.join(df2 ,on=col1, how='inner') -> SQL-style join the columns in df1 with the columns on df2 where the rows for col have identical values. 'how' can be : 'left', 'right', 'outer', 'inner' You can do it with a simple code tudf.head(5).style.set_properties(**{'background-color': 'lightgreen'}, subset=['Balance','EstimatedSalary']) By adding the style function we can choose to set a colour to our columns and much more if you would like to know more about styling I would recommend the official pandas website: https://pandas.pydata.org/pandas-docs/stable/user_guide/style.html In this Beginner-friendly tutorial, I implemented some of the most important Pandas functions and command used for Data Analysis. I went over for every function different types of examples. I would recommend finding additional data sets and playing around with these functions and explore as much as you can, at the end of the day it is a matter of practice. Mastering Pandas is a great asset for whoever is on the path to becoming a Skillful Data Scientist/Data analyst/ Machine learning engineer ecc...you name it. I hope this post gives you a nice foundation for whoever is trying to master it, and for whoever has well crafted this art may this post works as a re-freshening. Thank you for reading!
[ { "code": null, "e": 681, "s": 172, "text": "Pandas is one of the most popular python libraries used for data manipulation and analysis. It enables a variety of reading functions for a wide range of data formats, commands to best select the subset you want to analyze. It provides a variety of tools for data manipulation such as merging, joining and concatenation. In this post, we will focus on discovering pandas most important functions and commands which are most used to explore the dataset and unveil the underlying relationships among variables." }, { "code": null, "e": 802, "s": 681, "text": "This post is an attempt to mark out the different functions and commands available by the library all in a single post ." }, { "code": null, "e": 920, "s": 802, "text": "Importing DataViewing & Selecting DataStatistics & Simple Data OperationsDealing with Missing valuesData Manipulation" }, { "code": null, "e": 935, "s": 920, "text": "Importing Data" }, { "code": null, "e": 960, "s": 935, "text": "Viewing & Selecting Data" }, { "code": null, "e": 996, "s": 960, "text": "Statistics & Simple Data Operations" }, { "code": null, "e": 1024, "s": 996, "text": "Dealing with Missing values" }, { "code": null, "e": 1042, "s": 1024, "text": "Data Manipulation" }, { "code": null, "e": 1160, "s": 1042, "text": "I will use a customer churn dataset for the examples. The first step is to read the dataset into a pandas data frame." }, { "code": null, "e": 1315, "s": 1160, "text": "Before starting going through functions and implementations, I would like to emphasize the importance of Understanding the Axis and the Inplace parameter." }, { "code": null, "e": 1371, "s": 1315, "text": "A DataFrame object has two axes: “axis 0” and “axis 1”:" }, { "code": null, "e": 1423, "s": 1371, "text": "axis 0: Wherever you see this -> it represents rows" }, { "code": null, "e": 1478, "s": 1423, "text": "axis 1: Wherever you see this -> it represents columns" }, { "code": null, "e": 1554, "s": 1478, "text": "Understanding the “inplace” parameter can help us a lot of time and memory!" }, { "code": null, "e": 1708, "s": 1554, "text": "When inplace = False -> which is the default, then the operation is performed and it returns a copy of the object. You then need to save it to something." }, { "code": null, "e": 1777, "s": 1708, "text": "temp=df.set_index(‘CustomerId’)# here by Default inplace = Falsetemp" }, { "code": null, "e": 1908, "s": 1777, "text": "While , When inplace = True -> the data is modified in place, which means it will return nothing and the dataframe is now updated." }, { "code": null, "e": 1950, "s": 1908, "text": "df.set_index(‘CustomerId’,inplace=True)df" }, { "code": null, "e": 2127, "s": 1950, "text": "import pandas as pdimport numpy as nppd.set_option('display.max_columns', None)pd.set_option(\"display.precision\", 2) df = pd.read_csv(\"Churn_Modelling.csv\") # import from a CSV" }, { "code": null, "e": 2218, "s": 2127, "text": "Use these commands to take a look at specific sections of your pandas DataFrame or Series." }, { "code": null, "e": 2262, "s": 2218, "text": "df.head(5) -> First 5 rows of the DataFrame" }, { "code": null, "e": 2305, "s": 2262, "text": "df.tail(5) -> Last 5 rows of the DataFrame" }, { "code": null, "e": 2355, "s": 2305, "text": "df.shape -> Return the number of rows and columns" }, { "code": null, "e": 2413, "s": 2355, "text": "df.info() ->Return Index, Datatype and Memory information" }, { "code": null, "e": 2518, "s": 2413, "text": "Now, Let‘s find out which functions and commands are best used to select a specific subset of your data." }, { "code": null, "e": 2586, "s": 2518, "text": "df['Gender'] or df.Gender ->Returns column with label col as Series" }, { "code": null, "e": 2655, "s": 2586, "text": "df[['Gender', 'Age','Balance]] -> Returns columns as a new DataFrame" }, { "code": null, "e": 2772, "s": 2655, "text": "loc is label-based, which means that we have to specify the name of the rows and columns that we need to filter out." }, { "code": null, "e": 2821, "s": 2772, "text": "df.loc[1:5] -> Select a range of rows using loc." }, { "code": null, "e": 2944, "s": 2821, "text": "Note: if the indices are not numbers, then we cannot slice our data frame. In that case, we need to use the iloc function." }, { "code": null, "e": 3012, "s": 2944, "text": "df.loc[df.Age>=45] -> Select only required columns with a condition" }, { "code": null, "e": 3291, "s": 3012, "text": "# Some more examples- df.loc[0] # forst row details - df.loc[:,\"Gender\"] # Selects all rows of the Gender column as a series- df.loc[:,\"Balance\":\"HasCrCard\"] # Selects all rows of the columns going from Balance to HasCrCard" }, { "code": null, "e": 3381, "s": 3291, "text": "iloc is integer index-based , we have to specify rows and columns by their integer index." }, { "code": null, "e": 3428, "s": 3381, "text": "df.iloc[[100,200]] -> Selecting Rows 100 & 200" }, { "code": null, "e": 3490, "s": 3428, "text": "Note that: Another thing to remember in iloc are the indexes:" }, { "code": null, "e": 3517, "s": 3490, "text": "for instance: df.iloc[1:5]" }, { "code": null, "e": 3534, "s": 3517, "text": "- 1 is inclusive" }, { "code": null, "e": 3692, "s": 3534, "text": "- 5 is exclusive, meaning it won’t print it the 5th row instead it will return the the previous row -> it will go from 1 to (5–1);check out the below example" }, { "code": null, "e": 3759, "s": 3692, "text": "df.iloc[15:20,3:7]-> Select a range of rows and columns using iloc" }, { "code": null, "e": 3822, "s": 3759, "text": "df.iloc[20][2]-> Accessing the [3rd ]element of the [20th] row" }, { "code": null, "e": 4002, "s": 3822, "text": "# Some more examples- df.iloc[0:3] # 0 is inclusive and 3 is exclusive - df.iloc[15:20,'Gender':] -> the latter will give an error since we are passing a label rather than index" }, { "code": null, "e": 4066, "s": 4002, "text": "Use these commands to perform descriptive statistical analysis." }, { "code": null, "e": 4124, "s": 4066, "text": "df.describe() -> Summary statistics for numerical columns" }, { "code": null, "e": 4169, "s": 4124, "text": "df.mean() -> Returns the mean of all columns" }, { "code": null, "e": 4238, "s": 4169, "text": "df.corr() -> Returns the correlation between columns in theDataFrame" }, { "code": null, "e": 4315, "s": 4238, "text": "df.count() -> Returns the number of non-null values in each DataFrame column" }, { "code": null, "e": 4390, "s": 4315, "text": "df['Geography'].unique() -> Return the list of unique values in the column" }, { "code": null, "e": 4483, "s": 4390, "text": "df['Geography'].nunique() ->Return how many unique values are present in such feature/column" }, { "code": null, "e": 4555, "s": 4483, "text": "df['Gender'].value_counts(dropna=False) | View unique values and counts" }, { "code": null, "e": 4598, "s": 4555, "text": "df.sample(n=10) -> Randomly select 10 rows" }, { "code": null, "e": 4657, "s": 4598, "text": "df.nlargest(5,'Balance') ->Select and order top n entries." }, { "code": null, "e": 4726, "s": 4657, "text": "df.nsmallest(5,'EstimatedSalary')->Select and order bottom n entries" }, { "code": null, "e": 4829, "s": 4726, "text": "df.query(\"(Gender=='Male') and (Age<23)\") ->Query the columns of a DataFrame with a boolean expression" }, { "code": null, "e": 4981, "s": 4829, "text": "Where function will replace values where your condition is False. It is useful when you have values that do not meet criteria, and they need replacing." }, { "code": null, "e": 5094, "s": 4981, "text": "df['Age'].where(df['Age']>40,\"too Young\") -> if df[‘Age’]>40 is false it will substitute with ‘Less than fourty’" }, { "code": null, "e": 5183, "s": 5094, "text": "df['Age']=df['Age'].astype(float) -> Convert the datatype of the Age “series” to float64" }, { "code": null, "e": 5260, "s": 5183, "text": "df['HasCrCard'].replace(1,'yes') -> Replace all values equal to 1 with 'yes'" }, { "code": null, "e": 5348, "s": 5260, "text": "df.rename('columns={'Geography':'Nation'}) -> renaming the Geography column into Nation" }, { "code": null, "e": 5433, "s": 5348, "text": "df.reset_index() ->reset index of DataFrame to row numbers, moving index to columns." }, { "code": null, "e": 5520, "s": 5433, "text": "Let‘s find out which functions and commands are best used to deal with missing values." }, { "code": null, "e": 5594, "s": 5520, "text": "df.isnull()or df.isna() -> Checks for null Values, Returns Boolean Arrray" }, { "code": null, "e": 5647, "s": 5594, "text": "df.notnull() or df.notna()-> Opposite of df.isnull()" }, { "code": null, "e": 5730, "s": 5647, "text": "df.isnull().sum() -> returns the sum of null values of every single feature/column" }, { "code": null, "e": 5808, "s": 5730, "text": "The Dataset we are currently using as we see above has got no missing values." }, { "code": null, "e": 5920, "s": 5808, "text": "Use these commands and functions to drop columns and raws with missing values, dropping duplicates and columns." }, { "code": null, "e": 5973, "s": 5920, "text": "df.dropna()-> Drop all rows that contain null values" }, { "code": null, "e": 6036, "s": 5973, "text": "df.dropna(axis=1) -> Drop all columns that contain null values" }, { "code": null, "e": 6118, "s": 6036, "text": "df.dropna(axis=1,thresh=n) -> Drop all rows have have less than n non null values" }, { "code": null, "e": 6190, "s": 6118, "text": "df.drop_duplicates() -> Remove duplicate rows (only considers columns)." }, { "code": null, "e": 6322, "s": 6190, "text": "df.drop(['RowNumber', 'Surname'],axis=1, inplace=True).head(5) -> Return the dataframe after dropping the the two specified columns" }, { "code": null, "e": 6369, "s": 6322, "text": "df.fillna(x) -> Replace all null values with x" }, { "code": null, "e": 6425, "s": 6369, "text": "Use these commands to sort, filter and group your data." }, { "code": null, "e": 6507, "s": 6425, "text": "df.sort_values('Balance') -> Sort values of the Balance column in ascending order" }, { "code": null, "e": 6592, "s": 6507, "text": "df.sort_values('EstimatedSalary',ascending=False) -> Sort values in descending order" }, { "code": null, "e": 6675, "s": 6592, "text": "pd.Dataframe(df.sort_values(['Balance','EstimatedSalary'],ascending=[True,False]))" }, { "code": null, "e": 6768, "s": 6675, "text": "-> Sort “Balance” column in ascending order & and Sort “EstimatedSalary” in descending order" }, { "code": null, "e": 6969, "s": 6768, "text": "df[(df['CreditScore] > 700) & (df['CreditScore] < 900)].sort_values(['CreditScore'],ascending=True) — > Filter out CreditScore raws where values are from 700 to 900 and present them in ascending order" }, { "code": null, "e": 7076, "s": 6969, "text": "Pandas Groupby function is a versatile and easy-to-use function that helps to get an overview of the data." }, { "code": null, "e": 7131, "s": 7076, "text": "df[['Gender','NumOfProducts']].groupby('Gender).mean()" }, { "code": null, "e": 7252, "s": 7131, "text": "Data Aggregations refer to any data transformation that produces scalar values from arrays: (mean, count, min, and sum)." }, { "code": null, "e": 7336, "s": 7252, "text": "df[['Gender','EstimatedSalary','Balance]].groupby(['Geography]).agg(['mean','max'])" }, { "code": null, "e": 7458, "s": 7336, "text": "In order to group by multiple columns, we simply pass a list to our groupby function with the columns we want to groupby:" }, { "code": null, "e": 7554, "s": 7458, "text": "df[['Gender','EstimatedSalary','Balance]].groupby(['Gender','Geography']).agg(['mean','count'])" }, { "code": null, "e": 7618, "s": 7554, "text": "df.pivot_table(index='CreditScore',values=['Age','Balance']) ->" }, { "code": null, "e": 7709, "s": 7618, "text": "Create a pivot table that groups by CreditScore and calculates the mean of Age and Balance" }, { "code": null, "e": 7749, "s": 7709, "text": "pd.melt(df) -> Gather columns into rows" }, { "code": null, "e": 7838, "s": 7749, "text": "Discretize variable into equal-sized buckets based on rank or based on sample quantiles." }, { "code": null, "e": 7993, "s": 7838, "text": "-Create a new Column[‘Salary_level”] using “pd.qcut” splitting EstimatedSalary into 5 different levels:[‘Bronze’, ‘Silver’, ‘Gold’, ‘Platinum’, ‘Diamond’]" }, { "code": null, "e": 8157, "s": 7993, "text": "bin_labels_5 = [‘Bronze’, ‘Silver’, ‘Gold’, ‘Platinum’, ‘Diamond’]df[‘Salary_level’] = pd.qcut(df[‘EstimatedSalary’],q=[0, .2, .4, .6, .8, 1], labels=bin_labels_5)" }, { "code": null, "e": 8227, "s": 8157, "text": "Use these commands to combine multiple data frames into a single one." }, { "code": null, "e": 8314, "s": 8227, "text": "df1.append(df2) -> Add the rows in df1 to the end of df2 (columns should be identical)" }, { "code": null, "e": 8412, "s": 8314, "text": "pd.concat([df1, df2],axis=1) -> Add the columns in df1 to the end of df2 where rows are identical" }, { "code": null, "e": 8555, "s": 8412, "text": "df1.join(df2 ,on=col1, how='inner') -> SQL-style join the columns in df1 with the columns on df2 where the rows for col have identical values." }, { "code": null, "e": 8604, "s": 8555, "text": "'how' can be : 'left', 'right', 'outer', 'inner'" }, { "code": null, "e": 8637, "s": 8604, "text": "You can do it with a simple code" }, { "code": null, "e": 8747, "s": 8637, "text": "tudf.head(5).style.set_properties(**{'background-color': 'lightgreen'}, subset=['Balance','EstimatedSalary'])" }, { "code": null, "e": 8994, "s": 8747, "text": "By adding the style function we can choose to set a colour to our columns and much more if you would like to know more about styling I would recommend the official pandas website: https://pandas.pydata.org/pandas-docs/stable/user_guide/style.html" }, { "code": null, "e": 9511, "s": 8994, "text": "In this Beginner-friendly tutorial, I implemented some of the most important Pandas functions and command used for Data Analysis. I went over for every function different types of examples. I would recommend finding additional data sets and playing around with these functions and explore as much as you can, at the end of the day it is a matter of practice. Mastering Pandas is a great asset for whoever is on the path to becoming a Skillful Data Scientist/Data analyst/ Machine learning engineer ecc...you name it." }, { "code": null, "e": 9674, "s": 9511, "text": "I hope this post gives you a nice foundation for whoever is trying to master it, and for whoever has well crafted this art may this post works as a re-freshening." } ]
C++ Numeric Library - partial_sum
It is used to compute partial sums of range and assigns to every element in the range starting at result the partial sum of the corresponding elements in the range [first,last). Following is the declaration for std::partial_sum. template <class InputIterator, class OutputIterator> OutputIterator partial_sum (InputIterator first, InputIterator last, OutputIterator result); template <class InputIterator, class OutputIterator, class BinaryOperation> OutputIterator partial_sum (InputIterator first, InputIterator last, OutputIterator result, BinaryOperation binary_op); template <class InputIterator, class OutputIterator> OutputIterator partial_sum (InputIterator first, InputIterator last, OutputIterator result); template <class InputIterator, class OutputIterator, class BinaryOperation> OutputIterator partial_sum (InputIterator first, InputIterator last, OutputIterator result, BinaryOperation binary_op); first, last − It iterators to the initial and final positions in a sequence. first, last − It iterators to the initial and final positions in a sequence. init − It is an initial value for the accumulator. init − It is an initial value for the accumulator. binary_op − It is binary operation. binary_op − It is binary operation. binary_op2 − It is binary operation and taking two elements. binary_op2 − It is binary operation and taking two elements. It returns an iterator pointing to past the last element of the destination sequence where resulting elements have been stored, or result if [first,last) is an empty range. It throws if any of the operations on the elements or iterators throws. The elements in the range [first1,last1) are accessed. In below example for std::partial_sum. #include <iostream> #include <functional> #include <numeric> int myop (int x, int y) {return x+y+1;} int main () { int val[] = {10,20,30,40,50}; int result[5]; std::partial_sum (val, val+5, result); std::cout << "Default partial_sum: "; for (int i=0; i<5; i++) std::cout << result[i] << ' '; std::cout << '\n'; std::partial_sum (val, val+5, result, std::multiplies<int>()); std::cout << "Functional operation multiplies: "; for (int i=0; i<5; i++) std::cout << result[i] << ' '; std::cout << '\n'; std::partial_sum (val, val+5, result, myop); std::cout << "Custom function: "; for (int i=0; i<5; i++) std::cout << result[i] << ' '; std::cout << '\n'; return 0; } The output should be like this − Default partial_sum: 10 30 60 100 150 Functional operation multiplies: 10 200 6000 240000 12000000 Custom function: 10 31 62 103 154 Print Add Notes Bookmark this page
[ { "code": null, "e": 2781, "s": 2603, "text": "It is used to compute partial sums of range and assigns to every element in the range starting at result the partial sum of the corresponding elements in the range [first,last)." }, { "code": null, "e": 2832, "s": 2781, "text": "Following is the declaration for std::partial_sum." }, { "code": null, "e": 3245, "s": 2832, "text": "\t\ntemplate <class InputIterator, class OutputIterator>\n OutputIterator partial_sum (InputIterator first, InputIterator last,\n OutputIterator result);\t\ntemplate <class InputIterator, class OutputIterator, class BinaryOperation>\n OutputIterator partial_sum (InputIterator first, InputIterator last,\n OutputIterator result, BinaryOperation binary_op);" }, { "code": null, "e": 3656, "s": 3245, "text": "template <class InputIterator, class OutputIterator>\n OutputIterator partial_sum (InputIterator first, InputIterator last,\n OutputIterator result);\t\ntemplate <class InputIterator, class OutputIterator, class BinaryOperation>\n OutputIterator partial_sum (InputIterator first, InputIterator last,\n OutputIterator result, BinaryOperation binary_op);" }, { "code": null, "e": 3733, "s": 3656, "text": "first, last − It iterators to the initial and final positions in a sequence." }, { "code": null, "e": 3810, "s": 3733, "text": "first, last − It iterators to the initial and final positions in a sequence." }, { "code": null, "e": 3861, "s": 3810, "text": "init − It is an initial value for the accumulator." }, { "code": null, "e": 3912, "s": 3861, "text": "init − It is an initial value for the accumulator." }, { "code": null, "e": 3948, "s": 3912, "text": "binary_op − It is binary operation." }, { "code": null, "e": 3984, "s": 3948, "text": "binary_op − It is binary operation." }, { "code": null, "e": 4045, "s": 3984, "text": "binary_op2 − It is binary operation and taking two elements." }, { "code": null, "e": 4106, "s": 4045, "text": "binary_op2 − It is binary operation and taking two elements." }, { "code": null, "e": 4279, "s": 4106, "text": "It returns an iterator pointing to past the last element of the destination sequence where resulting elements have been stored, or result if [first,last) is an empty range." }, { "code": null, "e": 4351, "s": 4279, "text": "It throws if any of the operations on the elements or iterators throws." }, { "code": null, "e": 4406, "s": 4351, "text": "The elements in the range [first1,last1) are accessed." }, { "code": null, "e": 4445, "s": 4406, "text": "In below example for std::partial_sum." }, { "code": null, "e": 5158, "s": 4445, "text": "#include <iostream>\n#include <functional>\n#include <numeric>\n\nint myop (int x, int y) {return x+y+1;}\n\nint main () {\n int val[] = {10,20,30,40,50};\n int result[5];\n\n std::partial_sum (val, val+5, result);\n std::cout << \"Default partial_sum: \";\n for (int i=0; i<5; i++) std::cout << result[i] << ' ';\n std::cout << '\\n';\n\n std::partial_sum (val, val+5, result, std::multiplies<int>());\n std::cout << \"Functional operation multiplies: \";\n for (int i=0; i<5; i++) std::cout << result[i] << ' ';\n std::cout << '\\n';\n\n std::partial_sum (val, val+5, result, myop);\n std::cout << \"Custom function: \";\n for (int i=0; i<5; i++) std::cout << result[i] << ' ';\n std::cout << '\\n';\n return 0;\n}" }, { "code": null, "e": 5191, "s": 5158, "text": "The output should be like this −" }, { "code": null, "e": 5328, "s": 5191, "text": "Default partial_sum: 10 30 60 100 150 \nFunctional operation multiplies: 10 200 6000 240000 12000000 \nCustom function: 10 31 62 103 154 \n" }, { "code": null, "e": 5335, "s": 5328, "text": " Print" }, { "code": null, "e": 5346, "s": 5335, "text": " Add Notes" } ]
Python Pandas – Check if any specific column of two DataFrames are equal or not
To check if any specific column of two DataFrames are equal or not, use the equals() method. Let us first create DataFrame1 with two columns − dataFrame1 = pd.DataFrame( { "Car": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Bentley', 'Jaguar'], "Units": [100, 150, 110, 80, 110, 90] } ) Create DataFrame2 with two columns − dataFrame2 = pd.DataFrame( { "Car": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Mercedes', 'Jaguar'], "Units": [100, 150, 110, 80, 110, 90] } ) Check for the equality of a specific column Units − dataFrame2['Units'].equals(dataFrame1['Units']) Following is the code − import pandas as pd # Create DataFrame1 dataFrame1 = pd.DataFrame( { "Car": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Bentley', 'Jaguar'], "Units": [100, 150, 110, 80, 110, 90] } ) print"DataFrame1 ...\n",dataFrame1 # Create DataFrame2 dataFrame2 = pd.DataFrame( { "Car": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Bentley', 'Jaguar'], "Units": [100, 150, 110, 80, 110, 90] } ) print"\nDataFrame2 ...\n",dataFrame2 # check for equality print"\nAre both the DataFrame objects equal? ",dataFrame1.equals(dataFrame2) # check for specific column Units equality print"\nAre both the DataFrames have similar Units column? ",dataFrame2['Units'].equals(dataFrame1['Units'] ) This will produce the following output − DataFrame1 ... Car Units 0 BMW 100 1 Lexus 150 2 Audi 110 3 Mustang 80 4 Bentley 110 5 Jaguar 90 DataFrame2 ... Car Units 0 BMW 100 1 Lexus 150 2 Audi 110 3 Mustang 80 4 Bentley 110 5 Jaguar 90 Are both the DataFrame objects equal? True Are both the DataFrames have similar Units column? True
[ { "code": null, "e": 1205, "s": 1062, "text": "To check if any specific column of two DataFrames are equal or not, use the equals() method. Let us first create DataFrame1 with two columns −" }, { "code": null, "e": 1359, "s": 1205, "text": "dataFrame1 = pd.DataFrame(\n {\n \"Car\": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Bentley', 'Jaguar'],\n \"Units\": [100, 150, 110, 80, 110, 90]\n }\n)" }, { "code": null, "e": 1396, "s": 1359, "text": "Create DataFrame2 with two columns −" }, { "code": null, "e": 1551, "s": 1396, "text": "dataFrame2 = pd.DataFrame(\n {\n \"Car\": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Mercedes', 'Jaguar'],\n \"Units\": [100, 150, 110, 80, 110, 90]\n }\n)" }, { "code": null, "e": 1603, "s": 1551, "text": "Check for the equality of a specific column Units −" }, { "code": null, "e": 1652, "s": 1603, "text": "dataFrame2['Units'].equals(dataFrame1['Units'])\n" }, { "code": null, "e": 1676, "s": 1652, "text": "Following is the code −" }, { "code": null, "e": 2371, "s": 1676, "text": "import pandas as pd\n\n# Create DataFrame1\ndataFrame1 = pd.DataFrame(\n {\n \"Car\": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Bentley', 'Jaguar'],\n \"Units\": [100, 150, 110, 80, 110, 90] }\n)\n\nprint\"DataFrame1 ...\\n\",dataFrame1\n\n# Create DataFrame2\ndataFrame2 = pd.DataFrame(\n {\n \"Car\": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Bentley', 'Jaguar'],\n \"Units\": [100, 150, 110, 80, 110, 90]\n }\n)\n\nprint\"\\nDataFrame2 ...\\n\",dataFrame2\n\n# check for equality\nprint\"\\nAre both the DataFrame objects equal? \",dataFrame1.equals(dataFrame2)\n\n# check for specific column Units equality\nprint\"\\nAre both the DataFrames have similar Units column? \",dataFrame2['Units'].equals(dataFrame1['Units']\n)" }, { "code": null, "e": 2412, "s": 2371, "text": "This will produce the following output −" }, { "code": null, "e": 2798, "s": 2412, "text": "DataFrame1 ...\n Car Units\n0 BMW 100\n1 Lexus 150\n2 Audi 110\n3 Mustang 80\n4 Bentley 110\n5 Jaguar 90\n\nDataFrame2 ...\n Car Units\n0 BMW 100\n1 Lexus 150\n2 Audi 110\n3 Mustang 80\n4 Bentley 110\n5 Jaguar 90\n\nAre both the DataFrame objects equal? True\n\nAre both the DataFrames have similar Units column? True" } ]
Build Your First Machine Learning Model With Python in 7 minutes | by Soner Yıldırım | Towards Data Science
When I first started to learn about data science, machine learning sounded like an extremely difficult subject. I was reading about algorithms with fancy names such as support vector machine, gradient boosted decision trees, logistic regression, and so on. It did not take me long to realize that all those algorithms are essentially capturing the relationships among variables or the underlying structure within the data. Some of the relationships are crystal clear. For instance, we all know that, everything else being equal, the price of a car decreases as it gets older (excluding the classics). However, some relationships are not so intuitive and not easy for us to notice. Think simple and learn the fundamentals first. In this article, we will create a simple machine learning algorithm to predict customer churn. I will also explain some fundamental points that you need to pay extra attention to. Thus, we will not only practice but also learn some theory. We will be using Python libraries. To be more specific, Pandas and NumPy for data wrangling and Scikit-learn for preprocessing and machine learning tasks. The dataset is available on Kaggle under creative commons license with no copyright. Let’s start with reading the dataset. import numpy as npimport pandas as pddf = pd.read_csv("/content/Churn_Modelling.csv")print(df.shape)(10000, 14)df.columnsIndex(['RowNumber', 'CustomerId', 'Surname', 'CreditScore', 'Geography', 'Gender', 'Age', 'Tenure', 'Balance', 'NumOfProducts', 'HasCrCard','IsActiveMember', 'EstimatedSalary', 'Exited'], dtype='object') The dataset contains 10000 rows and 14 columns. We are expected to predict customer churn (i.e. Exited = 1) using the other 13 columns. The exited column is called the target or independent variable. The other columns are called features or dependent variables. The row number, surname, and customer id are redundant features so we can drop them. The id of customers or their surnames have no effect on customer churn. df.drop(["RowNumber","CustomerId","Surname"], axis=1, inplace=True)df.head() A typical dataset contains both categorical and numerical variables. A big portion of the machine learning algorithms only accept numerical variables. Thus, encoding categorical variables is a common preprocessing task. Our dataset contains two categorical variables which are geography and gender. Let’s check the distinct values in these columns. df.Geography.unique()array(['France', 'Spain', 'Germany'], dtype=object)df.Gender.unique()array(['Female', 'Male'], dtype=object) One option for converting these values to numbers is to assign an integer to each one. For instance, France is 0, Spain is 1, and Germany is 2. This process is called label encoding. The problem with this approach is that the algorithms might consider these numbers as a hierarchical relation. Germany is thought to have higher precedence than France. To overcome this problem, we can use an approach called one-hot encoding. Each distinct value is represented as a binary column. If the value in the geography column is France, then only the France column takes the value 1. The others become zero. The get_dummies function of Pandas can be used for this task. geography = pd.get_dummies(df.Geography)gender = pd.get_dummies(df.Gender)df = pd.concat([df, geography, gender], axis=1)df[["Geography","Gender","France","Germany","Spain","Female","Male"]].head() Exploratory data analysis is a crucial step before designing and implementing your model. The goal is to have a comprehensive understanding of the data at hand. We will pass this step with a few controls. You will be spending more and more time exploring the data as you gain more experience. A typical task in exploratory data analysis is to check the distribution of the numerical variables. You can also detect outliers (i.e. extreme values) with this approach. Histograms are great for checking the distribution of variables. You can use a data visualization library such as Seaborn or Matplotlib. I prefer to use Pandas since it is quite simple to produce basic plots. Let’s start with the balance column. df.Balance.plot(kind="hist", figsize=(10,6)) It seems like a lot of customers have zero balance. It might be better to convert this column to binary, 0 for no balance and 1 for positive balance. We can accomplish this task using the where function of NumPy as below: df.Balance = np.where(df.Balance==0, 0, 1)df.Balance.value_counts()1 6383 0 3617 Name: Balance, dtype: int64 One third of the customers have 0 balance. Let’s also draw the histogram of age column. df.Age.plot(kind="hist", figsize=(10,6)) It is close to a normal distribution. The values above 80 might be considered as outliers but we will not focus on detecting the outliers for now. Feel free to explore the distribution of other numerical variables such as tenure, number of products, and estimated salary. As you might notice, the value ranges of the numerical variables are very different. The age values are less than 100 whereas the estimated salaries are more than 10 thousand. If we use these features as they are, the model might give more importance to the column with higher values. Thus, it is better to scale them to the same range. A common approach is min-max scaling. The highest and lowest values are scaled to 1 and 0, respectively. The ones in between are scaled accordingly. There are more advanced scaling options as well. For instance, in case of a column with extreme values, mix-max scaling is not the best option. However, we will stick to the simple case for now. The point here is to emphasize the importance of feature scaling. We will perform feature scaling after introducing another highly important topic. A machine learning model learns by training. We feed the model with data and it learns the relationships between variables or the structure within the data. After a model is trained, it should be tested. However, it is not acceptable to test a model with the data it trained on. It would be similar to cheating. A model might just memorize everything in the data and give you 100% accuracy. Thus, before training a model, it is common practice to set aside a part of data for testing. The model performance should be evaluated using the test data. The important thing here is that a model should not have any information about the test data. Hence, the feature scaling we discussed in the previous step should be done after splitting the train and test sets. We can do this manually or use the train_test_split function of Scikit-learn. from sklearn.model_selection import train_test_splitX = df.drop(["Exited","Geography","Gender"], axis=1)y = df["Exited"]X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42) The X contains the features and y contains the target variable. By default, 25% of the entire data is set aside for testing. You can change this ratio by using the test_size or train_size parameters. X_train.shape(7500, 13)X_test.shape(2500, 13) We can now do the feature scaling. The MinMaxScaler function of Scikit-learn can be used for this task. We will create a Scaler object and train it with X_train. We will then use the trained scaler to transform (or scale) X_train and X_test. Thus, the model will not be given any hint or information about the test set. from sklearn.preprocessing import MinMaxScalerscaler = MinMaxScaler()scaler.fit(X_train)X_train_transformed = scaler.transform(X_train)X_test_transformed = scaler.transform(X_test) This part actually includes two steps. The first one is to choose an algorithm. There are several machine learning algorithms. They all have some pros and cons. We cannot cover all the algorithms in an article. So we will pick one and continue. The logistic regression algorithm is a commonly used one for binary classification tasks. This process with Scikit-learn is as follows: Create a logistic regression object which is our model Train the model with the training set Evaluate its performance on both training and test sets based on a particular metric The following code will perform all these steps: from sklearn.linear_model import LogisticRegressionfrom sklearn.metrics import accuracy_score# Create a model and train itmodel = LogisticRegression()model.fit(X_train, y_train)# Make predictionsy_train_pred = model.predict(X_train)y_test_pred = model.predict(X_test)# Evaluate model performanceprint(accuracy_score(y_train, y_train_pred))0.78print(accuracy_score(y_test, y_test_pred))0.80 Our model achieved an accuracy of 78% on the training set and 80% on the test set. It can definitely be improved. Some ways to improve model performance are: Collecting more data Trying different algorithms Hyperparameter tuning We will not get into model improvement in this article. I think that the most effective method is to collect more data. The potential improvement with the other two methods are limited. We have covered a basic workflow for creating a machine learning model. In a real-life case, each step is more detailed and studied in-depth. We have only scratched the surface. Once you are comfortable with the basic workflow, you can focus on improving each step. Building a decent machine learning model is an iterative process. You may have to modify your model or features several times after performance evaluation. How you evaluate a classification model is also very critical. In many cases, we cannot just use a simple accuracy metric. I previously wrote an article about how to best evaluate a classification model. Thank you for reading. Please let me know if you have any feedback.
[ { "code": null, "e": 429, "s": 172, "text": "When I first started to learn about data science, machine learning sounded like an extremely difficult subject. I was reading about algorithms with fancy names such as support vector machine, gradient boosted decision trees, logistic regression, and so on." }, { "code": null, "e": 595, "s": 429, "text": "It did not take me long to realize that all those algorithms are essentially capturing the relationships among variables or the underlying structure within the data." }, { "code": null, "e": 853, "s": 595, "text": "Some of the relationships are crystal clear. For instance, we all know that, everything else being equal, the price of a car decreases as it gets older (excluding the classics). However, some relationships are not so intuitive and not easy for us to notice." }, { "code": null, "e": 900, "s": 853, "text": "Think simple and learn the fundamentals first." }, { "code": null, "e": 1140, "s": 900, "text": "In this article, we will create a simple machine learning algorithm to predict customer churn. I will also explain some fundamental points that you need to pay extra attention to. Thus, we will not only practice but also learn some theory." }, { "code": null, "e": 1295, "s": 1140, "text": "We will be using Python libraries. To be more specific, Pandas and NumPy for data wrangling and Scikit-learn for preprocessing and machine learning tasks." }, { "code": null, "e": 1418, "s": 1295, "text": "The dataset is available on Kaggle under creative commons license with no copyright. Let’s start with reading the dataset." }, { "code": null, "e": 1748, "s": 1418, "text": "import numpy as npimport pandas as pddf = pd.read_csv(\"/content/Churn_Modelling.csv\")print(df.shape)(10000, 14)df.columnsIndex(['RowNumber', 'CustomerId', 'Surname', 'CreditScore', 'Geography', 'Gender', 'Age', 'Tenure', 'Balance', 'NumOfProducts', 'HasCrCard','IsActiveMember', 'EstimatedSalary', 'Exited'], dtype='object')" }, { "code": null, "e": 2010, "s": 1748, "text": "The dataset contains 10000 rows and 14 columns. We are expected to predict customer churn (i.e. Exited = 1) using the other 13 columns. The exited column is called the target or independent variable. The other columns are called features or dependent variables." }, { "code": null, "e": 2167, "s": 2010, "text": "The row number, surname, and customer id are redundant features so we can drop them. The id of customers or their surnames have no effect on customer churn." }, { "code": null, "e": 2244, "s": 2167, "text": "df.drop([\"RowNumber\",\"CustomerId\",\"Surname\"], axis=1, inplace=True)df.head()" }, { "code": null, "e": 2464, "s": 2244, "text": "A typical dataset contains both categorical and numerical variables. A big portion of the machine learning algorithms only accept numerical variables. Thus, encoding categorical variables is a common preprocessing task." }, { "code": null, "e": 2593, "s": 2464, "text": "Our dataset contains two categorical variables which are geography and gender. Let’s check the distinct values in these columns." }, { "code": null, "e": 2723, "s": 2593, "text": "df.Geography.unique()array(['France', 'Spain', 'Germany'], dtype=object)df.Gender.unique()array(['Female', 'Male'], dtype=object)" }, { "code": null, "e": 2906, "s": 2723, "text": "One option for converting these values to numbers is to assign an integer to each one. For instance, France is 0, Spain is 1, and Germany is 2. This process is called label encoding." }, { "code": null, "e": 3075, "s": 2906, "text": "The problem with this approach is that the algorithms might consider these numbers as a hierarchical relation. Germany is thought to have higher precedence than France." }, { "code": null, "e": 3323, "s": 3075, "text": "To overcome this problem, we can use an approach called one-hot encoding. Each distinct value is represented as a binary column. If the value in the geography column is France, then only the France column takes the value 1. The others become zero." }, { "code": null, "e": 3385, "s": 3323, "text": "The get_dummies function of Pandas can be used for this task." }, { "code": null, "e": 3583, "s": 3385, "text": "geography = pd.get_dummies(df.Geography)gender = pd.get_dummies(df.Gender)df = pd.concat([df, geography, gender], axis=1)df[[\"Geography\",\"Gender\",\"France\",\"Germany\",\"Spain\",\"Female\",\"Male\"]].head()" }, { "code": null, "e": 3744, "s": 3583, "text": "Exploratory data analysis is a crucial step before designing and implementing your model. The goal is to have a comprehensive understanding of the data at hand." }, { "code": null, "e": 3876, "s": 3744, "text": "We will pass this step with a few controls. You will be spending more and more time exploring the data as you gain more experience." }, { "code": null, "e": 4048, "s": 3876, "text": "A typical task in exploratory data analysis is to check the distribution of the numerical variables. You can also detect outliers (i.e. extreme values) with this approach." }, { "code": null, "e": 4257, "s": 4048, "text": "Histograms are great for checking the distribution of variables. You can use a data visualization library such as Seaborn or Matplotlib. I prefer to use Pandas since it is quite simple to produce basic plots." }, { "code": null, "e": 4294, "s": 4257, "text": "Let’s start with the balance column." }, { "code": null, "e": 4339, "s": 4294, "text": "df.Balance.plot(kind=\"hist\", figsize=(10,6))" }, { "code": null, "e": 4489, "s": 4339, "text": "It seems like a lot of customers have zero balance. It might be better to convert this column to binary, 0 for no balance and 1 for positive balance." }, { "code": null, "e": 4561, "s": 4489, "text": "We can accomplish this task using the where function of NumPy as below:" }, { "code": null, "e": 4676, "s": 4561, "text": "df.Balance = np.where(df.Balance==0, 0, 1)df.Balance.value_counts()1 6383 0 3617 Name: Balance, dtype: int64" }, { "code": null, "e": 4719, "s": 4676, "text": "One third of the customers have 0 balance." }, { "code": null, "e": 4764, "s": 4719, "text": "Let’s also draw the histogram of age column." }, { "code": null, "e": 4805, "s": 4764, "text": "df.Age.plot(kind=\"hist\", figsize=(10,6))" }, { "code": null, "e": 4952, "s": 4805, "text": "It is close to a normal distribution. The values above 80 might be considered as outliers but we will not focus on detecting the outliers for now." }, { "code": null, "e": 5077, "s": 4952, "text": "Feel free to explore the distribution of other numerical variables such as tenure, number of products, and estimated salary." }, { "code": null, "e": 5253, "s": 5077, "text": "As you might notice, the value ranges of the numerical variables are very different. The age values are less than 100 whereas the estimated salaries are more than 10 thousand." }, { "code": null, "e": 5414, "s": 5253, "text": "If we use these features as they are, the model might give more importance to the column with higher values. Thus, it is better to scale them to the same range." }, { "code": null, "e": 5563, "s": 5414, "text": "A common approach is min-max scaling. The highest and lowest values are scaled to 1 and 0, respectively. The ones in between are scaled accordingly." }, { "code": null, "e": 5824, "s": 5563, "text": "There are more advanced scaling options as well. For instance, in case of a column with extreme values, mix-max scaling is not the best option. However, we will stick to the simple case for now. The point here is to emphasize the importance of feature scaling." }, { "code": null, "e": 5906, "s": 5824, "text": "We will perform feature scaling after introducing another highly important topic." }, { "code": null, "e": 6063, "s": 5906, "text": "A machine learning model learns by training. We feed the model with data and it learns the relationships between variables or the structure within the data." }, { "code": null, "e": 6297, "s": 6063, "text": "After a model is trained, it should be tested. However, it is not acceptable to test a model with the data it trained on. It would be similar to cheating. A model might just memorize everything in the data and give you 100% accuracy." }, { "code": null, "e": 6454, "s": 6297, "text": "Thus, before training a model, it is common practice to set aside a part of data for testing. The model performance should be evaluated using the test data." }, { "code": null, "e": 6665, "s": 6454, "text": "The important thing here is that a model should not have any information about the test data. Hence, the feature scaling we discussed in the previous step should be done after splitting the train and test sets." }, { "code": null, "e": 6743, "s": 6665, "text": "We can do this manually or use the train_test_split function of Scikit-learn." }, { "code": null, "e": 6938, "s": 6743, "text": "from sklearn.model_selection import train_test_splitX = df.drop([\"Exited\",\"Geography\",\"Gender\"], axis=1)y = df[\"Exited\"]X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)" }, { "code": null, "e": 7138, "s": 6938, "text": "The X contains the features and y contains the target variable. By default, 25% of the entire data is set aside for testing. You can change this ratio by using the test_size or train_size parameters." }, { "code": null, "e": 7184, "s": 7138, "text": "X_train.shape(7500, 13)X_test.shape(2500, 13)" }, { "code": null, "e": 7346, "s": 7184, "text": "We can now do the feature scaling. The MinMaxScaler function of Scikit-learn can be used for this task. We will create a Scaler object and train it with X_train." }, { "code": null, "e": 7504, "s": 7346, "text": "We will then use the trained scaler to transform (or scale) X_train and X_test. Thus, the model will not be given any hint or information about the test set." }, { "code": null, "e": 7685, "s": 7504, "text": "from sklearn.preprocessing import MinMaxScalerscaler = MinMaxScaler()scaler.fit(X_train)X_train_transformed = scaler.transform(X_train)X_test_transformed = scaler.transform(X_test)" }, { "code": null, "e": 7846, "s": 7685, "text": "This part actually includes two steps. The first one is to choose an algorithm. There are several machine learning algorithms. They all have some pros and cons." }, { "code": null, "e": 8020, "s": 7846, "text": "We cannot cover all the algorithms in an article. So we will pick one and continue. The logistic regression algorithm is a commonly used one for binary classification tasks." }, { "code": null, "e": 8066, "s": 8020, "text": "This process with Scikit-learn is as follows:" }, { "code": null, "e": 8121, "s": 8066, "text": "Create a logistic regression object which is our model" }, { "code": null, "e": 8159, "s": 8121, "text": "Train the model with the training set" }, { "code": null, "e": 8244, "s": 8159, "text": "Evaluate its performance on both training and test sets based on a particular metric" }, { "code": null, "e": 8293, "s": 8244, "text": "The following code will perform all these steps:" }, { "code": null, "e": 8683, "s": 8293, "text": "from sklearn.linear_model import LogisticRegressionfrom sklearn.metrics import accuracy_score# Create a model and train itmodel = LogisticRegression()model.fit(X_train, y_train)# Make predictionsy_train_pred = model.predict(X_train)y_test_pred = model.predict(X_test)# Evaluate model performanceprint(accuracy_score(y_train, y_train_pred))0.78print(accuracy_score(y_test, y_test_pred))0.80" }, { "code": null, "e": 8797, "s": 8683, "text": "Our model achieved an accuracy of 78% on the training set and 80% on the test set. It can definitely be improved." }, { "code": null, "e": 8841, "s": 8797, "text": "Some ways to improve model performance are:" }, { "code": null, "e": 8862, "s": 8841, "text": "Collecting more data" }, { "code": null, "e": 8890, "s": 8862, "text": "Trying different algorithms" }, { "code": null, "e": 8912, "s": 8890, "text": "Hyperparameter tuning" }, { "code": null, "e": 9098, "s": 8912, "text": "We will not get into model improvement in this article. I think that the most effective method is to collect more data. The potential improvement with the other two methods are limited." }, { "code": null, "e": 9276, "s": 9098, "text": "We have covered a basic workflow for creating a machine learning model. In a real-life case, each step is more detailed and studied in-depth. We have only scratched the surface." }, { "code": null, "e": 9364, "s": 9276, "text": "Once you are comfortable with the basic workflow, you can focus on improving each step." }, { "code": null, "e": 9520, "s": 9364, "text": "Building a decent machine learning model is an iterative process. You may have to modify your model or features several times after performance evaluation." }, { "code": null, "e": 9724, "s": 9520, "text": "How you evaluate a classification model is also very critical. In many cases, we cannot just use a simple accuracy metric. I previously wrote an article about how to best evaluate a classification model." } ]
ReactJS – componentWillMount() Method
In this article, we are going to see how to execute a function before the component is loaded in the DOM tree. This method is used during the mounting phase of the React lifecycle. This function is generally called before the component gets loaded in the DOM tree. This method is called before the render() method is called, so it can be used to initialize the state but the constructor is preferred. This method is generally used in server-side rendering. Don’t call subscriptions or side-effects in this method; use componentDidMount instead. Note: This method is now deprecated. UNSAFE_componentWillMount() In this example, we will build a color-changing React application that changes the color of the text as soon as the component is loaded in the DOM tree. Our first component in the following example is App. This component is the parent of the ChangeName component. We are creating ChangeName separately and just adding it inside the JSX tree in our App component. Hence, only the App component needs to be exported. App.jsx import React from 'react'; class App extends React.Component { render() { return ( <div> <h1>Tutorialspoint</h1> <ChangeName /> </div> ); } } class ChangeName extends React.Component { constructor(props) { super(props); this.state = { color: 'lightgreen' }; } UNSAFE_componentWillMount() { // Changing the state immediately. this.setState({ color: 'wheat' }); } render() { return ( <div> <h1 style={{ color: this.state.color }}>Simply Easy Learning</h1> </div> ); } } export default App; This will produce the following result.
[ { "code": null, "e": 1173, "s": 1062, "text": "In this article, we are going to see how to execute a function before the component is loaded in the DOM tree." }, { "code": null, "e": 1463, "s": 1173, "text": "This method is used during the mounting phase of the React lifecycle. This function is generally called before the component gets loaded in the DOM tree. This method is called before the render() method is called, so it can be used to initialize the state but the constructor is preferred." }, { "code": null, "e": 1607, "s": 1463, "text": "This method is generally used in server-side rendering. Don’t call subscriptions or side-effects in this method; use componentDidMount instead." }, { "code": null, "e": 1644, "s": 1607, "text": "Note: This method is now deprecated." }, { "code": null, "e": 1672, "s": 1644, "text": "UNSAFE_componentWillMount()" }, { "code": null, "e": 1825, "s": 1672, "text": "In this example, we will build a color-changing React application that changes the color of the text as soon as the component is loaded in the DOM tree." }, { "code": null, "e": 2087, "s": 1825, "text": "Our first component in the following example is App. This component is the parent of the ChangeName component. We are creating ChangeName separately and just adding it inside the JSX tree in our App component. Hence, only the App component needs to be exported." }, { "code": null, "e": 2095, "s": 2087, "text": "App.jsx" }, { "code": null, "e": 2728, "s": 2095, "text": "import React from 'react';\n\nclass App extends React.Component {\n render() {\n return (\n <div>\n <h1>Tutorialspoint</h1>\n <ChangeName />\n </div>\n );\n }\n}\nclass ChangeName extends React.Component {\n constructor(props) {\n super(props);\n this.state = { color: 'lightgreen' };\n }\n UNSAFE_componentWillMount() {\n // Changing the state immediately.\n this.setState({ color: 'wheat' });\n }\n render() {\n return (\n <div>\n <h1 style={{ color: this.state.color }}>Simply Easy Learning</h1>\n </div>\n );\n }\n}\nexport default App;" }, { "code": null, "e": 2768, "s": 2728, "text": "This will produce the following result." } ]
How to convert a vector into matrix in R?
To convert a vector into matrix, just need to use matrix function. We can also define the number of rows and columns, if required but if the number of values in the vector are not a multiple of the number of rows or columns then R will throw an error as it is not possible to create a matrix for that vector. Here, we will read vectors by their names to make it easy but you can change their names if you want. There are four vectors of different lengths that are shown in these examples − s > Vector1<-1:9 > Vector1 [1] 1 2 3 4 5 6 7 8 9 > Vector1<-as.matrix(Vector1) > Vector1 [,1] [1,] 1 [2,] 2 [3,] 3 [4,] 4 [5,] 5 [6,] 6 [7,] 7 [8,] 8 [9,] 9 > Vector1<-matrix(Vector1,nrow=3) > Vector1 [,1] [,2] [,3] [1,] 1 4 7 [2,] 2 5 8 [3,] 3 6 9 > Vector2<-c(24,26,14,15,39,18,17,25,17,19,18,23,24,19,27,15) > Vector2 [1] 24 26 14 15 39 18 17 25 17 19 18 23 24 19 27 15 > Vector2<-as.matrix(Vector2) > Vector2 [,1] [1,] 24 [2,] 26 [3,] 14 [4,] 15 [5,] 39 [6,] 18 [7,] 17 [8,] 25 [9,] 17 [10,] 19 [11,] 18 [12,] 23 [13,] 24 [14,] 19 [15,] 27 [16,] 15 > Vector2<-matrix(Vector2,nrow=4,byrow=TRUE) > Vector2 [,1] [,2] [,3] [,4] [1,] 24 26 14 15 [2,] 39 18 17 25 [3,] 17 19 18 23 [4,] 24 19 27 15 > Vector3<-sample(1:100,25) > Vector3 [1] 86 84 32 14 4 78 7 82 71 38 98 87 58 54 46 44 88 65 97 60 31 89 63 91 90 > Vector3<-matrix(Vector3,nrow=5) > Vector3 [,1] [,2] [,3] [,4] [,5] [1,] 86 78 98 44 31 [2,] 84 7 87 88 89 [3,] 32 82 58 65 63 [4,] 14 71 54 97 91 [5,] 4 38 46 60 90 > Vector3<-matrix(Vector3,nrow=2) Warning message: In matrix(Vector3, nrow = 2) : data length [25] is not a sub-multiple or multiple of the number of rows [2] > Vector4<-1:10 > Vector4 [1] 1 2 3 4 5 6 7 8 9 10 > Vector4<-matrix(Vector4,nrow=2) > Vector4 [,1] [,2] [,3] [,4] [,5] [1,] 1 3 5 7 9 [2,] 2 4 6 8 10 > Vector4<-matrix(Vector4,ncol=2) > Vector4 [,1] [,2] [1,] 1 6 [2,] 2 7 [3,] 3 8 [4,] 4 9 [5,] 5 10
[ { "code": null, "e": 1371, "s": 1062, "text": "To convert a vector into matrix, just need to use matrix function. We can also define the number of rows and columns, if required but if the number of values in the vector are not a multiple of the number of rows or columns then R will throw an error as it is not possible to create a matrix for that vector." }, { "code": null, "e": 1552, "s": 1371, "text": "Here, we will read vectors by their names to make it easy but you can change their names if you want. There are four vectors of different lengths that are shown in these examples −" }, { "code": null, "e": 3056, "s": 1552, "text": "s\n> Vector1<-1:9\n> Vector1\n[1] 1 2 3 4 5 6 7 8 9\n> Vector1<-as.matrix(Vector1)\n> Vector1\n [,1]\n[1,] 1\n[2,] 2\n[3,] 3\n[4,] 4\n[5,] 5\n[6,] 6\n[7,] 7\n[8,] 8\n[9,] 9\n> Vector1<-matrix(Vector1,nrow=3)\n> Vector1\n [,1] [,2] [,3]\n[1,] 1 4 7\n[2,] 2 5 8\n[3,] 3 6 9\n> Vector2<-c(24,26,14,15,39,18,17,25,17,19,18,23,24,19,27,15)\n> Vector2\n[1] 24 26 14 15 39 18 17 25 17 19 18 23 24 19 27 15\n> Vector2<-as.matrix(Vector2)\n> Vector2\n [,1]\n[1,] 24\n[2,] 26\n[3,] 14\n[4,] 15\n[5,] 39\n[6,] 18\n[7,] 17\n[8,] 25\n[9,] 17\n[10,] 19\n[11,] 18\n[12,] 23\n[13,] 24\n[14,] 19\n[15,] 27\n[16,] 15\n> Vector2<-matrix(Vector2,nrow=4,byrow=TRUE)\n> Vector2\n [,1] [,2] [,3] [,4]\n[1,] 24 26 14 15\n[2,] 39 18 17 25\n[3,] 17 19 18 23\n[4,] 24 19 27 15\n> Vector3<-sample(1:100,25)\n> Vector3\n[1] 86 84 32 14 4 78 7 82 71 38 98 87 58 54 46 44 88 65 97 60 31 89 63 91 90\n> Vector3<-matrix(Vector3,nrow=5)\n> Vector3\n [,1] [,2] [,3] [,4] [,5]\n[1,] 86 78 98 44 31\n[2,] 84 7 87 88 89\n[3,] 32 82 58 65 63\n[4,] 14 71 54 97 91\n[5,] 4 38 46 60 90\n> Vector3<-matrix(Vector3,nrow=2)\nWarning message:\nIn matrix(Vector3, nrow = 2) :\ndata length [25] is not a sub-multiple or multiple of the number of rows [2]\n> Vector4<-1:10\n> Vector4\n[1] 1 2 3 4 5 6 7 8 9 10\n> Vector4<-matrix(Vector4,nrow=2)\n> Vector4\n[,1] [,2] [,3] [,4] [,5]\n[1,] 1 3 5 7 9\n[2,] 2 4 6 8 10\n> Vector4<-matrix(Vector4,ncol=2)\n> Vector4\n [,1] [,2]\n[1,] 1 6\n[2,] 2 7\n[3,] 3 8\n[4,] 4 9\n[5,] 5 10" } ]
Using a Neural Network to Predict Voter Preferences | by Gustavo Caffaro | Towards Data Science
With presidential elections around the corner, political analysts, forecasters, and other interested parties are running to build their best estimate of election outcomes. Traditionally, polls have been used to gauge the level of popularity of political candidates, but increased computing power and the development of powerful statistical methods provide an interesting alternative to them. A good place to start forecasting elections is to first predict voters’ political preferences. This is is what we will do here. In this article we will build a simple neural network in R to predict voter preferences in the United States. We will do this using Keras, an amazing open-source API that allows you to run neural network models in a simple yet powerful way. Although it runs natively in Python, RStudio has developed a package that allows seamless integration with R. Before we start, please make sure you have the following R packages installed, as we will be using them to perform our predictions: install.packages("keras")install.packages("tidyr")install.packages("ggplot2")install.packages("dplyr")install.packages("fastDummies") Data The data used to train the neural network comes from the 2018 Cooperative Congressional Election Study, administered by YouGov. It was compiled by Kuriwaki (2018), and was extracted from the Harvard Dataverse. You can download this data in .Rds file format for the years 2006–2018 here. Assuming you downloaded the file and placed it in your working directory, we can proceed to import the data and see its structure: d <- readRDS("cumulative_2006_2018.Rds")dim(d)[1] 452755 73 d is a dataframe with 452,755 rows (observations) and 73 columns (features). These features include geographic, demographic, and economic variables, in addition to other interesting variables such as political approval and news interest levels. Of course, they also include the presidential vote choice of each individual. This last variable will be our dependent variable, e.g. what we will predict with our model. Finally, a detailed explanation of each variable is provided in the aforementioned dataset source link. Since we have data for the years 2006–2008, let’s filter d to select only the responses made in 2018, the year of the latest survey: dd <- d %>% filter(year == 2018) Additionally, let’s select only the variables that are of interest to our model and exclude missing values: dd <- dd %>% select(st, dist, cong, # geography gender, birthyr, age, educ, race, faminc, marstat, # demographics newsint, # news interest approval_pres, # approval ideo5, # ideology voted_pres_16 # presidential vote )dd <- dd[complete.cases(dd),] This is how this data frame looks like: The table below presents the number of respondents for each of the categories of voter preferences (variable voted_pres_16). It can be seen that around 88% of the respondents voted for either Donald Trump or Hilary Clinton, 9.91% voted for another candidate, and around 1.3% did not reveal their preferences or did not vote. Coming back to our dataset dd, excluding the variable age, all our features are categorical. Thus, we need to one-hot encode these variables into dummies. There are many packages and functions to do this, but here we will use the function dummy_cols from the fastDummies package. cat_vars <- colnames(dd)cat_vars <- cat_vars[!cat_vars %in% c("age","voted_pres_16")]all_data <- dummy_cols(dd, select_columns = cat_vars, remove_first_dummy = TRUE, remove_selected_columns = TRUE) We also convert our dependent variable, voted_pres_16 into a numeric vector with integers (starting at zero) for each of the candidates, and we remove the variable voted_pres_16 from our dataframe: all_labels <- dd$voted_pres_16 %>% as.factor() %>% unclass() - 1all_data <- all_data %>% select(-voted_pres_16) %>% as.matrix() Finally, we separate our data into a training set (90%) and a test set (10%), so that after we train our model, we can test its performance on “new” data. party_levels <- levels(all_labels)elems <- sample(1:nrow(all_data), round(0.1*nrow(all_data)), replace = F)# training datatrain_data <- all_data[-elems,]train_labels <- all_labels[-elems]levels(train_labels) <- levels(all_labels)# test datatest_data <- all_data[elems,]test_labels <- all_labels[elems]levels(test_labels) <- party_levels Building the model Our problem at hand is modeled as a classification problem, where each candidate on Table 1 represents a classification category (in total 5 categories). The input layer is formatted such that each of the 148 explanatory variables feeds a neuron of the input layer. These neurons are then connected to other neurons in the hidden layer. In this example, we use 100 neurons for the hidden layer. Finally, the output layer has 5 units, one for each category. Figure 1 contains a graphical description of this neural network. Thus, we define our model: # Define modelmodel <- keras_model_sequential()model %>% layer_dense(units = 100, activation = "relu", input_shape = dim(train_data)[2]) %>% layer_dense(units = length(party_levels), activation = 'softmax') The activation function for the first stage (input to hidden layer) is Rectified Linear Unit, or ReLu, while the activation function for the second stage (hidden to output layer) is softmax. We now proceed to compile and train the model. The optimizer algorithm that we will use here is the adam, an adaptative optimization algorithm usually used to train deep neural networks. The loss function used is the sparse categorical crossentropy. Finally, we will take around 20% of our training data for the model to iteratively calculate the validation error. ###### Compile the model ######model %>% compile( optimizer = 'adam', loss = 'sparse_categorical_crossentropy', metrics = c('accuracy'))###### Train the Model #####early_stop <- callback_early_stopping(monitor = "val_loss", patience = 20)model %>% fit(train_data, train_labels, validation_split = 1/5, callbacks = list(early_stop), epochs = 500) The above algorithm will fit our neural network for 500 epochs, and it will stop before that if test model performance does not increase for 20 continuous epochs. Model Performance After training our model, we want to evaluate it using our test data by making predictions and looking at model performance: ###### Evaluate Model ######score <- model %>% evaluate(test_data, test_labels, verbose = 0)cat('Test loss:', score$loss, "\n")cat('Test accuracy:', score$acc, "\n") Test loss and accuracy of 0.4882 and 0.8461, respectively! Not bad! Even so, we would now like to take a look at where our model failed. A detailed presentation of the performance of the model is found in Figure 2. The image above contains a confusion matrix of the performance of our model. Correct classification rates (high accuracy on the diagonal and low values on the off-diagonal) are colored green, while incorrect classification rates (low values on the diagonal and high values on the off-diagonal) are colored red. A close look at the confusion matrix shows that the model made no correct predictions to the categories of “Did not vote” and “Not sure/Don’t recall”. This is due to the small number of observations that belonged to these categories relative to other categories: the number of respondents that answered “did not vote” or “not sure/don’t recall”, represent only 0.86% and 0.43% of the total sample, respectively (Table 1). Therefore, more information is required in order to accurately predict these categories: it is not enough to have information of the voter’s political and ideological preferences in order to know if the respondent did not vote or if they do not recall for whom they voted. Additionally, it may seem surprising that the model had a very poor performance assigning voters to the “others” category (a very poor 14.1% accuracy). This is especially true since about 9.91% of all observations belong to this category (see Table 1). Nonetheless, it is important to notice that this category includes a very diverse pool of presidential candidates, such as Gary Johnson (Libertarian Party) and Jill Stein (Green Party). These candidates have diverse political ideologies, and represent a heterogenous mix of voter preferences and demographics. Therefore, we may argue that it is actually expected that the model is unable to accurately predict any votes to presidential candidates that fall into this category. So, we built a model that predicts voter preferences. How do we forecast the outcome of an election? This is a significantly harder task and is out of the scope of this article, but a good start is training the model we developed here with poll data, and use data from an electoral roll to predict the political preferences of a given State or the whole US population. I hope you enjoyed this post and if you did, please let me know! Kuriwaki, Shiro, 2018, “Cumulative CCES Common Content (2006–2018)”, https://doi.org/10.7910/DVN/II2DB6, Harvard Dataverse, V4
[ { "code": null, "e": 691, "s": 171, "text": "With presidential elections around the corner, political analysts, forecasters, and other interested parties are running to build their best estimate of election outcomes. Traditionally, polls have been used to gauge the level of popularity of political candidates, but increased computing power and the development of powerful statistical methods provide an interesting alternative to them. A good place to start forecasting elections is to first predict voters’ political preferences. This is is what we will do here." }, { "code": null, "e": 801, "s": 691, "text": "In this article we will build a simple neural network in R to predict voter preferences in the United States." }, { "code": null, "e": 1042, "s": 801, "text": "We will do this using Keras, an amazing open-source API that allows you to run neural network models in a simple yet powerful way. Although it runs natively in Python, RStudio has developed a package that allows seamless integration with R." }, { "code": null, "e": 1174, "s": 1042, "text": "Before we start, please make sure you have the following R packages installed, as we will be using them to perform our predictions:" }, { "code": null, "e": 1308, "s": 1174, "text": "install.packages(\"keras\")install.packages(\"tidyr\")install.packages(\"ggplot2\")install.packages(\"dplyr\")install.packages(\"fastDummies\")" }, { "code": null, "e": 1313, "s": 1308, "text": "Data" }, { "code": null, "e": 1600, "s": 1313, "text": "The data used to train the neural network comes from the 2018 Cooperative Congressional Election Study, administered by YouGov. It was compiled by Kuriwaki (2018), and was extracted from the Harvard Dataverse. You can download this data in .Rds file format for the years 2006–2018 here." }, { "code": null, "e": 1731, "s": 1600, "text": "Assuming you downloaded the file and placed it in your working directory, we can proceed to import the data and see its structure:" }, { "code": null, "e": 1795, "s": 1731, "text": "d <- readRDS(\"cumulative_2006_2018.Rds\")dim(d)[1] 452755 73" }, { "code": null, "e": 2315, "s": 1795, "text": "d is a dataframe with 452,755 rows (observations) and 73 columns (features). These features include geographic, demographic, and economic variables, in addition to other interesting variables such as political approval and news interest levels. Of course, they also include the presidential vote choice of each individual. This last variable will be our dependent variable, e.g. what we will predict with our model. Finally, a detailed explanation of each variable is provided in the aforementioned dataset source link." }, { "code": null, "e": 2448, "s": 2315, "text": "Since we have data for the years 2006–2008, let’s filter d to select only the responses made in 2018, the year of the latest survey:" }, { "code": null, "e": 2482, "s": 2448, "text": "dd <- d %>% filter(year == 2018)" }, { "code": null, "e": 2590, "s": 2482, "text": "Additionally, let’s select only the variables that are of interest to our model and exclude missing values:" }, { "code": null, "e": 2889, "s": 2590, "text": "dd <- dd %>% select(st, dist, cong, # geography gender, birthyr, age, educ, race, faminc, marstat, # demographics newsint, # news interest approval_pres, # approval ideo5, # ideology voted_pres_16 # presidential vote )dd <- dd[complete.cases(dd),]" }, { "code": null, "e": 2929, "s": 2889, "text": "This is how this data frame looks like:" }, { "code": null, "e": 3254, "s": 2929, "text": "The table below presents the number of respondents for each of the categories of voter preferences (variable voted_pres_16). It can be seen that around 88% of the respondents voted for either Donald Trump or Hilary Clinton, 9.91% voted for another candidate, and around 1.3% did not reveal their preferences or did not vote." }, { "code": null, "e": 3534, "s": 3254, "text": "Coming back to our dataset dd, excluding the variable age, all our features are categorical. Thus, we need to one-hot encode these variables into dummies. There are many packages and functions to do this, but here we will use the function dummy_cols from the fastDummies package." }, { "code": null, "e": 3780, "s": 3534, "text": "cat_vars <- colnames(dd)cat_vars <- cat_vars[!cat_vars %in% c(\"age\",\"voted_pres_16\")]all_data <- dummy_cols(dd, select_columns = cat_vars, remove_first_dummy = TRUE, remove_selected_columns = TRUE)" }, { "code": null, "e": 3978, "s": 3780, "text": "We also convert our dependent variable, voted_pres_16 into a numeric vector with integers (starting at zero) for each of the candidates, and we remove the variable voted_pres_16 from our dataframe:" }, { "code": null, "e": 4110, "s": 3978, "text": "all_labels <- dd$voted_pres_16 %>% as.factor() %>% unclass() - 1all_data <- all_data %>% select(-voted_pres_16) %>% as.matrix()" }, { "code": null, "e": 4265, "s": 4110, "text": "Finally, we separate our data into a training set (90%) and a test set (10%), so that after we train our model, we can test its performance on “new” data." }, { "code": null, "e": 4632, "s": 4265, "text": "party_levels <- levels(all_labels)elems <- sample(1:nrow(all_data), round(0.1*nrow(all_data)), replace = F)# training datatrain_data <- all_data[-elems,]train_labels <- all_labels[-elems]levels(train_labels) <- levels(all_labels)# test datatest_data <- all_data[elems,]test_labels <- all_labels[elems]levels(test_labels) <- party_levels" }, { "code": null, "e": 4651, "s": 4632, "text": "Building the model" }, { "code": null, "e": 5174, "s": 4651, "text": "Our problem at hand is modeled as a classification problem, where each candidate on Table 1 represents a classification category (in total 5 categories). The input layer is formatted such that each of the 148 explanatory variables feeds a neuron of the input layer. These neurons are then connected to other neurons in the hidden layer. In this example, we use 100 neurons for the hidden layer. Finally, the output layer has 5 units, one for each category. Figure 1 contains a graphical description of this neural network." }, { "code": null, "e": 5201, "s": 5174, "text": "Thus, we define our model:" }, { "code": null, "e": 5424, "s": 5201, "text": "# Define modelmodel <- keras_model_sequential()model %>% layer_dense(units = 100, activation = \"relu\", input_shape = dim(train_data)[2]) %>% layer_dense(units = length(party_levels), activation = 'softmax') " }, { "code": null, "e": 5615, "s": 5424, "text": "The activation function for the first stage (input to hidden layer) is Rectified Linear Unit, or ReLu, while the activation function for the second stage (hidden to output layer) is softmax." }, { "code": null, "e": 5980, "s": 5615, "text": "We now proceed to compile and train the model. The optimizer algorithm that we will use here is the adam, an adaptative optimization algorithm usually used to train deep neural networks. The loss function used is the sparse categorical crossentropy. Finally, we will take around 20% of our training data for the model to iteratively calculate the validation error." }, { "code": null, "e": 6421, "s": 5980, "text": "###### Compile the model ######model %>% compile( optimizer = 'adam', loss = 'sparse_categorical_crossentropy', metrics = c('accuracy'))###### Train the Model #####early_stop <- callback_early_stopping(monitor = \"val_loss\", patience = 20)model %>% fit(train_data, train_labels, validation_split = 1/5, callbacks = list(early_stop), epochs = 500)" }, { "code": null, "e": 6584, "s": 6421, "text": "The above algorithm will fit our neural network for 500 epochs, and it will stop before that if test model performance does not increase for 20 continuous epochs." }, { "code": null, "e": 6602, "s": 6584, "text": "Model Performance" }, { "code": null, "e": 6727, "s": 6602, "text": "After training our model, we want to evaluate it using our test data by making predictions and looking at model performance:" }, { "code": null, "e": 6893, "s": 6727, "text": "###### Evaluate Model ######score <- model %>% evaluate(test_data, test_labels, verbose = 0)cat('Test loss:', score$loss, \"\\n\")cat('Test accuracy:', score$acc, \"\\n\")" }, { "code": null, "e": 6961, "s": 6893, "text": "Test loss and accuracy of 0.4882 and 0.8461, respectively! Not bad!" }, { "code": null, "e": 7108, "s": 6961, "text": "Even so, we would now like to take a look at where our model failed. A detailed presentation of the performance of the model is found in Figure 2." }, { "code": null, "e": 7419, "s": 7108, "text": "The image above contains a confusion matrix of the performance of our model. Correct classification rates (high accuracy on the diagonal and low values on the off-diagonal) are colored green, while incorrect classification rates (low values on the diagonal and high values on the off-diagonal) are colored red." }, { "code": null, "e": 8114, "s": 7419, "text": "A close look at the confusion matrix shows that the model made no correct predictions to the categories of “Did not vote” and “Not sure/Don’t recall”. This is due to the small number of observations that belonged to these categories relative to other categories: the number of respondents that answered “did not vote” or “not sure/don’t recall”, represent only 0.86% and 0.43% of the total sample, respectively (Table 1). Therefore, more information is required in order to accurately predict these categories: it is not enough to have information of the voter’s political and ideological preferences in order to know if the respondent did not vote or if they do not recall for whom they voted." }, { "code": null, "e": 8844, "s": 8114, "text": "Additionally, it may seem surprising that the model had a very poor performance assigning voters to the “others” category (a very poor 14.1% accuracy). This is especially true since about 9.91% of all observations belong to this category (see Table 1). Nonetheless, it is important to notice that this category includes a very diverse pool of presidential candidates, such as Gary Johnson (Libertarian Party) and Jill Stein (Green Party). These candidates have diverse political ideologies, and represent a heterogenous mix of voter preferences and demographics. Therefore, we may argue that it is actually expected that the model is unable to accurately predict any votes to presidential candidates that fall into this category." }, { "code": null, "e": 8945, "s": 8844, "text": "So, we built a model that predicts voter preferences. How do we forecast the outcome of an election?" }, { "code": null, "e": 9213, "s": 8945, "text": "This is a significantly harder task and is out of the scope of this article, but a good start is training the model we developed here with poll data, and use data from an electoral roll to predict the political preferences of a given State or the whole US population." }, { "code": null, "e": 9278, "s": 9213, "text": "I hope you enjoyed this post and if you did, please let me know!" } ]
How to Iterate over rows and columns in PySpark dataframe - GeeksforGeeks
23 Dec, 2021 In this article, we will discuss how to iterate rows and columns in PySpark dataframe. Create the dataframe for demonstration: Python3 # importing module import pyspark # importing sparksession from pyspark.sql module from pyspark.sql import SparkSession # creating sparksession and giving an app name spark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee data data = [["1", "sravan", "company 1"], ["2", "ojaswi", "company 1"], ["3", "rohith", "company 2"], ["4", "sridevi", "company 1"], ["5", "bobby", "company 1"]] # specify column names columns = ['ID', 'NAME', 'Company'] # creating a dataframe from the lists of data dataframe = spark.createDataFrame(data, columns) dataframe.show() Output: This method will collect all the rows and columns of the dataframe and then loop through it using for loop. Here an iterator is used to iterate over a loop from the collected elements using the collect() method. Syntax: for itertator in dataframe.collect(): print(itertator["column_name"],...............) where, dataframe is the input dataframe itertator is used to collect rows column_name is the column to iterate rows Example: Here we are going to iterate all the columns in the dataframe with collect() method and inside the for loop, we are specifying iterator[‘column_name’] to get column values. Python3 # importing module import pyspark # importing sparksession from pyspark.sql module from pyspark.sql import SparkSession # creating sparksession and giving an app name spark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee data data = [["1", "sravan", "company 1"], ["2", "ojaswi", "company 1"], ["3", "rohith", "company 2"], ["4", "sridevi", "company 1"], ["5", "bobby", "company 1"]] # specify column names columns = ['ID', 'NAME', 'Company'] # creating a dataframe from the lists of data dataframe = spark.createDataFrame(data, columns) # using collect for i in dataframe.collect(): # display print(i["ID"], i["NAME"], i["Company"]) Output: It will return the iterator that contains all rows and columns in RDD. It is similar to the collect() method, But it is in rdd format, so it is available inside the rdd method. We can use the toLocalIterator() with rdd like: dataframe.rdd.toLocalIterator() For iterating the all rows and columns we are iterating this inside an for loop Syntax: for itertator in dataframe.rdd.toLocalIterator(): print(itertator["column_name"],...............) where, dataframe is the input dataframe itertator is used to collect rows column_name is the column to iterate rows Example: Here we are going to iterate all the columns in the dataframe with toLocalIterator() method and inside the for loop, we are specifying iterator[‘column_name’] to get column values. Python3 # importing module import pyspark # importing sparksession from pyspark.sql module from pyspark.sql import SparkSession # creating sparksession and giving an app name spark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee data data = [["1", "sravan", "company 1"], ["2", "ojaswi", "company 1"], ["3", "rohith", "company 2"], ["4", "sridevi", "company 1"], ["5", "bobby", "company 1"]] # specify column names columns = ['ID', 'NAME', 'Company'] # creating a dataframe from the lists of data dataframe = spark.createDataFrame(data, columns) # using toLocalIterator() for i in dataframe.rdd.toLocalIterator(): # display print(i["ID"], i["NAME"], i["Company"]) Output: This will iterate rows. Before that, we have to convert our PySpark dataframe into Pandas dataframe using toPandas() method. This method is used to iterate row by row in the dataframe. Syntax: dataframe.toPandas().iterrows() Example: In this example, we are going to iterate three-column rows using iterrows() using for loop. Python3 # importing module import pyspark # importing sparksession from pyspark.sql module from pyspark.sql import SparkSession # creating sparksession and giving an app name spark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee data data = [["1", "sravan", "company 1"], ["2", "ojaswi", "company 1"], ["3", "rohith", "company 2"], ["4", "sridevi", "company 1"], ["5", "bobby", "company 1"]] # specify column names columns = ['ID', 'NAME', 'Company'] # creating a dataframe from the lists of data dataframe = spark.createDataFrame(data, columns) # using iterrows() for index, row in dataframe.toPandas().iterrows(): # display with index print(row[0], row[1], row[2]) Output: The select() function is used to select the number of columns. we are then using the collect() function to get the rows through for loop. The select method will select the columns which are mentioned and get the row data using collect() method. This method will collect rows from the given columns. Syntax: dataframe.select(“column1′′,............,”column n”).collect() Example: Here we are going to select ID and Name columns from the given dataframe using the select() method Python3 # importing module import pyspark # importing sparksession from pyspark.sql module from pyspark.sql import SparkSession # creating sparksession and giving an app name spark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee data data = [["1", "sravan", "company 1"], ["2", "ojaswi", "company 1"], ["3", "rohith", "company 2"], ["4", "sridevi", "company 1"], ["5", "bobby", "company 1"]] # specify column names columns = ['ID', 'NAME', 'Company'] # creating a dataframe from the lists of data dataframe = spark.createDataFrame(data, columns) # select only id and company for rows in dataframe.select("ID", "Name").collect(): # display print(rows[0], rows[1]) Output: This will act as a loop to get each row and finally we can use for loop to get particular columns, we are going to iterate the data in the given column using the collect() method through rdd. Syntax: dataframe.rdd.collect() Example: Here we are going to iterate rows in NAME column. Python3 # importing module import pyspark # importing sparksession from pyspark.sql module from pyspark.sql import SparkSession # creating sparksession and giving an app name spark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee data data = [["1", "sravan", "company 1"], ["2", "ojaswi", "company 1"], ["3", "rohith", "company 2"], ["4", "sridevi", "company 1"], ["5", "bobby", "company 1"]] # specify column names columns = ['ID', 'NAME', 'Company'] # creating a dataframe from the lists of data dataframe = spark.createDataFrame(data, columns) # select name column for i in [j["NAME"] for j in dataframe.rdd.collect()]: print(i) Output: sravan ojaswi rohith sridevi bobby In this method, we will use map() function, which returns a new vfrom a given dataframe or RDD. The map() function is used with the lambda function to iterate through each row of the pyspark Dataframe. For looping through each row using map() first we have to convert the PySpark dataframe into RDD because map() is performed on RDD’s only, so first convert into RDD it then use map() in which, lambda function for iterating through each row and stores the new RDD in some variable then convert back that new RDD into Dataframe using toDF() by passing schema into it. Syntax: rdd=dataframe.rdd.map(lambda loop: ( loop["column1"],...,loop["columnn"]) ) rdd.toDF(["column1",.......,"columnn"]).collect() Example: Here we are going to iterate ID and NAME column Python3 # importing module import pyspark # importing sparksession from pyspark.sql module from pyspark.sql import SparkSession # creating sparksession and giving an app name spark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee data data = [["1", "sravan", "company 1"], ["2", "ojaswi", "company 1"], ["3", "rohith", "company 2"], ["4", "sridevi", "company 1"], ["5", "bobby", "company 1"]] # specify column names columns = ['ID', 'NAME', 'Company'] # creating a dataframe from the lists of data dataframe = spark.createDataFrame(data, columns) # select id and name column using map() rdd = dataframe.rdd.map(lambda loop: ( loop["ID"], loop["NAME"])) # convert to dataframe and display rdd.toDF(["ID", "NAME"]).collect() Output: [Row(ID='1', NAME='sravan'), Row(ID='2', NAME='ojaswi'), Row(ID='3', NAME='rohith'), Row(ID='4', NAME='sridevi'), Row(ID='5', NAME='bobby')] surindertarika1234 Picked Python-Pyspark Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Enumerate() in Python How to Install PIP on Windows ? Different ways to create Pandas Dataframe Reading and Writing to text files in Python 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
[ { "code": null, "e": 25006, "s": 24975, "text": " \n23 Dec, 2021\n" }, { "code": null, "e": 25093, "s": 25006, "text": "In this article, we will discuss how to iterate rows and columns in PySpark dataframe." }, { "code": null, "e": 25133, "s": 25093, "text": "Create the dataframe for demonstration:" }, { "code": null, "e": 25141, "s": 25133, "text": "Python3" }, { "code": "\n\n\n\n\n\n\n# importing module\nimport pyspark\n \n# importing sparksession from pyspark.sql module\nfrom pyspark.sql import SparkSession\n \n# creating sparksession and giving an app name\nspark = SparkSession.builder.appName('sparkdf').getOrCreate()\n \n# list of employee data\ndata = [[\"1\", \"sravan\", \"company 1\"],\n [\"2\", \"ojaswi\", \"company 1\"],\n [\"3\", \"rohith\", \"company 2\"],\n [\"4\", \"sridevi\", \"company 1\"],\n [\"5\", \"bobby\", \"company 1\"]]\n \n# specify column names\ncolumns = ['ID', 'NAME', 'Company']\n \n# creating a dataframe from the lists of data\ndataframe = spark.createDataFrame(data, columns)\n \ndataframe.show()\n\n\n\n\n\n", "e": 25791, "s": 25151, "text": null }, { "code": null, "e": 25799, "s": 25791, "text": "Output:" }, { "code": null, "e": 26011, "s": 25799, "text": "This method will collect all the rows and columns of the dataframe and then loop through it using for loop. Here an iterator is used to iterate over a loop from the collected elements using the collect() method." }, { "code": null, "e": 26019, "s": 26011, "text": "Syntax:" }, { "code": null, "e": 26125, "s": 26019, "text": "for itertator in dataframe.collect():\n print(itertator[\"column_name\"],...............)" }, { "code": null, "e": 26132, "s": 26125, "text": "where," }, { "code": null, "e": 26165, "s": 26132, "text": "dataframe is the input dataframe" }, { "code": null, "e": 26199, "s": 26165, "text": "itertator is used to collect rows" }, { "code": null, "e": 26241, "s": 26199, "text": "column_name is the column to iterate rows" }, { "code": null, "e": 26423, "s": 26241, "text": "Example: Here we are going to iterate all the columns in the dataframe with collect() method and inside the for loop, we are specifying iterator[‘column_name’] to get column values." }, { "code": null, "e": 26431, "s": 26423, "text": "Python3" }, { "code": "\n\n\n\n\n\n\n# importing module\nimport pyspark\n \n# importing sparksession from pyspark.sql module\nfrom pyspark.sql import SparkSession\n \n# creating sparksession and giving an app name\nspark = SparkSession.builder.appName('sparkdf').getOrCreate()\n \n# list of employee data\ndata = [[\"1\", \"sravan\", \"company 1\"],\n [\"2\", \"ojaswi\", \"company 1\"],\n [\"3\", \"rohith\", \"company 2\"],\n [\"4\", \"sridevi\", \"company 1\"],\n [\"5\", \"bobby\", \"company 1\"]]\n \n# specify column names\ncolumns = ['ID', 'NAME', 'Company']\n \n# creating a dataframe from the lists of data\ndataframe = spark.createDataFrame(data, columns)\n \n# using collect\nfor i in dataframe.collect():\n # display\n print(i[\"ID\"], i[\"NAME\"], i[\"Company\"])\n\n\n\n\n\n", "e": 27168, "s": 26441, "text": null }, { "code": null, "e": 27176, "s": 27168, "text": "Output:" }, { "code": null, "e": 27401, "s": 27176, "text": "It will return the iterator that contains all rows and columns in RDD. It is similar to the collect() method, But it is in rdd format, so it is available inside the rdd method. We can use the toLocalIterator() with rdd like:" }, { "code": null, "e": 27433, "s": 27401, "text": "dataframe.rdd.toLocalIterator()" }, { "code": null, "e": 27513, "s": 27433, "text": "For iterating the all rows and columns we are iterating this inside an for loop" }, { "code": null, "e": 27521, "s": 27513, "text": "Syntax:" }, { "code": null, "e": 27639, "s": 27521, "text": "for itertator in dataframe.rdd.toLocalIterator():\n print(itertator[\"column_name\"],...............)" }, { "code": null, "e": 27646, "s": 27639, "text": "where," }, { "code": null, "e": 27679, "s": 27646, "text": "dataframe is the input dataframe" }, { "code": null, "e": 27713, "s": 27679, "text": "itertator is used to collect rows" }, { "code": null, "e": 27755, "s": 27713, "text": "column_name is the column to iterate rows" }, { "code": null, "e": 27945, "s": 27755, "text": "Example: Here we are going to iterate all the columns in the dataframe with toLocalIterator() method and inside the for loop, we are specifying iterator[‘column_name’] to get column values." }, { "code": null, "e": 27953, "s": 27945, "text": "Python3" }, { "code": "\n\n\n\n\n\n\n# importing module\nimport pyspark\n \n# importing sparksession from pyspark.sql module\nfrom pyspark.sql import SparkSession\n \n# creating sparksession and giving an app name\nspark = SparkSession.builder.appName('sparkdf').getOrCreate()\n \n# list of employee data\ndata = [[\"1\", \"sravan\", \"company 1\"],\n [\"2\", \"ojaswi\", \"company 1\"],\n [\"3\", \"rohith\", \"company 2\"],\n [\"4\", \"sridevi\", \"company 1\"],\n [\"5\", \"bobby\", \"company 1\"]]\n \n# specify column names\ncolumns = ['ID', 'NAME', 'Company']\n \n# creating a dataframe from the lists of data\ndataframe = spark.createDataFrame(data, columns)\n \n# using toLocalIterator()\nfor i in dataframe.rdd.toLocalIterator():\n \n # display\n print(i[\"ID\"], i[\"NAME\"], i[\"Company\"])\n\n\n\n\n\n", "e": 28716, "s": 27963, "text": null }, { "code": null, "e": 28724, "s": 28716, "text": "Output:" }, { "code": null, "e": 28909, "s": 28724, "text": "This will iterate rows. Before that, we have to convert our PySpark dataframe into Pandas dataframe using toPandas() method. This method is used to iterate row by row in the dataframe." }, { "code": null, "e": 28949, "s": 28909, "text": "Syntax: dataframe.toPandas().iterrows()" }, { "code": null, "e": 29050, "s": 28949, "text": "Example: In this example, we are going to iterate three-column rows using iterrows() using for loop." }, { "code": null, "e": 29058, "s": 29050, "text": "Python3" }, { "code": "\n\n\n\n\n\n\n# importing module\nimport pyspark\n \n# importing sparksession from pyspark.sql module\nfrom pyspark.sql import SparkSession\n \n# creating sparksession and giving an app name\nspark = SparkSession.builder.appName('sparkdf').getOrCreate()\n \n# list of employee data\ndata = [[\"1\", \"sravan\", \"company 1\"],\n [\"2\", \"ojaswi\", \"company 1\"],\n [\"3\", \"rohith\", \"company 2\"],\n [\"4\", \"sridevi\", \"company 1\"],\n [\"5\", \"bobby\", \"company 1\"]]\n \n# specify column names\ncolumns = ['ID', 'NAME', 'Company']\n \n# creating a dataframe from the lists of data\ndataframe = spark.createDataFrame(data, columns)\n \n# using iterrows()\nfor index, row in dataframe.toPandas().iterrows():\n # display with index\n print(row[0], row[1], row[2])\n\n\n\n\n\n", "e": 29820, "s": 29068, "text": null }, { "code": null, "e": 29828, "s": 29820, "text": "Output:" }, { "code": null, "e": 29966, "s": 29828, "text": "The select() function is used to select the number of columns. we are then using the collect() function to get the rows through for loop." }, { "code": null, "e": 30127, "s": 29966, "text": "The select method will select the columns which are mentioned and get the row data using collect() method. This method will collect rows from the given columns." }, { "code": null, "e": 30198, "s": 30127, "text": "Syntax: dataframe.select(“column1′′,............,”column n”).collect()" }, { "code": null, "e": 30306, "s": 30198, "text": "Example: Here we are going to select ID and Name columns from the given dataframe using the select() method" }, { "code": null, "e": 30314, "s": 30306, "text": "Python3" }, { "code": "\n\n\n\n\n\n\n# importing module\nimport pyspark\n \n# importing sparksession from pyspark.sql module\nfrom pyspark.sql import SparkSession\n \n# creating sparksession and giving an app name\nspark = SparkSession.builder.appName('sparkdf').getOrCreate()\n \n# list of employee data\ndata = [[\"1\", \"sravan\", \"company 1\"],\n [\"2\", \"ojaswi\", \"company 1\"],\n [\"3\", \"rohith\", \"company 2\"],\n [\"4\", \"sridevi\", \"company 1\"],\n [\"5\", \"bobby\", \"company 1\"]]\n \n# specify column names\ncolumns = ['ID', 'NAME', 'Company']\n \n# creating a dataframe from the lists of data\ndataframe = spark.createDataFrame(data, columns)\n \n# select only id and company\nfor rows in dataframe.select(\"ID\", \"Name\").collect():\n # display\n print(rows[0], rows[1])\n\n\n\n\n\n", "e": 31075, "s": 30324, "text": null }, { "code": null, "e": 31083, "s": 31075, "text": "Output:" }, { "code": null, "e": 31275, "s": 31083, "text": "This will act as a loop to get each row and finally we can use for loop to get particular columns, we are going to iterate the data in the given column using the collect() method through rdd." }, { "code": null, "e": 31307, "s": 31275, "text": "Syntax: dataframe.rdd.collect()" }, { "code": null, "e": 31366, "s": 31307, "text": "Example: Here we are going to iterate rows in NAME column." }, { "code": null, "e": 31374, "s": 31366, "text": "Python3" }, { "code": "\n\n\n\n\n\n\n# importing module\nimport pyspark\n \n# importing sparksession from pyspark.sql module\nfrom pyspark.sql import SparkSession\n \n# creating sparksession and giving an app name\nspark = SparkSession.builder.appName('sparkdf').getOrCreate()\n \n# list of employee data\ndata = [[\"1\", \"sravan\", \"company 1\"],\n [\"2\", \"ojaswi\", \"company 1\"],\n [\"3\", \"rohith\", \"company 2\"],\n [\"4\", \"sridevi\", \"company 1\"],\n [\"5\", \"bobby\", \"company 1\"]]\n \n# specify column names\ncolumns = ['ID', 'NAME', 'Company']\n \n# creating a dataframe from the lists of data\ndataframe = spark.createDataFrame(data, columns)\n \n# select name column\nfor i in [j[\"NAME\"] for j in dataframe.rdd.collect()]:\n print(i)\n\n\n\n\n\n", "e": 32096, "s": 31384, "text": null }, { "code": null, "e": 32104, "s": 32096, "text": "Output:" }, { "code": null, "e": 32139, "s": 32104, "text": "sravan\nojaswi\nrohith\nsridevi\nbobby" }, { "code": null, "e": 32342, "s": 32139, "text": "In this method, we will use map() function, which returns a new vfrom a given dataframe or RDD. The map() function is used with the lambda function to iterate through each row of the pyspark Dataframe." }, { "code": null, "e": 32708, "s": 32342, "text": "For looping through each row using map() first we have to convert the PySpark dataframe into RDD because map() is performed on RDD’s only, so first convert into RDD it then use map() in which, lambda function for iterating through each row and stores the new RDD in some variable then convert back that new RDD into Dataframe using toDF() by passing schema into it." }, { "code": null, "e": 32716, "s": 32708, "text": "Syntax:" }, { "code": null, "e": 32849, "s": 32716, "text": "rdd=dataframe.rdd.map(lambda loop: (\n loop[\"column1\"],...,loop[\"columnn\"]) )\n rdd.toDF([\"column1\",.......,\"columnn\"]).collect()" }, { "code": null, "e": 32906, "s": 32849, "text": "Example: Here we are going to iterate ID and NAME column" }, { "code": null, "e": 32914, "s": 32906, "text": "Python3" }, { "code": "\n\n\n\n\n\n\n# importing module\nimport pyspark\n \n# importing sparksession from pyspark.sql module\nfrom pyspark.sql import SparkSession\n \n# creating sparksession and giving an app name\nspark = SparkSession.builder.appName('sparkdf').getOrCreate()\n \n# list of employee data\ndata = [[\"1\", \"sravan\", \"company 1\"],\n [\"2\", \"ojaswi\", \"company 1\"],\n [\"3\", \"rohith\", \"company 2\"],\n [\"4\", \"sridevi\", \"company 1\"],\n [\"5\", \"bobby\", \"company 1\"]]\n \n# specify column names\ncolumns = ['ID', 'NAME', 'Company']\n \n# creating a dataframe from the lists of data\ndataframe = spark.createDataFrame(data, columns)\n \n# select id and name column using map()\nrdd = dataframe.rdd.map(lambda loop: (\n loop[\"ID\"], loop[\"NAME\"]))\n \n# convert to dataframe and display\nrdd.toDF([\"ID\", \"NAME\"]).collect()\n\n\n\n\n\n", "e": 33729, "s": 32924, "text": null }, { "code": null, "e": 33737, "s": 33729, "text": "Output:" }, { "code": null, "e": 33878, "s": 33737, "text": "[Row(ID='1', NAME='sravan'),\nRow(ID='2', NAME='ojaswi'),\nRow(ID='3', NAME='rohith'),\nRow(ID='4', NAME='sridevi'),\nRow(ID='5', NAME='bobby')]" }, { "code": null, "e": 33897, "s": 33878, "text": "surindertarika1234" }, { "code": null, "e": 33906, "s": 33897, "text": "\nPicked\n" }, { "code": null, "e": 33923, "s": 33906, "text": "\nPython-Pyspark\n" }, { "code": null, "e": 33932, "s": 33923, "text": "\nPython\n" }, { "code": null, "e": 34137, "s": 33932, "text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n " }, { "code": null, "e": 34155, "s": 34137, "text": "Python Dictionary" }, { "code": null, "e": 34177, "s": 34155, "text": "Enumerate() in Python" }, { "code": null, "e": 34209, "s": 34177, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 34251, "s": 34209, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 34295, "s": 34251, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 34332, "s": 34295, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 34357, "s": 34332, "text": "sum() function in Python" }, { "code": null, "e": 34386, "s": 34357, "text": "*args and **kwargs in Python" }, { "code": null, "e": 34442, "s": 34386, "text": "How to drop one or multiple columns in Pandas Dataframe" } ]
How to Make Boxplots with Data Points using Seaborn in Python? - GeeksforGeeks
03 Jan, 2021 Seaborn Matplotlib Box Plot or a Whisker Plot is a statistical plot to visualize graphically, depicting group of numerical data through their quartiles. This plot displays the summary of set of data containing the five values known as minimum, quartile 1, quartile 2 or median, quartile 3 and maximum, where the box is drawn from first quartile to third quartile. A generic box plot mainly focuses on the five elements mentioned above to give the user a quartile based interpretation of the data, but it is possible to show data points on the box plot itself, making it more informative. For this seaborn is equipped with stripplot() function, all we have to do is call it just after boxplot() function with appropriate parameters to generate a boxplot with data points. A strip plot is drawn on its own. It is a good complement to a boxplot or violinplot in cases where all observations are shown along with some representation of the underlying distribution. It is used to draw a scatter plot based on the category. Syntax: seaborn.stripplot(*, x=None, y=None, hue=None, data=None, order=None, hue_order=None, jitter=True, dodge=False, orient=None, color=None, palette=None, size=5, edgecolor=’gray’, linewidth=0, ax=None, **kwargs) Parameters: x, y, hue: Inputs for plotting long-form data. data: Dataset for plotting. order: It is the order to plot the categorical levels in. color: It is the color for all of the elements, or seed for a gradient palette Returns: This method returns the Axes object with the plot drawn onto it. Import the library Create or load the dataset. Plot a boxplot using boxplot(). Add data points using stripplot(). Display plot. Given below are few implementations to help you understand better Example 1: Regular box plot for comparison Python # importing libraryimport seaborn as snsimport matplotlib.pyplot as plt # loading seaborn dataset tipstdata = sns.load_dataset('tips') # creating boxplotsns.boxplot(x='size', y='tip', data=tdata) # display plotplt.show() Output: Example 2: Creating box plot with data points Python # importing libraryimport seaborn as snsimport matplotlib.pyplot as plt# loading seaborn dataset tipstdata = sns.load_dataset('tips') # creating boxplotsns.boxplot(x='size', y='tip', data=tdata) # adding data pointssns.stripplot(x='size', y='tip', data=tdata)# display plotplt.show() Output: Example 3: Boxplot with data points with non-default color Python # importing libraryimport seaborn as snsimport matplotlib.pyplot as plt# loading seaborn dataset tipstdata = sns.load_dataset('tips') # creating boxplotsns.boxplot(x='size', y='tip', data=tdata) # adding data pointssns.stripplot(x='size', y='tip', data=tdata, color="grey")# display plotplt.show() Output: Example 4: Changing size of the data points Python # importing libraryimport seaborn as snsimport matplotlib.pyplot as plt# loading seaborn dataset tipstdata = sns.load_dataset('tips') tdata = tdata.head(10)# creating boxplotsns.boxplot(x='size', y='tip', data=tdata) # adding data pointssns.stripplot(x='size', y='tip', data=tdata, color="grey", size=8)# display plotplt.show() Output: Example 5: Plotting transparent data points Python # importing libraryimport seaborn as snsimport matplotlib.pyplot as plt# loading seaborn dataset tipstdata = sns.load_dataset('tips') tdata = tdata.head(20)# creating boxplotsns.boxplot(x='size', y='tip', data=tdata) # adding data pointssns.stripplot(x='size', y='tip', data=tdata, color="black", size=8, alpha=0.5)# display plotplt.show() Output: Picked Python-Seaborn Technical Scripter 2020 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How To Convert Python Dictionary To JSON? Check if element exists in list in Python How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Create a directory in Python Defaultdict in Python Python | Get unique values from a list Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25689, "s": 25661, "text": "\n03 Jan, 2021" }, { "code": null, "e": 25697, "s": 25689, "text": "Seaborn" }, { "code": null, "e": 25708, "s": 25697, "text": "Matplotlib" }, { "code": null, "e": 26053, "s": 25708, "text": "Box Plot or a Whisker Plot is a statistical plot to visualize graphically, depicting group of numerical data through their quartiles. This plot displays the summary of set of data containing the five values known as minimum, quartile 1, quartile 2 or median, quartile 3 and maximum, where the box is drawn from first quartile to third quartile." }, { "code": null, "e": 26460, "s": 26053, "text": "A generic box plot mainly focuses on the five elements mentioned above to give the user a quartile based interpretation of the data, but it is possible to show data points on the box plot itself, making it more informative. For this seaborn is equipped with stripplot() function, all we have to do is call it just after boxplot() function with appropriate parameters to generate a boxplot with data points." }, { "code": null, "e": 26707, "s": 26460, "text": "A strip plot is drawn on its own. It is a good complement to a boxplot or violinplot in cases where all observations are shown along with some representation of the underlying distribution. It is used to draw a scatter plot based on the category." }, { "code": null, "e": 26924, "s": 26707, "text": "Syntax: seaborn.stripplot(*, x=None, y=None, hue=None, data=None, order=None, hue_order=None, jitter=True, dodge=False, orient=None, color=None, palette=None, size=5, edgecolor=’gray’, linewidth=0, ax=None, **kwargs)" }, { "code": null, "e": 26936, "s": 26924, "text": "Parameters:" }, { "code": null, "e": 26983, "s": 26936, "text": "x, y, hue: Inputs for plotting long-form data." }, { "code": null, "e": 27011, "s": 26983, "text": "data: Dataset for plotting." }, { "code": null, "e": 27069, "s": 27011, "text": "order: It is the order to plot the categorical levels in." }, { "code": null, "e": 27148, "s": 27069, "text": "color: It is the color for all of the elements, or seed for a gradient palette" }, { "code": null, "e": 27222, "s": 27148, "text": "Returns: This method returns the Axes object with the plot drawn onto it." }, { "code": null, "e": 27241, "s": 27222, "text": "Import the library" }, { "code": null, "e": 27269, "s": 27241, "text": "Create or load the dataset." }, { "code": null, "e": 27301, "s": 27269, "text": "Plot a boxplot using boxplot()." }, { "code": null, "e": 27336, "s": 27301, "text": "Add data points using stripplot()." }, { "code": null, "e": 27350, "s": 27336, "text": "Display plot." }, { "code": null, "e": 27417, "s": 27350, "text": "Given below are few implementations to help you understand better " }, { "code": null, "e": 27460, "s": 27417, "text": "Example 1: Regular box plot for comparison" }, { "code": null, "e": 27467, "s": 27460, "text": "Python" }, { "code": "# importing libraryimport seaborn as snsimport matplotlib.pyplot as plt # loading seaborn dataset tipstdata = sns.load_dataset('tips') # creating boxplotsns.boxplot(x='size', y='tip', data=tdata) # display plotplt.show()", "e": 27691, "s": 27467, "text": null }, { "code": null, "e": 27699, "s": 27691, "text": "Output:" }, { "code": null, "e": 27745, "s": 27699, "text": "Example 2: Creating box plot with data points" }, { "code": null, "e": 27752, "s": 27745, "text": "Python" }, { "code": "# importing libraryimport seaborn as snsimport matplotlib.pyplot as plt# loading seaborn dataset tipstdata = sns.load_dataset('tips') # creating boxplotsns.boxplot(x='size', y='tip', data=tdata) # adding data pointssns.stripplot(x='size', y='tip', data=tdata)# display plotplt.show()", "e": 28038, "s": 27752, "text": null }, { "code": null, "e": 28046, "s": 28038, "text": "Output:" }, { "code": null, "e": 28105, "s": 28046, "text": "Example 3: Boxplot with data points with non-default color" }, { "code": null, "e": 28112, "s": 28105, "text": "Python" }, { "code": "# importing libraryimport seaborn as snsimport matplotlib.pyplot as plt# loading seaborn dataset tipstdata = sns.load_dataset('tips') # creating boxplotsns.boxplot(x='size', y='tip', data=tdata) # adding data pointssns.stripplot(x='size', y='tip', data=tdata, color=\"grey\")# display plotplt.show()", "e": 28412, "s": 28112, "text": null }, { "code": null, "e": 28420, "s": 28412, "text": "Output:" }, { "code": null, "e": 28464, "s": 28420, "text": "Example 4: Changing size of the data points" }, { "code": null, "e": 28471, "s": 28464, "text": "Python" }, { "code": "# importing libraryimport seaborn as snsimport matplotlib.pyplot as plt# loading seaborn dataset tipstdata = sns.load_dataset('tips') tdata = tdata.head(10)# creating boxplotsns.boxplot(x='size', y='tip', data=tdata) # adding data pointssns.stripplot(x='size', y='tip', data=tdata, color=\"grey\", size=8)# display plotplt.show()", "e": 28801, "s": 28471, "text": null }, { "code": null, "e": 28809, "s": 28801, "text": "Output:" }, { "code": null, "e": 28853, "s": 28809, "text": "Example 5: Plotting transparent data points" }, { "code": null, "e": 28860, "s": 28853, "text": "Python" }, { "code": "# importing libraryimport seaborn as snsimport matplotlib.pyplot as plt# loading seaborn dataset tipstdata = sns.load_dataset('tips') tdata = tdata.head(20)# creating boxplotsns.boxplot(x='size', y='tip', data=tdata) # adding data pointssns.stripplot(x='size', y='tip', data=tdata, color=\"black\", size=8, alpha=0.5)# display plotplt.show()", "e": 29202, "s": 28860, "text": null }, { "code": null, "e": 29210, "s": 29202, "text": "Output:" }, { "code": null, "e": 29217, "s": 29210, "text": "Picked" }, { "code": null, "e": 29232, "s": 29217, "text": "Python-Seaborn" }, { "code": null, "e": 29256, "s": 29232, "text": "Technical Scripter 2020" }, { "code": null, "e": 29263, "s": 29256, "text": "Python" }, { "code": null, "e": 29282, "s": 29263, "text": "Technical Scripter" }, { "code": null, "e": 29380, "s": 29282, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29412, "s": 29380, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29454, "s": 29412, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 29496, "s": 29454, "text": "Check if element exists in list in Python" }, { "code": null, "e": 29552, "s": 29496, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 29579, "s": 29552, "text": "Python Classes and Objects" }, { "code": null, "e": 29610, "s": 29579, "text": "Python | os.path.join() method" }, { "code": null, "e": 29639, "s": 29610, "text": "Create a directory in Python" }, { "code": null, "e": 29661, "s": 29639, "text": "Defaultdict in Python" }, { "code": null, "e": 29700, "s": 29661, "text": "Python | Get unique values from a list" } ]
Ruby Directories - GeeksforGeeks
25 Jan, 2022 A directory is a location where files can be stored. For Ruby, the Dir class and the FileUtils module manages directories and the File class handles the files. Double dot (..) refers to the parent directory for directories and single dot(.)refers to the directory itself.The Dir Class The Dir class provides access to and contents of file system directory structures in Ruby.It provides a means of listing folder contents, generating file names with proper path separators, etc.These are some of the features of the Dir class: Creating Ruby directories: The mkdir() method in Dir class is used to create directory. We can use the below code to create non nested directory, the mkdir() method returns 0 if the directory is successfully created. Syntax: Dir.mkdir "name_of_directory" Example: Ruby # creating directoryf=Dir.mkdir "abc" # a directory named abc is createdprint("#{f}") Output: 0 Checking Ruby directories: The exists() method in Dir class is used to check if a directory exists or not. Syntax: The exists() method in Dir class is used to check if a directory exists or not. Syntax: Dir.exist?"name_of_directory" Example: Ruby # creating directoryputs Dir.mkdir("folder") # checking if the directory exists or notputs Dir.exists?("folder") Output: 0 true The empty? method in Dir class is used to check if a directory is empty or not. Syntax: Dir.empty?"name_of_directory" Example: Ruby # creating directoryputs Dir.mkdir("folder") # checking if the directory is empty or notputs Dir.empty?("folder") Output: 0 true Working with Ruby directories: Dir class uses different methods for Ruby directory operations, such methods are new(), pwd(), home(), path(), getwd(), chdir(), entries(), glob() etc. The new() is used to create a new directory object. Syntax: The new() is used to create a new directory object. Syntax: obj=Dir.new("name_of_directory") In the above code, folder directory should already exist. The pwd() method in Dir class returns the current directory. Syntax: Dir.pwd Example: Ruby # creating directoryDir.mkdir("folder") # returns current working directoryputs Dir.pwd Output: /workspace The home() method in Dir class is used to return the home directory of the current user. Syntax: Dir.home Example: Ruby # creating directoryDir.mkdir("folder") # returns home directoryputs Dir.home Output: /workspace The below code will return the home directory of a specific user. Dir.home('username') The path() method of Dir class is used to return the path parameter. Syntax: d=Dir.new("name_of_directory") d.path Example: Ruby # creating directoryDir.mkdir("folder") # creating object of that directory using new() methodobj=Dir.new("folder") # assigns the path parameter of obj to variable ff=obj.pathprint("#{f}") Output: folder The getwd() method of Dir class is used to return the path of the current directory. Syntax: Dir.getwd Example: Ruby # creating directoryDir.mkdir("folder") # returns the path of the current working directoryputs Dir.getwd Output: /workspace The chdir() method of Dir class is used to modify the current directory. Syntax: Dir.chdir("name_of_directory") Example: Ruby # creating directoriesDir.mkdir("/workspace/folder1")Dir.mkdir("/workspace/folder2") # displaying the path of the current directoryputs Dir.pwd # changing the current working directoryDir.chdir("folder2")puts Dir.pwd Output: /workspace /workspace/folder2 The entries() method in Dir class is used to return all the files and folders present in the directory in an array. Syntax: Dir.entries("directory") Example: Ruby # creating a directory named folderDir.mkdir("folder") # displaying the path of the current directoryputs Dir.pwd # changing current working directory to folderDir.chdir("folder")puts Dir.pwd # creating directories inside folderDir.mkdir("subfolder1")Dir.mkdir("subfolder2")Dir.mkdir("subfolder3") # displays all the files and folders present in folderprint("Entries:\n")puts Dir.entries("C:/Users/KIIT/Desktop/folder") Output: C:/Users/KIIT/Desktop C:/Users/KIIT/Desktop/folder Entries: . .. subfolder1 subfolder2 subfolder3 The glob() method in Dir class is used to display all the files having a certain matching pattern. Syntax: Dir.glob("pattern") Example: Ruby # creating a directory named folderDir.mkdir("folder") # changing current working directory to folderDir.chdir("folder") # creating directories inside folderDir.mkdir("dabce")Dir.mkdir("abcd")Dir.mkdir("program.rb")Dir.mkdir("program2.rb") # displaying specified files and foldersprint"\nAll files in the current working directory: \n"puts Dir.glob("*")print"\nAll files containing 'abc' in the name: \n"puts Dir.glob("*abc*")print"\nAll ruby files: \n"puts Dir.glob("*.rb") Output: All files in the current working directory: abcd dabce program.rb program2.rb All files containing 'abc' in the name: abcd dabce All ruby files: program.rb program2.rb Removing Ruby Directories : There are various methods in class Dir to remove Ruby Directories like rmdir(), delete() and unlink() Syntax: Dir.delete "folder" Dir.rmdir "folder" Dir.unlink "folder" Example: Ruby #creating directoryDir.mkdir("folder")puts Dir.exist?("folder") # deleting directoryDir.rmdir("folder")puts Dir.exist?("folder") Output: true false Creating nested directory: mkdir_p() method in FileUtils module is used to create a directory and all its parent directories. Syntax: FileUtils.mkdir_p 'directory_path' Example: Ruby # creating directory parent_folderDir.mkdir "parent_folder"print("Current Directory: ")puts Dir.pwdrequire "fileutils" # creating nested directory in parent_folderFileUtils.mkdir_p "parent_folder/child_folder/folder" # changing current directory to parent_folderDir.chdir("/workspace/parent_folder")print("Current Directory: ")puts Dir.pwd# checking child folder exists or notputs Dir.exists?("child_folder") # changing current directory to child_folderDir.chdir("/workspace/parent_folder/child_folder")print("Current Directory: ")puts Dir.pwd # checking folder exists or notputs Dir.exists?("folder") Output: Current Directory: /workspace Current Directory: /workspace/parent_folder true Current Directory: /workspace/parent_folder/child_folder true Moving files and folders: mv() and move() methods in FileUtils module are used to move files and folders from current directory to destination directory. Syntax: FileUtils.mv("source", "destination") Example: Ruby # creating directoriesDir.mkdir "folder1"Dir.mkdir "folder2"require "fileutils" # moving directory folder1 into directory folder2FileUtils.mv( "folder1", "folder2") # changing current directory to folder2Dir.chdir("folder2") # checking if folder1 exists in folder 2puts Dir.exists?("folder1") Output: true Copying files from one directory to another directory: cp() method in FileUtils module is used to copy files from current directory to destination directory. Syntax: FileUtils.cp("source", "destination") Example: Consider two directories folder1 and folder2 are already created and folder2 contains test.txt . Ruby require "fileutils" # copying test.txt from folder1 to folder2FileUtils.cp( "folder2/test.txt", "folder1")Dir.chdir("folder1") # checking if test.txt exists in folder1puts File.exist?("test.txt") Output: true sagar0719kumar rajeev0719singh sumitgumber28 rkbhola5 Picked Ruby-OOP Ruby Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Ruby | Enumerator each_with_index function Ruby For Beginners Ruby | Decision Making (if, if-else, if-else-if, ternary) | Set - 1 Ruby | Array shift() function Ruby Mixins Ruby | Array collect() operation Ruby | Module Ruby | String concat Method Instance Variables in Ruby Ruby | Array reject() function
[ { "code": null, "e": 24094, "s": 24066, "text": "\n25 Jan, 2022" }, { "code": null, "e": 24622, "s": 24094, "text": "A directory is a location where files can be stored. For Ruby, the Dir class and the FileUtils module manages directories and the File class handles the files. Double dot (..) refers to the parent directory for directories and single dot(.)refers to the directory itself.The Dir Class The Dir class provides access to and contents of file system directory structures in Ruby.It provides a means of listing folder contents, generating file names with proper path separators, etc.These are some of the features of the Dir class: " }, { "code": null, "e": 24847, "s": 24622, "text": "Creating Ruby directories: The mkdir() method in Dir class is used to create directory. We can use the below code to create non nested directory, the mkdir() method returns 0 if the directory is successfully created. Syntax:" }, { "code": null, "e": 24877, "s": 24847, "text": "Dir.mkdir \"name_of_directory\"" }, { "code": null, "e": 24886, "s": 24877, "text": "Example:" }, { "code": null, "e": 24891, "s": 24886, "text": "Ruby" }, { "code": "# creating directoryf=Dir.mkdir \"abc\" # a directory named abc is createdprint(\"#{f}\")", "e": 24977, "s": 24891, "text": null }, { "code": null, "e": 24985, "s": 24977, "text": "Output:" }, { "code": null, "e": 24987, "s": 24985, "text": "0" }, { "code": null, "e": 25102, "s": 24987, "text": "Checking Ruby directories: The exists() method in Dir class is used to check if a directory exists or not. Syntax:" }, { "code": null, "e": 25190, "s": 25102, "text": "The exists() method in Dir class is used to check if a directory exists or not. Syntax:" }, { "code": null, "e": 25220, "s": 25190, "text": "Dir.exist?\"name_of_directory\"" }, { "code": null, "e": 25229, "s": 25220, "text": "Example:" }, { "code": null, "e": 25234, "s": 25229, "text": "Ruby" }, { "code": "# creating directoryputs Dir.mkdir(\"folder\") # checking if the directory exists or notputs Dir.exists?(\"folder\")", "e": 25347, "s": 25234, "text": null }, { "code": null, "e": 25355, "s": 25347, "text": "Output:" }, { "code": null, "e": 25362, "s": 25355, "text": "0\ntrue" }, { "code": null, "e": 25450, "s": 25362, "text": "The empty? method in Dir class is used to check if a directory is empty or not. Syntax:" }, { "code": null, "e": 25480, "s": 25450, "text": "Dir.empty?\"name_of_directory\"" }, { "code": null, "e": 25489, "s": 25480, "text": "Example:" }, { "code": null, "e": 25494, "s": 25489, "text": "Ruby" }, { "code": "# creating directoryputs Dir.mkdir(\"folder\") # checking if the directory is empty or notputs Dir.empty?(\"folder\")", "e": 25608, "s": 25494, "text": null }, { "code": null, "e": 25616, "s": 25608, "text": "Output:" }, { "code": null, "e": 25623, "s": 25616, "text": "0\ntrue" }, { "code": null, "e": 25866, "s": 25623, "text": "Working with Ruby directories: Dir class uses different methods for Ruby directory operations, such methods are new(), pwd(), home(), path(), getwd(), chdir(), entries(), glob() etc. The new() is used to create a new directory object. Syntax:" }, { "code": null, "e": 25926, "s": 25866, "text": "The new() is used to create a new directory object. Syntax:" }, { "code": null, "e": 25959, "s": 25926, "text": "obj=Dir.new(\"name_of_directory\")" }, { "code": null, "e": 26017, "s": 25959, "text": "In the above code, folder directory should already exist." }, { "code": null, "e": 26086, "s": 26017, "text": "The pwd() method in Dir class returns the current directory. Syntax:" }, { "code": null, "e": 26094, "s": 26086, "text": "Dir.pwd" }, { "code": null, "e": 26103, "s": 26094, "text": "Example:" }, { "code": null, "e": 26108, "s": 26103, "text": "Ruby" }, { "code": "# creating directoryDir.mkdir(\"folder\") # returns current working directoryputs Dir.pwd ", "e": 26197, "s": 26108, "text": null }, { "code": null, "e": 26205, "s": 26197, "text": "Output:" }, { "code": null, "e": 26216, "s": 26205, "text": "/workspace" }, { "code": null, "e": 26313, "s": 26216, "text": "The home() method in Dir class is used to return the home directory of the current user. Syntax:" }, { "code": null, "e": 26322, "s": 26313, "text": "Dir.home" }, { "code": null, "e": 26331, "s": 26322, "text": "Example:" }, { "code": null, "e": 26336, "s": 26331, "text": "Ruby" }, { "code": "# creating directoryDir.mkdir(\"folder\") # returns home directoryputs Dir.home", "e": 26414, "s": 26336, "text": null }, { "code": null, "e": 26422, "s": 26414, "text": "Output:" }, { "code": null, "e": 26433, "s": 26422, "text": "/workspace" }, { "code": null, "e": 26499, "s": 26433, "text": "The below code will return the home directory of a specific user." }, { "code": null, "e": 26520, "s": 26499, "text": "Dir.home('username')" }, { "code": null, "e": 26597, "s": 26520, "text": "The path() method of Dir class is used to return the path parameter. Syntax:" }, { "code": null, "e": 26635, "s": 26597, "text": "d=Dir.new(\"name_of_directory\")\nd.path" }, { "code": null, "e": 26644, "s": 26635, "text": "Example:" }, { "code": null, "e": 26649, "s": 26644, "text": "Ruby" }, { "code": "# creating directoryDir.mkdir(\"folder\") # creating object of that directory using new() methodobj=Dir.new(\"folder\") # assigns the path parameter of obj to variable ff=obj.pathprint(\"#{f}\")", "e": 26838, "s": 26649, "text": null }, { "code": null, "e": 26846, "s": 26838, "text": "Output:" }, { "code": null, "e": 26853, "s": 26846, "text": "folder" }, { "code": null, "e": 26946, "s": 26853, "text": "The getwd() method of Dir class is used to return the path of the current directory. Syntax:" }, { "code": null, "e": 26956, "s": 26946, "text": "Dir.getwd" }, { "code": null, "e": 26965, "s": 26956, "text": "Example:" }, { "code": null, "e": 26970, "s": 26965, "text": "Ruby" }, { "code": "# creating directoryDir.mkdir(\"folder\") # returns the path of the current working directoryputs Dir.getwd", "e": 27076, "s": 26970, "text": null }, { "code": null, "e": 27084, "s": 27076, "text": "Output:" }, { "code": null, "e": 27095, "s": 27084, "text": "/workspace" }, { "code": null, "e": 27176, "s": 27095, "text": "The chdir() method of Dir class is used to modify the current directory. Syntax:" }, { "code": null, "e": 27207, "s": 27176, "text": "Dir.chdir(\"name_of_directory\")" }, { "code": null, "e": 27216, "s": 27207, "text": "Example:" }, { "code": null, "e": 27221, "s": 27216, "text": "Ruby" }, { "code": "# creating directoriesDir.mkdir(\"/workspace/folder1\")Dir.mkdir(\"/workspace/folder2\") # displaying the path of the current directoryputs Dir.pwd # changing the current working directoryDir.chdir(\"folder2\")puts Dir.pwd", "e": 27438, "s": 27221, "text": null }, { "code": null, "e": 27446, "s": 27438, "text": "Output:" }, { "code": null, "e": 27476, "s": 27446, "text": "/workspace\n/workspace/folder2" }, { "code": null, "e": 27600, "s": 27476, "text": "The entries() method in Dir class is used to return all the files and folders present in the directory in an array. Syntax:" }, { "code": null, "e": 27625, "s": 27600, "text": "Dir.entries(\"directory\")" }, { "code": null, "e": 27634, "s": 27625, "text": "Example:" }, { "code": null, "e": 27639, "s": 27634, "text": "Ruby" }, { "code": "# creating a directory named folderDir.mkdir(\"folder\") # displaying the path of the current directoryputs Dir.pwd # changing current working directory to folderDir.chdir(\"folder\")puts Dir.pwd # creating directories inside folderDir.mkdir(\"subfolder1\")Dir.mkdir(\"subfolder2\")Dir.mkdir(\"subfolder3\") # displays all the files and folders present in folderprint(\"Entries:\\n\")puts Dir.entries(\"C:/Users/KIIT/Desktop/folder\")", "e": 28059, "s": 27639, "text": null }, { "code": null, "e": 28067, "s": 28059, "text": "Output:" }, { "code": null, "e": 28165, "s": 28067, "text": "C:/Users/KIIT/Desktop\nC:/Users/KIIT/Desktop/folder\nEntries:\n.\n..\nsubfolder1\nsubfolder2\nsubfolder3" }, { "code": null, "e": 28272, "s": 28165, "text": "The glob() method in Dir class is used to display all the files having a certain matching pattern. Syntax:" }, { "code": null, "e": 28292, "s": 28272, "text": "Dir.glob(\"pattern\")" }, { "code": null, "e": 28301, "s": 28292, "text": "Example:" }, { "code": null, "e": 28306, "s": 28301, "text": "Ruby" }, { "code": "# creating a directory named folderDir.mkdir(\"folder\") # changing current working directory to folderDir.chdir(\"folder\") # creating directories inside folderDir.mkdir(\"dabce\")Dir.mkdir(\"abcd\")Dir.mkdir(\"program.rb\")Dir.mkdir(\"program2.rb\") # displaying specified files and foldersprint\"\\nAll files in the current working directory: \\n\"puts Dir.glob(\"*\")print\"\\nAll files containing 'abc' in the name: \\n\"puts Dir.glob(\"*abc*\")print\"\\nAll ruby files: \\n\"puts Dir.glob(\"*.rb\")", "e": 28781, "s": 28306, "text": null }, { "code": null, "e": 28789, "s": 28781, "text": "Output:" }, { "code": null, "e": 28959, "s": 28789, "text": "All files in the current working directory:\nabcd\ndabce\nprogram.rb\nprogram2.rb\n\nAll files containing 'abc' in the name:\nabcd\ndabce\n\nAll ruby files:\nprogram.rb\nprogram2.rb" }, { "code": null, "e": 29097, "s": 28959, "text": "Removing Ruby Directories : There are various methods in class Dir to remove Ruby Directories like rmdir(), delete() and unlink() Syntax:" }, { "code": null, "e": 29156, "s": 29097, "text": "Dir.delete \"folder\"\nDir.rmdir \"folder\"\nDir.unlink \"folder\"" }, { "code": null, "e": 29165, "s": 29156, "text": "Example:" }, { "code": null, "e": 29170, "s": 29165, "text": "Ruby" }, { "code": "#creating directoryDir.mkdir(\"folder\")puts Dir.exist?(\"folder\") # deleting directoryDir.rmdir(\"folder\")puts Dir.exist?(\"folder\")", "e": 29299, "s": 29170, "text": null }, { "code": null, "e": 29307, "s": 29299, "text": "Output:" }, { "code": null, "e": 29318, "s": 29307, "text": "true\nfalse" }, { "code": null, "e": 29452, "s": 29318, "text": "Creating nested directory: mkdir_p() method in FileUtils module is used to create a directory and all its parent directories. Syntax:" }, { "code": null, "e": 29487, "s": 29452, "text": "FileUtils.mkdir_p 'directory_path'" }, { "code": null, "e": 29496, "s": 29487, "text": "Example:" }, { "code": null, "e": 29501, "s": 29496, "text": "Ruby" }, { "code": "# creating directory parent_folderDir.mkdir \"parent_folder\"print(\"Current Directory: \")puts Dir.pwdrequire \"fileutils\" # creating nested directory in parent_folderFileUtils.mkdir_p \"parent_folder/child_folder/folder\" # changing current directory to parent_folderDir.chdir(\"/workspace/parent_folder\")print(\"Current Directory: \")puts Dir.pwd# checking child folder exists or notputs Dir.exists?(\"child_folder\") # changing current directory to child_folderDir.chdir(\"/workspace/parent_folder/child_folder\")print(\"Current Directory: \")puts Dir.pwd # checking folder exists or notputs Dir.exists?(\"folder\")", "e": 30103, "s": 29501, "text": null }, { "code": null, "e": 30111, "s": 30103, "text": "Output:" }, { "code": null, "e": 30252, "s": 30111, "text": "Current Directory: /workspace\nCurrent Directory: /workspace/parent_folder\ntrue\nCurrent Directory: /workspace/parent_folder/child_folder\ntrue" }, { "code": null, "e": 30414, "s": 30252, "text": "Moving files and folders: mv() and move() methods in FileUtils module are used to move files and folders from current directory to destination directory. Syntax:" }, { "code": null, "e": 30452, "s": 30414, "text": "FileUtils.mv(\"source\", \"destination\")" }, { "code": null, "e": 30461, "s": 30452, "text": "Example:" }, { "code": null, "e": 30466, "s": 30461, "text": "Ruby" }, { "code": "# creating directoriesDir.mkdir \"folder1\"Dir.mkdir \"folder2\"require \"fileutils\" # moving directory folder1 into directory folder2FileUtils.mv( \"folder1\", \"folder2\") # changing current directory to folder2Dir.chdir(\"folder2\") # checking if folder1 exists in folder 2puts Dir.exists?(\"folder1\")", "e": 30759, "s": 30466, "text": null }, { "code": null, "e": 30767, "s": 30759, "text": "Output:" }, { "code": null, "e": 30772, "s": 30767, "text": "true" }, { "code": null, "e": 30938, "s": 30772, "text": "Copying files from one directory to another directory: cp() method in FileUtils module is used to copy files from current directory to destination directory. Syntax:" }, { "code": null, "e": 30976, "s": 30938, "text": "FileUtils.cp(\"source\", \"destination\")" }, { "code": null, "e": 31082, "s": 30976, "text": "Example: Consider two directories folder1 and folder2 are already created and folder2 contains test.txt ." }, { "code": null, "e": 31087, "s": 31082, "text": "Ruby" }, { "code": "require \"fileutils\" # copying test.txt from folder1 to folder2FileUtils.cp( \"folder2/test.txt\", \"folder1\")Dir.chdir(\"folder1\") # checking if test.txt exists in folder1puts File.exist?(\"test.txt\")", "e": 31283, "s": 31087, "text": null }, { "code": null, "e": 31291, "s": 31283, "text": "Output:" }, { "code": null, "e": 31296, "s": 31291, "text": "true" }, { "code": null, "e": 31311, "s": 31296, "text": "sagar0719kumar" }, { "code": null, "e": 31327, "s": 31311, "text": "rajeev0719singh" }, { "code": null, "e": 31341, "s": 31327, "text": "sumitgumber28" }, { "code": null, "e": 31350, "s": 31341, "text": "rkbhola5" }, { "code": null, "e": 31357, "s": 31350, "text": "Picked" }, { "code": null, "e": 31366, "s": 31357, "text": "Ruby-OOP" }, { "code": null, "e": 31371, "s": 31366, "text": "Ruby" }, { "code": null, "e": 31469, "s": 31371, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31512, "s": 31469, "text": "Ruby | Enumerator each_with_index function" }, { "code": null, "e": 31531, "s": 31512, "text": "Ruby For Beginners" }, { "code": null, "e": 31599, "s": 31531, "text": "Ruby | Decision Making (if, if-else, if-else-if, ternary) | Set - 1" }, { "code": null, "e": 31629, "s": 31599, "text": "Ruby | Array shift() function" }, { "code": null, "e": 31641, "s": 31629, "text": "Ruby Mixins" }, { "code": null, "e": 31674, "s": 31641, "text": "Ruby | Array collect() operation" }, { "code": null, "e": 31688, "s": 31674, "text": "Ruby | Module" }, { "code": null, "e": 31716, "s": 31688, "text": "Ruby | String concat Method" }, { "code": null, "e": 31743, "s": 31716, "text": "Instance Variables in Ruby" } ]
Getting rounded value of a number in Julia - round() Method - GeeksforGeeks
21 Apr, 2020 The round() is an inbuilt function in julia which is used to round the specified number in different ways which are illustrated below- The default round process is done to the nearest integer, with ties (fractional values of 0.5) being rounded to the nearest even integer. The specified value x is rounded to an integer value and returns a value of the given type T or of the same type of x. If the digits keyword parameter is given, it rounds to the specified number of digits after the decimal place (or before if negative), in the given base. If the sigdigits keyword parameter is given, it rounds to the specified number of significant digits, in the given base. Syntax:round(x)round(T, x)round(x, digits::Integer, base)round(x, sigdigits::Integer, base) Parameters: x: Specified number T: Specified number type digits: Specified digit values base: Specified base in which results are coming sigdigits: Specified significant digits Returns: It returns the rounded value of the specified number. Example 1: # Julia program to illustrate # the use of round() method # Getting the rounded valuesprintln(round(2))println(round(2.3))println(round(2.9))println(round(0.5))println(round(2.5))println(round(3.5)) Output: 2 2.0 3.0 0.0 2.0 4.0 Example 2: # Julia program to illustrate # the use of round() method # Getting the rounded valuesprintln(round(pi; digits = 3))println(round(56.7685; digits = 3))println(round(pi; digits = 3, base = 2))println(round(55.98634; digits = 3, base = 2))println(round(324.675; sigdigits = 2))println(round(232.97634; sigdigits = 4, base = 2)) Output: Julia Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder) Get array dimensions and size of a dimension in Julia - size() Method Exception handling in Julia Searching in Array for a given element in Julia Find maximum element along with its index in Julia - findmax() Method Get number of elements of array in Julia - length() Method Working with Excel Files in Julia Getting last element of an array in Julia - last() Method Join an array of strings into a single string in Julia - join() Method File Handling in Julia
[ { "code": null, "e": 25669, "s": 25641, "text": "\n21 Apr, 2020" }, { "code": null, "e": 25804, "s": 25669, "text": "The round() is an inbuilt function in julia which is used to round the specified number in different ways which are illustrated below-" }, { "code": null, "e": 25942, "s": 25804, "text": "The default round process is done to the nearest integer, with ties (fractional values of 0.5) being rounded to the nearest even integer." }, { "code": null, "e": 26061, "s": 25942, "text": "The specified value x is rounded to an integer value and returns a value of the given type T or of the same type of x." }, { "code": null, "e": 26215, "s": 26061, "text": "If the digits keyword parameter is given, it rounds to the specified number of digits after the decimal place (or before if negative), in the given base." }, { "code": null, "e": 26336, "s": 26215, "text": "If the sigdigits keyword parameter is given, it rounds to the specified number of significant digits, in the given base." }, { "code": null, "e": 26428, "s": 26336, "text": "Syntax:round(x)round(T, x)round(x, digits::Integer, base)round(x, sigdigits::Integer, base)" }, { "code": null, "e": 26440, "s": 26428, "text": "Parameters:" }, { "code": null, "e": 26460, "s": 26440, "text": "x: Specified number" }, { "code": null, "e": 26485, "s": 26460, "text": "T: Specified number type" }, { "code": null, "e": 26516, "s": 26485, "text": "digits: Specified digit values" }, { "code": null, "e": 26565, "s": 26516, "text": "base: Specified base in which results are coming" }, { "code": null, "e": 26605, "s": 26565, "text": "sigdigits: Specified significant digits" }, { "code": null, "e": 26668, "s": 26605, "text": "Returns: It returns the rounded value of the specified number." }, { "code": null, "e": 26679, "s": 26668, "text": "Example 1:" }, { "code": "# Julia program to illustrate # the use of round() method # Getting the rounded valuesprintln(round(2))println(round(2.3))println(round(2.9))println(round(0.5))println(round(2.5))println(round(3.5))", "e": 26879, "s": 26679, "text": null }, { "code": null, "e": 26887, "s": 26879, "text": "Output:" }, { "code": null, "e": 26910, "s": 26887, "text": "2\n2.0\n3.0\n0.0\n2.0\n4.0\n" }, { "code": null, "e": 26921, "s": 26910, "text": "Example 2:" }, { "code": "# Julia program to illustrate # the use of round() method # Getting the rounded valuesprintln(round(pi; digits = 3))println(round(56.7685; digits = 3))println(round(pi; digits = 3, base = 2))println(round(55.98634; digits = 3, base = 2))println(round(324.675; sigdigits = 2))println(round(232.97634; sigdigits = 4, base = 2))", "e": 27248, "s": 26921, "text": null }, { "code": null, "e": 27256, "s": 27248, "text": "Output:" }, { "code": null, "e": 27262, "s": 27256, "text": "Julia" }, { "code": null, "e": 27360, "s": 27262, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27433, "s": 27360, "text": "Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder)" }, { "code": null, "e": 27503, "s": 27433, "text": "Get array dimensions and size of a dimension in Julia - size() Method" }, { "code": null, "e": 27531, "s": 27503, "text": "Exception handling in Julia" }, { "code": null, "e": 27579, "s": 27531, "text": "Searching in Array for a given element in Julia" }, { "code": null, "e": 27649, "s": 27579, "text": "Find maximum element along with its index in Julia - findmax() Method" }, { "code": null, "e": 27708, "s": 27649, "text": "Get number of elements of array in Julia - length() Method" }, { "code": null, "e": 27742, "s": 27708, "text": "Working with Excel Files in Julia" }, { "code": null, "e": 27800, "s": 27742, "text": "Getting last element of an array in Julia - last() Method" }, { "code": null, "e": 27871, "s": 27800, "text": "Join an array of strings into a single string in Julia - join() Method" } ]
How to create typewriter effect in ReactJS ?
25 Jan, 2021 The typewriter effect in ReactJS is a JS package that can be used for a better UI design. This effect allows us to create a simple typing animation in ReactJS. For using Typewriter in ReactJS we need to install the typewriter-effect package. Prerequisites: Basics of ReactJS Already created ReactJSapp Below all the steps are described order-wise to use styled-components in React. Installation: Step 1: Before moving further, firstly we have to install the typewriter-effect, by running the following command in your project directory, with the help of terminal in your src folder or you can also run this command in Visual Studio Code’s terminal in your project folder.npm install --save typewriter-effectyarn add typewriter-effect npm install --save typewriter-effect yarn add typewriter-effect Step 2: After installing the package, now open your App.js file which is present inside your project’s directory, under the src folder, and delete the code present inside it. Step 3: Now import React and typewriter-effect package. Step 4: In your app.js file, add this code snippet to import React and typewriter-effect package.import React from 'react'; import Typewriter from "typewriter-effect"; import React from 'react'; import Typewriter from "typewriter-effect"; Below is a sample program to illustrate the use of the typewriter-effect : Filename- App.js: Javascript import React from 'react'; //importing typewriter-effectimport Typewriter from "typewriter-effect";import './App.css'; function App() { return ( <div className="App"> <Typewriter onInit={(typewriter)=> { typewriter .typeString("GeeksForGeeks") .pauseFor(1000) .deleteAll() .typeString("Welcomes You") .start(); }} /> </div> );} export default App; Filename- App.css CSS .App { font-family: sans-serif; font-weight:800; font-size:40px; text-align: center; display:flex; justify-content:center; align-items:center; min-height:100vh; background:green;} Output: Hence using the above-mentioned steps, we can use the typewriter-effect to import and change the typing animation React. Technical Scripter 2020 ReactJS Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n25 Jan, 2021" }, { "code": null, "e": 294, "s": 52, "text": "The typewriter effect in ReactJS is a JS package that can be used for a better UI design. This effect allows us to create a simple typing animation in ReactJS. For using Typewriter in ReactJS we need to install the typewriter-effect package." }, { "code": null, "e": 309, "s": 294, "text": "Prerequisites:" }, { "code": null, "e": 327, "s": 309, "text": "Basics of ReactJS" }, { "code": null, "e": 354, "s": 327, "text": "Already created ReactJSapp" }, { "code": null, "e": 434, "s": 354, "text": "Below all the steps are described order-wise to use styled-components in React." }, { "code": null, "e": 448, "s": 434, "text": "Installation:" }, { "code": null, "e": 786, "s": 448, "text": "Step 1: Before moving further, firstly we have to install the typewriter-effect, by running the following command in your project directory, with the help of terminal in your src folder or you can also run this command in Visual Studio Code’s terminal in your project folder.npm install --save typewriter-effectyarn add typewriter-effect" }, { "code": null, "e": 823, "s": 786, "text": "npm install --save typewriter-effect" }, { "code": null, "e": 850, "s": 823, "text": "yarn add typewriter-effect" }, { "code": null, "e": 1025, "s": 850, "text": "Step 2: After installing the package, now open your App.js file which is present inside your project’s directory, under the src folder, and delete the code present inside it." }, { "code": null, "e": 1081, "s": 1025, "text": "Step 3: Now import React and typewriter-effect package." }, { "code": null, "e": 1249, "s": 1081, "text": "Step 4: In your app.js file, add this code snippet to import React and typewriter-effect package.import React from 'react';\nimport Typewriter from \"typewriter-effect\";" }, { "code": null, "e": 1320, "s": 1249, "text": "import React from 'react';\nimport Typewriter from \"typewriter-effect\";" }, { "code": null, "e": 1395, "s": 1320, "text": "Below is a sample program to illustrate the use of the typewriter-effect :" }, { "code": null, "e": 1413, "s": 1395, "text": "Filename- App.js:" }, { "code": null, "e": 1424, "s": 1413, "text": "Javascript" }, { "code": "import React from 'react'; //importing typewriter-effectimport Typewriter from \"typewriter-effect\";import './App.css'; function App() { return ( <div className=\"App\"> <Typewriter onInit={(typewriter)=> { typewriter .typeString(\"GeeksForGeeks\") .pauseFor(1000) .deleteAll() .typeString(\"Welcomes You\") .start(); }} /> </div> );} export default App;", "e": 1863, "s": 1424, "text": null }, { "code": null, "e": 1881, "s": 1863, "text": "Filename- App.css" }, { "code": null, "e": 1885, "s": 1881, "text": "CSS" }, { "code": ".App { font-family: sans-serif; font-weight:800; font-size:40px; text-align: center; display:flex; justify-content:center; align-items:center; min-height:100vh; background:green;}", "e": 2074, "s": 1885, "text": null }, { "code": null, "e": 2204, "s": 2074, "text": "Output: Hence using the above-mentioned steps, we can use the typewriter-effect to import and change the typing animation React. " }, { "code": null, "e": 2228, "s": 2204, "text": "Technical Scripter 2020" }, { "code": null, "e": 2236, "s": 2228, "text": "ReactJS" }, { "code": null, "e": 2255, "s": 2236, "text": "Technical Scripter" } ]
JavaScript SyntaxError – JSON.parse: bad parsing
31 Jul, 2020 This JavaScript exception thrown by JSON.parse() occurs if string passed as a parameter to the method is invalid. Message: SyntaxError: JSON.parse: unterminated string literal SyntaxError: JSON.parse: bad control character in string literal SyntaxError: JSON.parse: bad character in string literal SyntaxError: JSON.parse: bad Unicode escape SyntaxError: JSON.parse: bad escape character SyntaxError: JSON.parse: unterminated string SyntaxError: JSON.parse: no number after minus sign SyntaxError: JSON.parse: unexpected non-digit SyntaxError: JSON.parse: missing digits after decimal point SyntaxError: JSON.parse: unterminated fractional number SyntaxError: JSON.parse: missing digits after exponent indicator SyntaxError: JSON.parse: missing digits after exponent sign SyntaxError: JSON.parse: exponent part is missing a number SyntaxError: JSON.parse: unexpected end of data SyntaxError: JSON.parse: unexpected keyword SyntaxError: JSON.parse: unexpected character SyntaxError: JSON.parse: end of data while reading object contents SyntaxError: JSON.parse: expected property name or '}' SyntaxError: JSON.parse: end of data when ',' or ']' was expected SyntaxError: JSON.parse: expected ',' or ']' after array element SyntaxError: JSON.parse: end of data when property name was expected SyntaxError: JSON.parse: expected double-quoted property name SyntaxError: JSON.parse: end of data after property name when ':' was expected SyntaxError: JSON.parse: expected ':' after property name in object SyntaxError: JSON.parse: end of data after property value in object SyntaxError: JSON.parse: expected ',' or '}' after property value in object SyntaxError: JSON.parse: expected ',' or '}' after property-value pair in object literal SyntaxError: JSON.parse: property names must be double-quoted strings SyntaxError: JSON.parse: expected property name or '}' SyntaxError: JSON.parse: unexpected character SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data SyntaxError: JSON.parse Error: Invalid character at position {0} (Edge) Error Type: SyntaxError Cause of Error: This string passed to JSON.parse() method is invalid and will throw this error. Example 1: HTML <script> var str = '{"Prop_1" : "Val_1"}'; JSON.parse(str); document.write(str);</script> Output: {"Prop_1" : "Val_1"} Example 2: HTML <script> var str = '{"Prop_1" : "Val_1"}}'; JSON.parse(str); document.write(str);</script> Output(in console): Unexpected token } in JSON at position 2 javascript-basics 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": "\n31 Jul, 2020" }, { "code": null, "e": 142, "s": 28, "text": "This JavaScript exception thrown by JSON.parse() occurs if string passed as a parameter to the method is invalid." }, { "code": null, "e": 151, "s": 142, "text": "Message:" }, { "code": null, "e": 2152, "s": 151, "text": "SyntaxError: JSON.parse: unterminated string literal\nSyntaxError: JSON.parse: bad control character in string literal\nSyntaxError: JSON.parse: bad character in string literal\nSyntaxError: JSON.parse: bad Unicode escape\nSyntaxError: JSON.parse: bad escape character\nSyntaxError: JSON.parse: unterminated string\nSyntaxError: JSON.parse: no number after minus sign\nSyntaxError: JSON.parse: unexpected non-digit\nSyntaxError: JSON.parse: missing digits after decimal point\nSyntaxError: JSON.parse: unterminated fractional number\nSyntaxError: JSON.parse: missing digits after exponent indicator\nSyntaxError: JSON.parse: missing digits after exponent sign\nSyntaxError: JSON.parse: exponent part is missing a number\nSyntaxError: JSON.parse: unexpected end of data\nSyntaxError: JSON.parse: unexpected keyword\nSyntaxError: JSON.parse: unexpected character\nSyntaxError: JSON.parse: end of data while reading object contents\nSyntaxError: JSON.parse: expected property name or '}'\nSyntaxError: JSON.parse: end of data when ',' or ']' was expected\nSyntaxError: JSON.parse: expected ',' or ']' after array element\nSyntaxError: JSON.parse: end of data when property name was expected\nSyntaxError: JSON.parse: expected double-quoted property name\nSyntaxError: JSON.parse: end of data after property name when ':' \n was expected\nSyntaxError: JSON.parse: expected ':' after property name in object\nSyntaxError: JSON.parse: end of data after property value in object\nSyntaxError: JSON.parse: expected ',' or '}' after property value in \n object\nSyntaxError: JSON.parse: expected ',' or '}' after property-value \n pair in object literal\nSyntaxError: JSON.parse: property names must be double-quoted strings\nSyntaxError: JSON.parse: expected property name or '}'\nSyntaxError: JSON.parse: unexpected character\nSyntaxError: JSON.parse: unexpected non-whitespace character after \n JSON data\nSyntaxError: JSON.parse Error: Invalid character at position {0} \n (Edge)\n" }, { "code": null, "e": 2164, "s": 2152, "text": "Error Type:" }, { "code": null, "e": 2178, "s": 2164, "text": "SyntaxError\n\n" }, { "code": null, "e": 2274, "s": 2178, "text": "Cause of Error: This string passed to JSON.parse() method is invalid and will throw this error." }, { "code": null, "e": 2285, "s": 2274, "text": "Example 1:" }, { "code": null, "e": 2290, "s": 2285, "text": "HTML" }, { "code": "<script> var str = '{\"Prop_1\" : \"Val_1\"}'; JSON.parse(str); document.write(str);</script>", "e": 2389, "s": 2290, "text": null }, { "code": null, "e": 2397, "s": 2389, "text": "Output:" }, { "code": null, "e": 2419, "s": 2397, "text": "{\"Prop_1\" : \"Val_1\"}\n" }, { "code": null, "e": 2430, "s": 2419, "text": "Example 2:" }, { "code": null, "e": 2435, "s": 2430, "text": "HTML" }, { "code": "<script> var str = '{\"Prop_1\" : \"Val_1\"}}'; JSON.parse(str); document.write(str);</script>", "e": 2535, "s": 2435, "text": null }, { "code": null, "e": 2555, "s": 2535, "text": "Output(in console):" }, { "code": null, "e": 2597, "s": 2555, "text": "Unexpected token } in JSON at position 2\n" }, { "code": null, "e": 2615, "s": 2597, "text": "javascript-basics" }, { "code": null, "e": 2626, "s": 2615, "text": "JavaScript" }, { "code": null, "e": 2643, "s": 2626, "text": "Web Technologies" } ]
set::erase in C++ STL
06 Oct, 2021 Sets are a type of associative containers in which each element has to be unique, because the value of the element identifies it. The value of the element cannot be modified once it is added to the set, though it is possible to remove and add the modified value of that element. erase() function is used to remove elements from a container from the specified position or range.Syntax : 1. setname.erase(position) 2. setname.erase(startingposition, endingposition) Parameters : Position of the element to be removed in the form of iterator or the range specified using start and end iterator. Result : Elements are removed from the specified position of the container. Examples: Input : myset{1, 2, 3, 4, 5}, iterator= 2 myset.erase(iterator); Output : 1, 2, 4, 5 Input : myset{1, 2, 3, 4, 5, 6, 7, 8}, iterator1= 3, iterator2= 6 myset.erase(iterator1, iterator2); Output : 1, 2, 3, 8 Errors and Exceptions1. It has a no exception throw guarantee, if the position is valid. 2. Shows undefined behavior otherwise.Removing element from particular position CPP // INTEGER SET EXAMPLE// CPP program to illustrate// Implementation of erase() function#include <iostream>#include <set> using namespace std; int main(){ // set declaration set<int> myset{ 1, 2, 3, 4, 5 }; set<int>::iterator it1, it2; // defining it1 pointing to the first // element and it2 to the last element it1 = myset.begin(); it2 = myset.end(); // decrementing the it2 two times it2--; it2--; // erasing elements within the range // of it1 and it2 myset.erase(it1, it2); // Printing the set for (auto it = myset.begin(); it != myset.end(); ++it) cout << ' ' << *it; return 0;} Output: 4 5 CPP // CHARACTER SET EXAMPLE// CPP program to illustrate// Implementation of erase() function#include <iostream>#include <set> using namespace std; int main(){ // set declaration set<char> myset{ 'A', 'C', 'E', 'G' }; set<char>::iterator it1, it2; // defining it1 pointing to the first // element and it2 to the last element it1 = myset.begin(); it2 = myset.end(); // decrementing the it2 two times it2--; it2--; // erasing elements within the // range of it1 and it2 myset.erase(it1, it2); // Printing the set for (auto it = myset.begin(); it != myset.end(); ++it) cout << ' ' << *it; return 0;} Output: E G Removing elements within a range CPP // INTEGER SET EXAMPLE// CPP program to illustrate// Implementation of erase() function#include <iostream>#include <set> using namespace std; int main(){ // set declaration set<int> myset{ 1, 2, 3, 4, 5 }; set<int>::iterator it; // defining iterator pointing // to the first element it = myset.begin(); // erasing the first element myset.erase(it); // Printing the set for (auto it = myset.begin(); it != myset.end(); ++it) cout << ' ' << *it; return 0;} Output: 2 3 4 5 CPP // CHARACTER SET EXAMPLE// CPP program to illustrate// Implementation of erase() function#include <iostream>#include <set> using namespace std; int main(){ // set declaration set<char> myset{ 'A', 'B', 'C', 'D' }; set<char>::iterator it; // defining iterator pointing // to the first element it = myset.begin(); // erasing the first element myset.erase(it); // Printing the set for (auto it = myset.begin(); it != myset.end(); ++it) cout << ' ' << *it; return 0;} Output: B C D Time Complexity: 1. setname.erase(position) – amortized constant 2. setname.erase(startingposition, endingposition) – O(n), n is number of elements between starting position and ending position.Application Given a set of integers, remove all the even elements from the set and print the set. Input :1, 2, 3, 4, 5, 6, 7, 8, 9 Output :1 3 5 7 9 Explanation - 2, 4, 6 and 8 which are even are erased from the set Algorithm 1. Run a loop till the size of the set. 2. Check if the element at each position is divisible by 2, if yes- remove the element and assign the return iterator to the current iterator, if no- increment the iterator. 3. Print the final set. Note:erase return the iterator of the next element CPP // CPP program to illustrate// Application of erase() function#include <iostream>#include <set> using namespace std; int main(){ // set declaration set<int> myset{ 1, 2, 3, 4, 5, 6, 7, 8, 9 }; // checking for even elements and removing them for (auto i = myset.begin(); i != myset.end(); ) { if (*i % 2 == 0) i=myset.erase(i); else i++; } // Printing the set for (auto it = myset.begin(); it != myset.end(); ++it) cout << ' ' << *it; return 0;} Output : 1 3 5 7 9 Dsv hritikbhatnagar2182 cpp-set 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": "\n06 Oct, 2021" }, { "code": null, "e": 332, "s": 52, "text": "Sets are a type of associative containers in which each element has to be unique, because the value of the element identifies it. The value of the element cannot be modified once it is added to the set, though it is possible to remove and add the modified value of that element. " }, { "code": null, "e": 440, "s": 332, "text": "erase() function is used to remove elements from a container from the specified position or range.Syntax : " }, { "code": null, "e": 723, "s": 440, "text": "1. setname.erase(position)\n2. setname.erase(startingposition, endingposition)\nParameters :\nPosition of the element to be removed in \nthe form of iterator or the range specified\nusing start and end iterator.\nResult :\nElements are removed from the specified\nposition of the container." }, { "code": null, "e": 734, "s": 723, "text": "Examples: " }, { "code": null, "e": 971, "s": 734, "text": "Input : myset{1, 2, 3, 4, 5}, iterator= 2\n myset.erase(iterator);\nOutput : 1, 2, 4, 5\n\nInput : myset{1, 2, 3, 4, 5, 6, 7, 8}, \n iterator1= 3, iterator2= 6\n myset.erase(iterator1, iterator2);\nOutput : 1, 2, 3, 8" }, { "code": null, "e": 1141, "s": 971, "text": "Errors and Exceptions1. It has a no exception throw guarantee, if the position is valid. 2. Shows undefined behavior otherwise.Removing element from particular position " }, { "code": null, "e": 1145, "s": 1141, "text": "CPP" }, { "code": "// INTEGER SET EXAMPLE// CPP program to illustrate// Implementation of erase() function#include <iostream>#include <set> using namespace std; int main(){ // set declaration set<int> myset{ 1, 2, 3, 4, 5 }; set<int>::iterator it1, it2; // defining it1 pointing to the first // element and it2 to the last element it1 = myset.begin(); it2 = myset.end(); // decrementing the it2 two times it2--; it2--; // erasing elements within the range // of it1 and it2 myset.erase(it1, it2); // Printing the set for (auto it = myset.begin(); it != myset.end(); ++it) cout << ' ' << *it; return 0;}", "e": 1795, "s": 1145, "text": null }, { "code": null, "e": 1805, "s": 1795, "text": "Output: " }, { "code": null, "e": 1809, "s": 1805, "text": "4 5" }, { "code": null, "e": 1815, "s": 1811, "text": "CPP" }, { "code": "// CHARACTER SET EXAMPLE// CPP program to illustrate// Implementation of erase() function#include <iostream>#include <set> using namespace std; int main(){ // set declaration set<char> myset{ 'A', 'C', 'E', 'G' }; set<char>::iterator it1, it2; // defining it1 pointing to the first // element and it2 to the last element it1 = myset.begin(); it2 = myset.end(); // decrementing the it2 two times it2--; it2--; // erasing elements within the // range of it1 and it2 myset.erase(it1, it2); // Printing the set for (auto it = myset.begin(); it != myset.end(); ++it) cout << ' ' << *it; return 0;}", "e": 2474, "s": 1815, "text": null }, { "code": null, "e": 2484, "s": 2474, "text": "Output: " }, { "code": null, "e": 2488, "s": 2484, "text": "E G" }, { "code": null, "e": 2522, "s": 2488, "text": "Removing elements within a range " }, { "code": null, "e": 2526, "s": 2522, "text": "CPP" }, { "code": "// INTEGER SET EXAMPLE// CPP program to illustrate// Implementation of erase() function#include <iostream>#include <set> using namespace std; int main(){ // set declaration set<int> myset{ 1, 2, 3, 4, 5 }; set<int>::iterator it; // defining iterator pointing // to the first element it = myset.begin(); // erasing the first element myset.erase(it); // Printing the set for (auto it = myset.begin(); it != myset.end(); ++it) cout << ' ' << *it; return 0;}", "e": 3031, "s": 2526, "text": null }, { "code": null, "e": 3041, "s": 3031, "text": "Output: " }, { "code": null, "e": 3049, "s": 3041, "text": "2 3 4 5" }, { "code": null, "e": 3055, "s": 3051, "text": "CPP" }, { "code": "// CHARACTER SET EXAMPLE// CPP program to illustrate// Implementation of erase() function#include <iostream>#include <set> using namespace std; int main(){ // set declaration set<char> myset{ 'A', 'B', 'C', 'D' }; set<char>::iterator it; // defining iterator pointing // to the first element it = myset.begin(); // erasing the first element myset.erase(it); // Printing the set for (auto it = myset.begin(); it != myset.end(); ++it) cout << ' ' << *it; return 0;}", "e": 3569, "s": 3055, "text": null }, { "code": null, "e": 3579, "s": 3569, "text": "Output: " }, { "code": null, "e": 3585, "s": 3579, "text": "B C D" }, { "code": null, "e": 3878, "s": 3585, "text": "Time Complexity: 1. setname.erase(position) – amortized constant 2. setname.erase(startingposition, endingposition) – O(n), n is number of elements between starting position and ending position.Application Given a set of integers, remove all the even elements from the set and print the set. " }, { "code": null, "e": 3997, "s": 3878, "text": "Input :1, 2, 3, 4, 5, 6, 7, 8, 9\nOutput :1 3 5 7 9\nExplanation - 2, 4, 6 and 8 which are even are erased from the set" }, { "code": null, "e": 4298, "s": 3997, "text": "Algorithm 1. Run a loop till the size of the set. 2. Check if the element at each position is divisible by 2, if yes- remove the element and assign the return iterator to the current iterator, if no- increment the iterator. 3. Print the final set. Note:erase return the iterator of the next element " }, { "code": null, "e": 4302, "s": 4298, "text": "CPP" }, { "code": "// CPP program to illustrate// Application of erase() function#include <iostream>#include <set> using namespace std; int main(){ // set declaration set<int> myset{ 1, 2, 3, 4, 5, 6, 7, 8, 9 }; // checking for even elements and removing them for (auto i = myset.begin(); i != myset.end(); ) { if (*i % 2 == 0) i=myset.erase(i); else i++; } // Printing the set for (auto it = myset.begin(); it != myset.end(); ++it) cout << ' ' << *it; return 0;}", "e": 4825, "s": 4302, "text": null }, { "code": null, "e": 4836, "s": 4825, "text": "Output : " }, { "code": null, "e": 4846, "s": 4836, "text": "1 3 5 7 9" }, { "code": null, "e": 4852, "s": 4848, "text": "Dsv" }, { "code": null, "e": 4872, "s": 4852, "text": "hritikbhatnagar2182" }, { "code": null, "e": 4880, "s": 4872, "text": "cpp-set" }, { "code": null, "e": 4884, "s": 4880, "text": "STL" }, { "code": null, "e": 4888, "s": 4884, "text": "C++" }, { "code": null, "e": 4892, "s": 4888, "text": "STL" }, { "code": null, "e": 4896, "s": 4892, "text": "CPP" } ]
TensorFlow – How to create one hot tensor
01 Aug, 2020 TensorFlow is open-source Python library designed by Google to develop Machine Learning models and deep learning neural networks. One hot tensor is a Tensor in which all the values at indices where i =j and i!=j is same. Method Used: one_hot: This method accepts a Tensor of indices, a scalar defining depth of the one hot dimension and returns a one hot Tensor with default on value 1 and off value 0. These on and off values can be modified. Example 1: Python3 # importing the libraryimport tensorflow as tf # Initializing the Inputindices = tf.constant([1, 2, 3]) # Printing the Inputprint("Indices: ", indices) # Generating one hot Tensorres = tf.one_hot(indices, depth = 3) # Printing the resulting Tensorsprint("Res: ", res ) Output: Indices: tf.Tensor([1 2 3], shape=(3, ), dtype=int32) Res: tf.Tensor( [[0. 1. 0.] [0. 0. 1.] [0. 0. 0.]], shape=(3, 3), dtype=float32) Example 2: This example explicitly defines the on and off values for the one hot tensor. Python3 # importing the libraryimport tensorflow as tf # Initializing the Inputindices = tf.constant([1, 2, 3]) # Printing the Inputprint("Indices: ", indices) # Generating one hot Tensorres = tf.one_hot(indices, depth = 3, on_value = 3, off_value =-1) # Printing the resulting Tensorsprint("Res: ", res ) Output: Indices: tf.Tensor([1 2 3], shape=(3, ), dtype=int32) Res: tf.Tensor( [[-1 3 -1] [-1 -1 3] [-1 -1 -1]], shape=(3, 3), dtype=int32) Python-Tensorflow Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Python | os.path.join() method How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Aug, 2020" }, { "code": null, "e": 159, "s": 28, "text": "TensorFlow is open-source Python library designed by Google to develop Machine Learning models and deep learning neural networks." }, { "code": null, "e": 251, "s": 159, "text": "One hot tensor is a Tensor in which all the values at indices where i =j and i!=j is same. " }, { "code": null, "e": 264, "s": 251, "text": "Method Used:" }, { "code": null, "e": 474, "s": 264, "text": "one_hot: This method accepts a Tensor of indices, a scalar defining depth of the one hot dimension and returns a one hot Tensor with default on value 1 and off value 0. These on and off values can be modified." }, { "code": null, "e": 485, "s": 474, "text": "Example 1:" }, { "code": null, "e": 493, "s": 485, "text": "Python3" }, { "code": "# importing the libraryimport tensorflow as tf # Initializing the Inputindices = tf.constant([1, 2, 3]) # Printing the Inputprint(\"Indices: \", indices) # Generating one hot Tensorres = tf.one_hot(indices, depth = 3) # Printing the resulting Tensorsprint(\"Res: \", res )", "e": 766, "s": 493, "text": null }, { "code": null, "e": 774, "s": 766, "text": "Output:" }, { "code": null, "e": 915, "s": 774, "text": "Indices: tf.Tensor([1 2 3], shape=(3, ), dtype=int32)\nRes: tf.Tensor(\n[[0. 1. 0.]\n [0. 0. 1.]\n [0. 0. 0.]], shape=(3, 3), dtype=float32)\n\n" }, { "code": null, "e": 1004, "s": 915, "text": "Example 2: This example explicitly defines the on and off values for the one hot tensor." }, { "code": null, "e": 1012, "s": 1004, "text": "Python3" }, { "code": "# importing the libraryimport tensorflow as tf # Initializing the Inputindices = tf.constant([1, 2, 3]) # Printing the Inputprint(\"Indices: \", indices) # Generating one hot Tensorres = tf.one_hot(indices, depth = 3, on_value = 3, off_value =-1) # Printing the resulting Tensorsprint(\"Res: \", res )", "e": 1314, "s": 1012, "text": null }, { "code": null, "e": 1322, "s": 1314, "text": "Output:" }, { "code": null, "e": 1462, "s": 1322, "text": "Indices: tf.Tensor([1 2 3], shape=(3, ), dtype=int32)\nRes: tf.Tensor(\n[[-1 3 -1]\n [-1 -1 3]\n [-1 -1 -1]], shape=(3, 3), dtype=int32)\n\n\n" }, { "code": null, "e": 1480, "s": 1462, "text": "Python-Tensorflow" }, { "code": null, "e": 1487, "s": 1480, "text": "Python" }, { "code": null, "e": 1585, "s": 1487, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1617, "s": 1585, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1644, "s": 1617, "text": "Python Classes and Objects" }, { "code": null, "e": 1665, "s": 1644, "text": "Python OOPs Concepts" }, { "code": null, "e": 1688, "s": 1665, "text": "Introduction To PYTHON" }, { "code": null, "e": 1719, "s": 1688, "text": "Python | os.path.join() method" }, { "code": null, "e": 1775, "s": 1719, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 1817, "s": 1775, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 1859, "s": 1817, "text": "Check if element exists in list in Python" }, { "code": null, "e": 1898, "s": 1859, "text": "Python | Get unique values from a list" } ]
Python OpenCv: Write text on video
30 Jan, 2020 OpenCV is the huge open-source library for computer vision, machine learning, and image processing and now it plays a major role in real-time operation which is very important in today’s systems. By using it, one can process images and videos to identify objects, faces, or even the handwriting of a human. cv2.putText() method inserts a text on the video frame at the desired position specified by the user. We can style the type of font and also it’s color and thickness. Syntax : cv2.putText(frame, Text, org, font, color, thickness) Parameters:frame: current running frame of the video.Text: The text string to be inserted.org: bottom-left corner of the text stringfont: the type of font to be used.color: the colour of the font.thickness: the thickness of the font Example: # Python program to write# text on video import cv2 cap = cv2.VideoCapture('sample_vid.mp4') while(True): # Capture frames in the video ret, frame = cap.read() # describe the type of font # to be used. font = cv2.FONT_HERSHEY_SIMPLEX # Use putText() method for # inserting text on video cv2.putText(frame, 'TEXT ON VIDEO', (50, 50), font, 1, (0, 255, 255), 2, cv2.LINE_4) # Display the resulting frame cv2.imshow('video', frame) # creating 'q' as the quit # button for the video if cv2.waitKey(1) & 0xFF == ord('q'): break # release the cap objectcap.release()# close all windowscv2.destroyAllWindows() Output: Python-OpenCV Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Jan, 2020" }, { "code": null, "e": 335, "s": 28, "text": "OpenCV is the huge open-source library for computer vision, machine learning, and image processing and now it plays a major role in real-time operation which is very important in today’s systems. By using it, one can process images and videos to identify objects, faces, or even the handwriting of a human." }, { "code": null, "e": 502, "s": 335, "text": "cv2.putText() method inserts a text on the video frame at the desired position specified by the user. We can style the type of font and also it’s color and thickness." }, { "code": null, "e": 565, "s": 502, "text": "Syntax : cv2.putText(frame, Text, org, font, color, thickness)" }, { "code": null, "e": 798, "s": 565, "text": "Parameters:frame: current running frame of the video.Text: The text string to be inserted.org: bottom-left corner of the text stringfont: the type of font to be used.color: the colour of the font.thickness: the thickness of the font" }, { "code": null, "e": 807, "s": 798, "text": "Example:" }, { "code": "# Python program to write# text on video import cv2 cap = cv2.VideoCapture('sample_vid.mp4') while(True): # Capture frames in the video ret, frame = cap.read() # describe the type of font # to be used. font = cv2.FONT_HERSHEY_SIMPLEX # Use putText() method for # inserting text on video cv2.putText(frame, 'TEXT ON VIDEO', (50, 50), font, 1, (0, 255, 255), 2, cv2.LINE_4) # Display the resulting frame cv2.imshow('video', frame) # creating 'q' as the quit # button for the video if cv2.waitKey(1) & 0xFF == ord('q'): break # release the cap objectcap.release()# close all windowscv2.destroyAllWindows()", "e": 1575, "s": 807, "text": null }, { "code": null, "e": 1583, "s": 1575, "text": "Output:" }, { "code": null, "e": 1597, "s": 1583, "text": "Python-OpenCV" }, { "code": null, "e": 1604, "s": 1597, "text": "Python" } ]
Wikipedia module in Python
23 Sep, 2021 The Internet is the single largest source of information, and therefore it is important to know how to fetch data from various sources. And with Wikipedia being one of the largest and most popular sources for information on the Internet. Wikipedia is a multilingual online encyclopedia created and maintained as an open collaboration project by a community of volunteer editors using a wiki-based editing system.In this article, we will see how to use Python’s Wikipedia module to fetch a variety of information from the Wikipedia website. In order to extract data from Wikipedia, we must first install the Python Wikipedia library, which wraps the official Wikipedia API. This can be done by entering the command below in your command prompt or terminal: pip install wikipedia Summary of any title can be obtained by using summary method. Syntax : wikipedia.summary(title, sentences)Argument : Title of the topic Optional argument: setting number of lines in result.Return : Returns the summary in string format. Code : Python3 # importing the moduleimport wikipedia # finding result for the search# sentences = 2 refers to numbers of lineresult = wikipedia.summary("India", sentences = 2) # printing the resultprint(result) Output : India (Hindi: Bh?rat), officially the Republic of India (Hindi: Bh?rat Ga?ar?jya), is a country in South Asia. It is the seventh-largest country by area, the second-most populous country, and the most populous democracy in the world. Title and suggestions can be get by using search() method. Syntax : wikipedia.search(title, results)Argument : Title of the topic Optional argument : setting number of result.Return : Returns the list of titles. Code : Python3 # importing the moduleimport wikipedia # getting suggestionsresult = wikipedia.search("Geek", results = 5) # printing the resultprint(result) Output : ['Geek', 'Geek!', 'Freaks and Geeks', 'The Geek', 'Geek show'] The page() method is used to get the contents, categories, coordinates, images, links and other metadata of a Wikipedia page. Syntax : wikipedia.page(title)Argument : Title of the topic.Return : Return a WikipediaPage object. Code : Python3 # importing the moduleimport wikipedia # wikipedia page object is createdpage_object = wikipedia.page("india") # printing html of page_objectprint(page_object.html) # printing titleprint(page_object.original_title) # printing links on that page objectprint(page_object.links[0:10]) Output : “bound method WikipediaPage.html of “WikipediaPage ‘India'”> India [‘.in’, ’10th BRICS summit’, ’11th BRICS summit’, ’12th BRICS summit’, ’17th SAARC summit’, ’18th SAARC summit’, ‘1951 Asian Games’, ‘1957 Indian general election’, ‘1962 Indian general election’, ‘1982 Asian Games’] The language can be changed to your native language if the page exists in your native language. Set_lang() method is used for the same. Syntax : wikipedia.set_lang(language)Argument : prefix of the language like for arabic prefix is ar and so on.Action performed : It converted the data into that language default language is english. Code : Python3 # importing the moduleimport wikipedia # setting language to hindiwikipedia.set_lang("hi") # printing the summaryprint(wikipedia.summary("India")) Output : simmytarika5 python-modules Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n23 Sep, 2021" }, { "code": null, "e": 291, "s": 53, "text": "The Internet is the single largest source of information, and therefore it is important to know how to fetch data from various sources. And with Wikipedia being one of the largest and most popular sources for information on the Internet." }, { "code": null, "e": 593, "s": 291, "text": "Wikipedia is a multilingual online encyclopedia created and maintained as an open collaboration project by a community of volunteer editors using a wiki-based editing system.In this article, we will see how to use Python’s Wikipedia module to fetch a variety of information from the Wikipedia website." }, { "code": null, "e": 809, "s": 593, "text": "In order to extract data from Wikipedia, we must first install the Python Wikipedia library, which wraps the official Wikipedia API. This can be done by entering the command below in your command prompt or terminal:" }, { "code": null, "e": 831, "s": 809, "text": "pip install wikipedia" }, { "code": null, "e": 894, "s": 831, "text": "Summary of any title can be obtained by using summary method. " }, { "code": null, "e": 1070, "s": 894, "text": "Syntax : wikipedia.summary(title, sentences)Argument : Title of the topic Optional argument: setting number of lines in result.Return : Returns the summary in string format. " }, { "code": null, "e": 1079, "s": 1070, "text": "Code : " }, { "code": null, "e": 1087, "s": 1079, "text": "Python3" }, { "code": "# importing the moduleimport wikipedia # finding result for the search# sentences = 2 refers to numbers of lineresult = wikipedia.summary(\"India\", sentences = 2) # printing the resultprint(result)", "e": 1284, "s": 1087, "text": null }, { "code": null, "e": 1293, "s": 1284, "text": "Output :" }, { "code": null, "e": 1528, "s": 1293, "text": "India (Hindi: Bh?rat), officially the Republic of India (Hindi: Bh?rat Ga?ar?jya), is a country in South Asia. It is the seventh-largest country by area, the second-most populous country, and the most populous democracy in the world. " }, { "code": null, "e": 1588, "s": 1528, "text": "Title and suggestions can be get by using search() method. " }, { "code": null, "e": 1743, "s": 1588, "text": "Syntax : wikipedia.search(title, results)Argument : Title of the topic Optional argument : setting number of result.Return : Returns the list of titles. " }, { "code": null, "e": 1752, "s": 1743, "text": "Code : " }, { "code": null, "e": 1760, "s": 1752, "text": "Python3" }, { "code": "# importing the moduleimport wikipedia # getting suggestionsresult = wikipedia.search(\"Geek\", results = 5) # printing the resultprint(result)", "e": 1902, "s": 1760, "text": null }, { "code": null, "e": 1912, "s": 1902, "text": "Output : " }, { "code": null, "e": 1975, "s": 1912, "text": "['Geek', 'Geek!', 'Freaks and Geeks', 'The Geek', 'Geek show']" }, { "code": null, "e": 2101, "s": 1975, "text": "The page() method is used to get the contents, categories, coordinates, images, links and other metadata of a Wikipedia page." }, { "code": null, "e": 2203, "s": 2101, "text": "Syntax : wikipedia.page(title)Argument : Title of the topic.Return : Return a WikipediaPage object. " }, { "code": null, "e": 2212, "s": 2203, "text": "Code : " }, { "code": null, "e": 2220, "s": 2212, "text": "Python3" }, { "code": "# importing the moduleimport wikipedia # wikipedia page object is createdpage_object = wikipedia.page(\"india\") # printing html of page_objectprint(page_object.html) # printing titleprint(page_object.original_title) # printing links on that page objectprint(page_object.links[0:10])", "e": 2502, "s": 2220, "text": null }, { "code": null, "e": 2511, "s": 2502, "text": "Output :" }, { "code": null, "e": 2796, "s": 2511, "text": "“bound method WikipediaPage.html of “WikipediaPage ‘India'”> India [‘.in’, ’10th BRICS summit’, ’11th BRICS summit’, ’12th BRICS summit’, ’17th SAARC summit’, ’18th SAARC summit’, ‘1951 Asian Games’, ‘1957 Indian general election’, ‘1962 Indian general election’, ‘1982 Asian Games’] " }, { "code": null, "e": 2933, "s": 2796, "text": "The language can be changed to your native language if the page exists in your native language. Set_lang() method is used for the same. " }, { "code": null, "e": 3134, "s": 2933, "text": "Syntax : wikipedia.set_lang(language)Argument : prefix of the language like for arabic prefix is ar and so on.Action performed : It converted the data into that language default language is english. " }, { "code": null, "e": 3143, "s": 3134, "text": "Code : " }, { "code": null, "e": 3151, "s": 3143, "text": "Python3" }, { "code": "# importing the moduleimport wikipedia # setting language to hindiwikipedia.set_lang(\"hi\") # printing the summaryprint(wikipedia.summary(\"India\"))", "e": 3298, "s": 3151, "text": null }, { "code": null, "e": 3307, "s": 3298, "text": "Output :" }, { "code": null, "e": 3322, "s": 3309, "text": "simmytarika5" }, { "code": null, "e": 3337, "s": 3322, "text": "python-modules" }, { "code": null, "e": 3344, "s": 3337, "text": "Python" } ]
Python – seaborn.lmplot() method
12 Dec, 2021 Seaborn is an amazing visualization library for statistical graphics plotting in Python. It provides beautiful default styles and color palettes to make statistical plots more attractive. It is built on the top of matplotlib library and also closely integrated to the data structures from pandas. seaborn.lmplot() method is used to draw a scatter plot onto a FacetGrid. Syntax : seaborn.lmplot(x, y, data, hue=None, col=None, row=None, palette=None, col_wrap=None, height=5, aspect=1, markers=’o’, sharex=True, sharey=True, hue_order=None, col_order=None, row_order=None, legend=True, legend_out=True, x_estimator=None, x_bins=None, x_ci=’ci’, scatter=True, fit_reg=True, ci=95, n_boot=1000, units=None, seed=None, order=1, logistic=False, lowest=False, robust=False, logx=False, x_partial=None, y_partial=None, truncate=True, x_jitter=None, y_jitter=None, scatter_kws=None, line_kws=None, size=None) Parameters : This method is accepting the following parameters that are described below: x, y: ( optional) This parameters are column names in data. data : This parameter is DataFrame . hue, col, row : This parameters are define subsets of the data, which will be drawn on separate facets in the grid. See the *_order parameters to control the order of levels of this variable. palette: (optional) This parameter is palette name, list, or dict, Colors to use for the different levels of the hue variable. Should be something that can be interpreted by color_palette(), or a dictionary mapping hue levels to matplotlib colors. col_wrap : (optional) This parameter is of int type, “Wrap” the column variable at this width, so that the column facets span multiple rows. Incompatible with a row facet. height : (optional) This parameter is Height (in inches) of each facet. aspect : (optional) This parameter is Aspect ratio of each facet, so that aspect * height gives the width of each facet in inches. markers : (optional) This parameter is matplotlib marker code or list of marker codes, Markers for the scatterplot. If a list, each marker in the list will be used for each level of the hue variable. share{x, y} : (optional) This parameter is of bool type, ‘col’, or ‘row’, If true, the facets will share y axes across columns and/or x axes across rows. {hue, col, row}_order : (optional) This parameter is lists, Order for the levels of the faceting variables. By default, this will be the order that the levels appear in data or, if the variables are pandas categoricals, the category order. legend : (optional) This parameter accepting bool value, If True and there is a hue variable, add a legend. legend_out : (optional) This parameter accepting bool value, If True, the figure size will be extended, and the legend will be drawn outside the plot on the center right. x_estimator : (optional)This parameter is callable that maps vector -> scalar, Apply this function to each unique value of x and plot the resulting estimate. This is useful when x is a discrete variable. If x_ci is given, this estimate will be bootstrapped and a confidence interval will be drawn. x_bins : (optional) This parameter is int or vector, Bin the x variable into discrete bins and then estimate the central tendency and a confidence interval. This binning only influences how the scatter plot is drawn; the regression is still fit to the original data. This parameter is interpreted either as the number of evenly-sized (not necessary spaced) bins or the positions of the bin centers. When this parameter is used, it implies that the default of x_estimator is numpy.mean. x_ci : (optional) This parameter is “ci”, “sd”, int in [0, 100] or None, Size of the confidence interval used when plotting a central tendency for discrete values of x. If “ci”, defer to the value of the ci parameter. If “sd”, skip bootstrapping and show the standard deviation of the observations in each bin. scatter : (optional) This parameter accepting bool value . If True, draw a scatterplot with the underlying observations (or the x_estimator values). fit_reg : (optional) This parameter accepting bool value . If True, estimate and plot a regression model relating the x and y variables. ci : (optional) This parameter is int in [0, 100] or None, Size of the confidence interval for the regression estimate. This will be drawn using translucent bands around the regression line. The confidence interval is estimated using a bootstrap; for large datasets, it may be advisable to avoid that computation by setting this parameter to None. n_boot : (optional) This parameter is Number of bootstrap resamples used to estimate the ci. The default value attempts to balance time and stability; you may want to increase this value for “final” versions of plots. units : (optional) This parameter is variable name in data, If the x and y observations are nested within sampling units, those can be specified here. This will be taken into account when computing the confidence intervals by performing a multilevel bootstrap that resamples both units and observations (within unit). This does not otherwise influence how the regression is estimated or drawn. seed : (optional) This parameter is int, numpy.random.Generator, or numpy.random.RandomState, Seed or random number generator for reproducible bootstrapping. order : (optional) This parameter, order is greater than 1, use numpy.polyfit to estimate a polynomial regression. logistic : (optional) This parameter accepting bool value, If True, assume that y is a binary variable and use statsmodels to estimate a logistic regression model. Note that this is substantially more computationally intensive than linear regression, so you may wish to decrease the number of bootstrap resamples (n_boot) or set ci to None. lowest : (optional) This parameter accepting bool value, If True, use statsmodels to estimate a non-parametric lowest model (locally weighted linear regression). Note that confidence intervals cannot currently be drawn for this kind of model. robust : (optional) This parameter accepting bool value, If True, use statsmodels to estimate a robust regression. This will de-weight outliers. Note that this is substantially more computationally intensive than standard linear regression, so you may wish to decrease the number of bootstrap resamples (n_boot) or set ci to None. logx : (optional) This parameter accepting bool value. If True, estimate a linear regression of the form y ~ log(x), but plot the scatterplot and regression model in the input space. Note that x must be positive for this to work. {x, y}_partial : (optional) This parameter is strings in data or matrices, Confounding variables to regress out of the x or y variables before plotting. truncate : (optional) This parameter accepting bool value.If True, the regression line is bounded by the data limits. If False, it extends to the x axis limits. {x, y}_jitter : (optional) This parameter is Add uniform random noise of this size to either the x or y variables. The noise is added to a copy of the data after fitting the regression, and only influences the look of the scatterplot. This can be helpful when plotting variables that take discrete values. {scatter, line}_kws : (optional)dictionaries Returns : This method returns the FacetGrid object with the plot on it for further tweaking. Note: For downloading the Tips dataset Click Here. Below examples illustrate the lmplot() method of seaborn library. Example 1 : Scatter plot with regression line(by default). Python3 # importing the required libraryimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as plt # read a csv filedf = pd.read_csv('Tips.csv') # scatter plot with regression# line(by default)sns.lmplot(x ='total_bill', y ='tip', data = df) # Show the plotplt.show() Output : Example 2 : Scatter plot without regression line. Python3 # importing the required libraryimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as plt # read a csv filedf = pd.read_csv('Tips.csv') # scatter plot without regression# line.sns.lmplot(x ='total_bill', y ='tip', fit_reg = False, data = df) # Show the plotplt.show() Output : Example 3 : Scatter plot using hue attribute for coloring out points according to the sex. Python3 # importing the required libraryimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as plt # read a csv filedf = pd.read_csv('Tips.csv') # scatter plot using hue attribute# for colouring out points# according to the sexsns.lmplot(x ='total_bill', y ='tip', fit_reg = False, hue = 'sex', data = df) # Show the plotplt.show() Output : ruhelaa48 surinderdawra388 sooda367 Python-Seaborn Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Enumerate() in Python Different ways to create Pandas Dataframe How to Install PIP on Windows ? Python String | replace() Python Classes and Objects *args and **kwargs in Python Introduction To PYTHON Python OOPs Concepts Create a Pandas DataFrame from Lists
[ { "code": null, "e": 52, "s": 24, "text": "\n12 Dec, 2021" }, { "code": null, "e": 349, "s": 52, "text": "Seaborn is an amazing visualization library for statistical graphics plotting in Python. It provides beautiful default styles and color palettes to make statistical plots more attractive. It is built on the top of matplotlib library and also closely integrated to the data structures from pandas." }, { "code": null, "e": 422, "s": 349, "text": "seaborn.lmplot() method is used to draw a scatter plot onto a FacetGrid." }, { "code": null, "e": 953, "s": 422, "text": "Syntax : seaborn.lmplot(x, y, data, hue=None, col=None, row=None, palette=None, col_wrap=None, height=5, aspect=1, markers=’o’, sharex=True, sharey=True, hue_order=None, col_order=None, row_order=None, legend=True, legend_out=True, x_estimator=None, x_bins=None, x_ci=’ci’, scatter=True, fit_reg=True, ci=95, n_boot=1000, units=None, seed=None, order=1, logistic=False, lowest=False, robust=False, logx=False, x_partial=None, y_partial=None, truncate=True, x_jitter=None, y_jitter=None, scatter_kws=None, line_kws=None, size=None)" }, { "code": null, "e": 1043, "s": 953, "text": "Parameters : This method is accepting the following parameters that are described below: " }, { "code": null, "e": 1103, "s": 1043, "text": "x, y: ( optional) This parameters are column names in data." }, { "code": null, "e": 1140, "s": 1103, "text": "data : This parameter is DataFrame ." }, { "code": null, "e": 1332, "s": 1140, "text": "hue, col, row : This parameters are define subsets of the data, which will be drawn on separate facets in the grid. See the *_order parameters to control the order of levels of this variable." }, { "code": null, "e": 1580, "s": 1332, "text": "palette: (optional) This parameter is palette name, list, or dict, Colors to use for the different levels of the hue variable. Should be something that can be interpreted by color_palette(), or a dictionary mapping hue levels to matplotlib colors." }, { "code": null, "e": 1752, "s": 1580, "text": "col_wrap : (optional) This parameter is of int type, “Wrap” the column variable at this width, so that the column facets span multiple rows. Incompatible with a row facet." }, { "code": null, "e": 1824, "s": 1752, "text": "height : (optional) This parameter is Height (in inches) of each facet." }, { "code": null, "e": 1955, "s": 1824, "text": "aspect : (optional) This parameter is Aspect ratio of each facet, so that aspect * height gives the width of each facet in inches." }, { "code": null, "e": 2155, "s": 1955, "text": "markers : (optional) This parameter is matplotlib marker code or list of marker codes, Markers for the scatterplot. If a list, each marker in the list will be used for each level of the hue variable." }, { "code": null, "e": 2309, "s": 2155, "text": "share{x, y} : (optional) This parameter is of bool type, ‘col’, or ‘row’, If true, the facets will share y axes across columns and/or x axes across rows." }, { "code": null, "e": 2549, "s": 2309, "text": "{hue, col, row}_order : (optional) This parameter is lists, Order for the levels of the faceting variables. By default, this will be the order that the levels appear in data or, if the variables are pandas categoricals, the category order." }, { "code": null, "e": 2657, "s": 2549, "text": "legend : (optional) This parameter accepting bool value, If True and there is a hue variable, add a legend." }, { "code": null, "e": 2828, "s": 2657, "text": "legend_out : (optional) This parameter accepting bool value, If True, the figure size will be extended, and the legend will be drawn outside the plot on the center right." }, { "code": null, "e": 3126, "s": 2828, "text": "x_estimator : (optional)This parameter is callable that maps vector -> scalar, Apply this function to each unique value of x and plot the resulting estimate. This is useful when x is a discrete variable. If x_ci is given, this estimate will be bootstrapped and a confidence interval will be drawn." }, { "code": null, "e": 3612, "s": 3126, "text": "x_bins : (optional) This parameter is int or vector, Bin the x variable into discrete bins and then estimate the central tendency and a confidence interval. This binning only influences how the scatter plot is drawn; the regression is still fit to the original data. This parameter is interpreted either as the number of evenly-sized (not necessary spaced) bins or the positions of the bin centers. When this parameter is used, it implies that the default of x_estimator is numpy.mean." }, { "code": null, "e": 3923, "s": 3612, "text": "x_ci : (optional) This parameter is “ci”, “sd”, int in [0, 100] or None, Size of the confidence interval used when plotting a central tendency for discrete values of x. If “ci”, defer to the value of the ci parameter. If “sd”, skip bootstrapping and show the standard deviation of the observations in each bin." }, { "code": null, "e": 4072, "s": 3923, "text": "scatter : (optional) This parameter accepting bool value . If True, draw a scatterplot with the underlying observations (or the x_estimator values)." }, { "code": null, "e": 4209, "s": 4072, "text": "fit_reg : (optional) This parameter accepting bool value . If True, estimate and plot a regression model relating the x and y variables." }, { "code": null, "e": 4557, "s": 4209, "text": "ci : (optional) This parameter is int in [0, 100] or None, Size of the confidence interval for the regression estimate. This will be drawn using translucent bands around the regression line. The confidence interval is estimated using a bootstrap; for large datasets, it may be advisable to avoid that computation by setting this parameter to None." }, { "code": null, "e": 4775, "s": 4557, "text": "n_boot : (optional) This parameter is Number of bootstrap resamples used to estimate the ci. The default value attempts to balance time and stability; you may want to increase this value for “final” versions of plots." }, { "code": null, "e": 5169, "s": 4775, "text": "units : (optional) This parameter is variable name in data, If the x and y observations are nested within sampling units, those can be specified here. This will be taken into account when computing the confidence intervals by performing a multilevel bootstrap that resamples both units and observations (within unit). This does not otherwise influence how the regression is estimated or drawn." }, { "code": null, "e": 5327, "s": 5169, "text": "seed : (optional) This parameter is int, numpy.random.Generator, or numpy.random.RandomState, Seed or random number generator for reproducible bootstrapping." }, { "code": null, "e": 5442, "s": 5327, "text": "order : (optional) This parameter, order is greater than 1, use numpy.polyfit to estimate a polynomial regression." }, { "code": null, "e": 5783, "s": 5442, "text": "logistic : (optional) This parameter accepting bool value, If True, assume that y is a binary variable and use statsmodels to estimate a logistic regression model. Note that this is substantially more computationally intensive than linear regression, so you may wish to decrease the number of bootstrap resamples (n_boot) or set ci to None." }, { "code": null, "e": 6026, "s": 5783, "text": "lowest : (optional) This parameter accepting bool value, If True, use statsmodels to estimate a non-parametric lowest model (locally weighted linear regression). Note that confidence intervals cannot currently be drawn for this kind of model." }, { "code": null, "e": 6357, "s": 6026, "text": "robust : (optional) This parameter accepting bool value, If True, use statsmodels to estimate a robust regression. This will de-weight outliers. Note that this is substantially more computationally intensive than standard linear regression, so you may wish to decrease the number of bootstrap resamples (n_boot) or set ci to None." }, { "code": null, "e": 6587, "s": 6357, "text": "logx : (optional) This parameter accepting bool value. If True, estimate a linear regression of the form y ~ log(x), but plot the scatterplot and regression model in the input space. Note that x must be positive for this to work." }, { "code": null, "e": 6740, "s": 6587, "text": "{x, y}_partial : (optional) This parameter is strings in data or matrices, Confounding variables to regress out of the x or y variables before plotting." }, { "code": null, "e": 6901, "s": 6740, "text": "truncate : (optional) This parameter accepting bool value.If True, the regression line is bounded by the data limits. If False, it extends to the x axis limits." }, { "code": null, "e": 7207, "s": 6901, "text": "{x, y}_jitter : (optional) This parameter is Add uniform random noise of this size to either the x or y variables. The noise is added to a copy of the data after fitting the regression, and only influences the look of the scatterplot. This can be helpful when plotting variables that take discrete values." }, { "code": null, "e": 7252, "s": 7207, "text": "{scatter, line}_kws : (optional)dictionaries" }, { "code": null, "e": 7347, "s": 7252, "text": "Returns : This method returns the FacetGrid object with the plot on it for further tweaking. " }, { "code": null, "e": 7398, "s": 7347, "text": "Note: For downloading the Tips dataset Click Here." }, { "code": null, "e": 7464, "s": 7398, "text": "Below examples illustrate the lmplot() method of seaborn library." }, { "code": null, "e": 7525, "s": 7464, "text": "Example 1 : Scatter plot with regression line(by default). " }, { "code": null, "e": 7533, "s": 7525, "text": "Python3" }, { "code": "# importing the required libraryimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as plt # read a csv filedf = pd.read_csv('Tips.csv') # scatter plot with regression# line(by default)sns.lmplot(x ='total_bill', y ='tip', data = df) # Show the plotplt.show()", "e": 7806, "s": 7533, "text": null }, { "code": null, "e": 7817, "s": 7806, "text": "Output : " }, { "code": null, "e": 7868, "s": 7817, "text": "Example 2 : Scatter plot without regression line. " }, { "code": null, "e": 7876, "s": 7868, "text": "Python3" }, { "code": "# importing the required libraryimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as plt # read a csv filedf = pd.read_csv('Tips.csv') # scatter plot without regression# line.sns.lmplot(x ='total_bill', y ='tip', fit_reg = False, data = df) # Show the plotplt.show()", "e": 8168, "s": 7876, "text": null }, { "code": null, "e": 8178, "s": 8168, "text": "Output : " }, { "code": null, "e": 8270, "s": 8178, "text": "Example 3 : Scatter plot using hue attribute for coloring out points according to the sex. " }, { "code": null, "e": 8278, "s": 8270, "text": "Python3" }, { "code": "# importing the required libraryimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as plt # read a csv filedf = pd.read_csv('Tips.csv') # scatter plot using hue attribute# for colouring out points# according to the sexsns.lmplot(x ='total_bill', y ='tip', fit_reg = False, hue = 'sex', data = df) # Show the plotplt.show()", "e": 8633, "s": 8278, "text": null }, { "code": null, "e": 8643, "s": 8633, "text": "Output : " }, { "code": null, "e": 8655, "s": 8645, "text": "ruhelaa48" }, { "code": null, "e": 8672, "s": 8655, "text": "surinderdawra388" }, { "code": null, "e": 8681, "s": 8672, "text": "sooda367" }, { "code": null, "e": 8696, "s": 8681, "text": "Python-Seaborn" }, { "code": null, "e": 8703, "s": 8696, "text": "Python" }, { "code": null, "e": 8801, "s": 8703, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8819, "s": 8801, "text": "Python Dictionary" }, { "code": null, "e": 8841, "s": 8819, "text": "Enumerate() in Python" }, { "code": null, "e": 8883, "s": 8841, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 8915, "s": 8883, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 8941, "s": 8915, "text": "Python String | replace()" }, { "code": null, "e": 8968, "s": 8941, "text": "Python Classes and Objects" }, { "code": null, "e": 8997, "s": 8968, "text": "*args and **kwargs in Python" }, { "code": null, "e": 9020, "s": 8997, "text": "Introduction To PYTHON" }, { "code": null, "e": 9041, "s": 9020, "text": "Python OOPs Concepts" } ]
How to get value of selected radio button using JavaScript?
20 Jul, 2021 To get the value of selected radio button, a user-defined function can be created that gets all the radio buttons with the name attribute and finds the radio button selected using the checked property. The checked property returns True if the radio button is selected and False otherwise. If there are multiple Radio buttons in a webpage, first, all the input tags are fetched and then the values of all the tags that have type as ‘radio’ and are selected are displayed. Example 1: The following program displays the value of selected radio button when user clicks on Submit button. <!DOCTYPE html><html> <head> <title> Get value of selected radio button </title></head> <body> <p> Select a radio button and click on Submit. </p> Gender: <input type="radio" name="gender" value="Male">Male <input type="radio" name="gender" value="Female">Female <input type="radio" name="gender" value="Others">Others <br> <button type="button" onclick="displayRadioValue()"> Submit </button> <br> <div id="result"></div> <script> function displayRadioValue() { var ele = document.getElementsByName('gender'); for(i = 0; i < ele.length; i++) { if(ele[i].checked) document.getElementById("result").innerHTML = "Gender: "+ele[i].value; } } </script></body></html> Output : Example 2: The following program displays values of all the selected radio buttons when submit is clicked. <!DOCTYPE html><html> <head> <title> Get value of selected radio button </title></head> <body> <p> Select a radio button and click on Submit. </p> Gender: <input type="radio" name="Gender" value="Male">Male <input type="radio" name="Gender" value="Female">Female <input type="radio" name="Gender" value="Others">Others <br> Food Preference: <input type="radio" name="Food" value="Vegetarian">Vegetarian <input type="radio" name="Food" value="Non-Vegetarian">Non-Vegetarian <br> <button type="button" onclick="displayRadioValue()"> Submit </button> <br> <div id="result"></div> <script> function displayRadioValue() { document.getElementById("result").innerHTML = ""; var ele = document.getElementsByTagName('input'); for(i = 0; i < ele.length; i++) { if(ele[i].type="radio") { if(ele[i].checked) document.getElementById("result").innerHTML += ele[i].name + " Value: " + ele[i].value + "<br>"; } } } </script></body> </html> Output: JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples. JavaScript-Misc Picked JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n20 Jul, 2021" }, { "code": null, "e": 525, "s": 54, "text": "To get the value of selected radio button, a user-defined function can be created that gets all the radio buttons with the name attribute and finds the radio button selected using the checked property. The checked property returns True if the radio button is selected and False otherwise. If there are multiple Radio buttons in a webpage, first, all the input tags are fetched and then the values of all the tags that have type as ‘radio’ and are selected are displayed." }, { "code": null, "e": 637, "s": 525, "text": "Example 1: The following program displays the value of selected radio button when user clicks on Submit button." }, { "code": "<!DOCTYPE html><html> <head> <title> Get value of selected radio button </title></head> <body> <p> Select a radio button and click on Submit. </p> Gender: <input type=\"radio\" name=\"gender\" value=\"Male\">Male <input type=\"radio\" name=\"gender\" value=\"Female\">Female <input type=\"radio\" name=\"gender\" value=\"Others\">Others <br> <button type=\"button\" onclick=\"displayRadioValue()\"> Submit </button> <br> <div id=\"result\"></div> <script> function displayRadioValue() { var ele = document.getElementsByName('gender'); for(i = 0; i < ele.length; i++) { if(ele[i].checked) document.getElementById(\"result\").innerHTML = \"Gender: \"+ele[i].value; } } </script></body></html> ", "e": 1545, "s": 637, "text": null }, { "code": null, "e": 1554, "s": 1545, "text": "Output :" }, { "code": null, "e": 1661, "s": 1554, "text": "Example 2: The following program displays values of all the selected radio buttons when submit is clicked." }, { "code": "<!DOCTYPE html><html> <head> <title> Get value of selected radio button </title></head> <body> <p> Select a radio button and click on Submit. </p> Gender: <input type=\"radio\" name=\"Gender\" value=\"Male\">Male <input type=\"radio\" name=\"Gender\" value=\"Female\">Female <input type=\"radio\" name=\"Gender\" value=\"Others\">Others <br> Food Preference: <input type=\"radio\" name=\"Food\" value=\"Vegetarian\">Vegetarian <input type=\"radio\" name=\"Food\" value=\"Non-Vegetarian\">Non-Vegetarian <br> <button type=\"button\" onclick=\"displayRadioValue()\"> Submit </button> <br> <div id=\"result\"></div> <script> function displayRadioValue() { document.getElementById(\"result\").innerHTML = \"\"; var ele = document.getElementsByTagName('input'); for(i = 0; i < ele.length; i++) { if(ele[i].type=\"radio\") { if(ele[i].checked) document.getElementById(\"result\").innerHTML += ele[i].name + \" Value: \" + ele[i].value + \"<br>\"; } } } </script></body> </html> ", "e": 2976, "s": 1661, "text": null }, { "code": null, "e": 2984, "s": 2976, "text": "Output:" }, { "code": null, "e": 3203, "s": 2984, "text": "JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples." }, { "code": null, "e": 3219, "s": 3203, "text": "JavaScript-Misc" }, { "code": null, "e": 3226, "s": 3219, "text": "Picked" }, { "code": null, "e": 3237, "s": 3226, "text": "JavaScript" }, { "code": null, "e": 3254, "s": 3237, "text": "Web Technologies" }, { "code": null, "e": 3281, "s": 3254, "text": "Web technologies Questions" } ]
Matplotlib.ticker.LinearLocator Class in Python
16 Jun, 2022 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.ticker.LinearLocator class is used to determine the tick locations. At its first call the function tries to set up the number of ticks to make a nice tick partitioning. There after the interactive navigation improves as the number of ticks get fixed. The preset parameter is used to set locs based on lom, which is a dictionary mapping of vmin, vmax -> locs. Syntax: class matplotlib.ticker.LinearLocator(numticks=None, presets=None) Parameters: numticks: Number of ticks in total. presets: It is used to set locs based on lom, which is a dictionary mapping of vmin, vmax -> locs. Methods of the class: set_params(self, numticks=None, presets=None): It is used to set parameters within this locator. tick_values(self, vmin, vmax): It returns the values of located ticks between the vmin and vmax. view_limits(self, vmin, vmax): It is used to intelligently choose the view limits. Example 1: Python3 import numpy as npimport matplotlib.pyplot as pltimport matplotlib.ticker xGrid = np.linspace(1-1e-14, 1-1e-16, 30, dtype = np.longdouble) y = np.random.rand(len(xGrid)) plt.plot(xGrid, y)plt.xlim(1-1e-14, 1) loc = matplotlib.ticker.LinearLocator(numticks = 5)plt.gca().xaxis.set_major_locator(loc) plt.show() Output: Example 2: Python3 import numpy as npimport matplotlib.pyplot as pltimport matplotlib.ticker as ticker # Setup a plot such that only the bottom# spine is showndef setup(ax): ax.spines['right'].set_color('green') ax.spines['left'].set_color('red') ax.yaxis.set_major_locator(ticker.NullLocator()) ax.spines['top'].set_color('pink') ax.xaxis.set_ticks_position('bottom') ax.tick_params(which ='major', width = 1.00) ax.tick_params(which ='major', length = 5) ax.tick_params(which ='minor', width = 0.75) ax.tick_params(which ='minor', length = 2.5) ax.set_xlim(0, 5) ax.set_ylim(0, 1) ax.patch.set_alpha(0.0) plt.figure(figsize =(8, 6))n = 8ax = plt.subplot(n, 1, 4)setup(ax)ax.xaxis.set_major_locator(ticker.LinearLocator(3))ax.xaxis.set_minor_locator(ticker.LinearLocator(31)) ax.text(0.0, 0.1, "LinearLocator", fontsize = 14, transform = ax.transAxes) plt.subplots_adjust(left = 0.05, right = 0.95, bottom = 0.05, top = 1.05) plt.show() Output: surinderdawra388 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": "\n16 Jun, 2022" }, { "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": 615, "s": 240, "text": "The matplotlib.ticker.LinearLocator class is used to determine the tick locations. At its first call the function tries to set up the number of ticks to make a nice tick partitioning. There after the interactive navigation improves as the number of ticks get fixed. The preset parameter is used to set locs based on lom, which is a dictionary mapping of vmin, vmax -> locs." }, { "code": null, "e": 691, "s": 615, "text": "Syntax: class matplotlib.ticker.LinearLocator(numticks=None, presets=None) " }, { "code": null, "e": 703, "s": 691, "text": "Parameters:" }, { "code": null, "e": 739, "s": 703, "text": "numticks: Number of ticks in total." }, { "code": null, "e": 838, "s": 739, "text": "presets: It is used to set locs based on lom, which is a dictionary mapping of vmin, vmax -> locs." }, { "code": null, "e": 860, "s": 838, "text": "Methods of the class:" }, { "code": null, "e": 957, "s": 860, "text": "set_params(self, numticks=None, presets=None): It is used to set parameters within this locator." }, { "code": null, "e": 1054, "s": 957, "text": "tick_values(self, vmin, vmax): It returns the values of located ticks between the vmin and vmax." }, { "code": null, "e": 1137, "s": 1054, "text": "view_limits(self, vmin, vmax): It is used to intelligently choose the view limits." }, { "code": null, "e": 1149, "s": 1137, "text": "Example 1: " }, { "code": null, "e": 1157, "s": 1149, "text": "Python3" }, { "code": "import numpy as npimport matplotlib.pyplot as pltimport matplotlib.ticker xGrid = np.linspace(1-1e-14, 1-1e-16, 30, dtype = np.longdouble) y = np.random.rand(len(xGrid)) plt.plot(xGrid, y)plt.xlim(1-1e-14, 1) loc = matplotlib.ticker.LinearLocator(numticks = 5)plt.gca().xaxis.set_major_locator(loc) plt.show()", "e": 1487, "s": 1157, "text": null }, { "code": null, "e": 1495, "s": 1487, "text": "Output:" }, { "code": null, "e": 1510, "s": 1498, "text": "Example 2: " }, { "code": null, "e": 1518, "s": 1510, "text": "Python3" }, { "code": "import numpy as npimport matplotlib.pyplot as pltimport matplotlib.ticker as ticker # Setup a plot such that only the bottom# spine is showndef setup(ax): ax.spines['right'].set_color('green') ax.spines['left'].set_color('red') ax.yaxis.set_major_locator(ticker.NullLocator()) ax.spines['top'].set_color('pink') ax.xaxis.set_ticks_position('bottom') ax.tick_params(which ='major', width = 1.00) ax.tick_params(which ='major', length = 5) ax.tick_params(which ='minor', width = 0.75) ax.tick_params(which ='minor', length = 2.5) ax.set_xlim(0, 5) ax.set_ylim(0, 1) ax.patch.set_alpha(0.0) plt.figure(figsize =(8, 6))n = 8ax = plt.subplot(n, 1, 4)setup(ax)ax.xaxis.set_major_locator(ticker.LinearLocator(3))ax.xaxis.set_minor_locator(ticker.LinearLocator(31)) ax.text(0.0, 0.1, \"LinearLocator\", fontsize = 14, transform = ax.transAxes) plt.subplots_adjust(left = 0.05, right = 0.95, bottom = 0.05, top = 1.05) plt.show()", "e": 2565, "s": 1518, "text": null }, { "code": null, "e": 2573, "s": 2565, "text": "Output:" }, { "code": null, "e": 2592, "s": 2575, "text": "surinderdawra388" }, { "code": null, "e": 2610, "s": 2592, "text": "Python-matplotlib" }, { "code": null, "e": 2617, "s": 2610, "text": "Python" }, { "code": null, "e": 2633, "s": 2617, "text": "Write From Home" } ]
How to initialize all the imported modules in PyGame?
27 Apr, 2022 PyGame is Python library designed for game development. PyGame is built on the top of SDL library so it provides full functionality to develop game in Python. Pygame has many modules to perform it’s operation, before these modules can be used, they must be initialized. All the modules can be initialized individually or one at a time. This post describes how all the imported modules can be initialized at a time. Methods Used: pygame.init() – To initialize all the modules. It takes no arguments and return a tuple (numpass,numfail) which indicate the no of modules initialized successfully and the number of modules failed. pygame.get_init() – This method is used to check whether pygame modules are initialized or not. Example 1: This example initialize all the pygame modules and print the number of modules initialized successfully. Python3 # importing the libraryimport pygame # initializing all the imported# pygame modules(numpass,numfail) = pygame.init() # printing the number of modules# initialized successfullyprint('Number of modules initialized successfully:', numpass) Output: Number of modules initialized successfully: 6 Example 2: This example uses pygame.get_init() function to check whether pygame module is initialized or not. Python3 # importing the libraryimport pygame # initializing the modulespygame.init() # checking the initializationis_initialized = pygame.get_init() # printing the resultprint('Is pygame modules initialized:', is_initialized) Output: Is pygame modules initialized: True sooda367 avtarkumar719 Python-PyGame Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n27 Apr, 2022" }, { "code": null, "e": 443, "s": 28, "text": "PyGame is Python library designed for game development. PyGame is built on the top of SDL library so it provides full functionality to develop game in Python. Pygame has many modules to perform it’s operation, before these modules can be used, they must be initialized. All the modules can be initialized individually or one at a time. This post describes how all the imported modules can be initialized at a time." }, { "code": null, "e": 459, "s": 443, "text": "Methods Used: " }, { "code": null, "e": 659, "s": 459, "text": "pygame.init() – To initialize all the modules. It takes no arguments and return a tuple (numpass,numfail) which indicate the no of modules initialized successfully and the number of modules failed. " }, { "code": null, "e": 757, "s": 659, "text": "pygame.get_init() – This method is used to check whether pygame modules are initialized or not. " }, { "code": null, "e": 873, "s": 757, "text": "Example 1: This example initialize all the pygame modules and print the number of modules initialized successfully." }, { "code": null, "e": 881, "s": 873, "text": "Python3" }, { "code": "# importing the libraryimport pygame # initializing all the imported# pygame modules(numpass,numfail) = pygame.init() # printing the number of modules# initialized successfullyprint('Number of modules initialized successfully:', numpass)", "e": 1124, "s": 881, "text": null }, { "code": null, "e": 1137, "s": 1127, "text": "Output: " }, { "code": null, "e": 1185, "s": 1139, "text": "Number of modules initialized successfully: 6" }, { "code": null, "e": 1297, "s": 1187, "text": "Example 2: This example uses pygame.get_init() function to check whether pygame module is initialized or not." }, { "code": null, "e": 1307, "s": 1299, "text": "Python3" }, { "code": "# importing the libraryimport pygame # initializing the modulespygame.init() # checking the initializationis_initialized = pygame.get_init() # printing the resultprint('Is pygame modules initialized:', is_initialized)", "e": 1530, "s": 1307, "text": null }, { "code": null, "e": 1541, "s": 1533, "text": "Output:" }, { "code": null, "e": 1579, "s": 1543, "text": "Is pygame modules initialized: True" }, { "code": null, "e": 1590, "s": 1581, "text": "sooda367" }, { "code": null, "e": 1604, "s": 1590, "text": "avtarkumar719" }, { "code": null, "e": 1618, "s": 1604, "text": "Python-PyGame" }, { "code": null, "e": 1625, "s": 1618, "text": "Python" } ]
Output of python program | Set 11(Lists)
22 Apr, 2022 Pre-requisite: List in python 1) What is the output of the following program? Python data = [2, 3, 9]temp = [[x for x in[data]] for x in range(3)]print (temp) a) [[[2, 3, 9]], [[2, 3, 9]], [[2, 3, 9]]] b) [[2, 3, 9], [2, 3, 9], [2, 3, 9]] c) [[[2, 3, 9]], [[2, 3, 9]]] d) None of these Ans. (a) Explanation: [x for x in[data] returns a new list copying the values in the list data and the outer for statement prints the newly created list 3 times. 2) What is the output of the following program? Python data = [x for x in range(5)]temp = [x for x in range(7) if x in data and x%2==0]print(temp) a) [0, 2, 4, 6] b) [0, 2, 4] c) [0, 1, 2, 3, 4, 5] d) Runtime error Ans. (b) Explanation: The is statement checks whether the value lies in list data and if it does whether it’s divisible by 2. It does so for x in (0, 7). 3) What is the output of the following program? Python temp = ['Geeks', 'for', 'Geeks']arr = [i[0].upper() for i in temp]print(arr) a) [‘G’, ‘F’, ‘G’] b) [‘GEEKS’] c) [‘GEEKS’, ‘FOR’, ‘GEEKS’] d) Compilation error Ans. (a) Explanation: The variable i is used to iterate over each element in list temp. i[0] represent the character at 0th index of i and .upper() function is used to capitalize the character present at i[0]. 4) What is the output of the following program? Python temp = 'Geeks 22536 for 445 Geeks'data = [x for x in (int(x) for x in temp if x.isdigit()) if x%2 == 0]print(data) a) [2, 2, 6, 4, 4] b) Compilation error c) Runtime error d) [‘2’, ‘2’, ‘5’, ‘3’, ‘6’, ‘4’, ‘4’, ‘5’] Ans. (a) Explanation: This is an example of nested list comprehension. The inner list created contains a list of integer in temp. The outer list only procures those x which are a multiple of 2. 5) What is the output of the following program? Python data = [x for x in (x for x in 'Geeks 22966 for Geeks' if x.isdigit()) if(x in ([x for x in range(20)]))]print(data) a) [2, 2, 9, 6, 6] b) [] c) Compilation error d) Runtime error Ans. (b) Explanation: Since here x have not been converted to int, the condition in the if statement fails and therefore, the list remains empty. This article is contributed by Mayank Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. surinderdawra388 python-list Python-Output Program Output python-list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n22 Apr, 2022" }, { "code": null, "e": 133, "s": 54, "text": "Pre-requisite: List in python 1) What is the output of the following program? " }, { "code": null, "e": 140, "s": 133, "text": "Python" }, { "code": "data = [2, 3, 9]temp = [[x for x in[data]] for x in range(3)]print (temp)", "e": 214, "s": 140, "text": null }, { "code": null, "e": 552, "s": 214, "text": "a) [[[2, 3, 9]], [[2, 3, 9]], [[2, 3, 9]]] b) [[2, 3, 9], [2, 3, 9], [2, 3, 9]] c) [[[2, 3, 9]], [[2, 3, 9]]] d) None of these Ans. (a) Explanation: [x for x in[data] returns a new list copying the values in the list data and the outer for statement prints the newly created list 3 times. 2) What is the output of the following program? " }, { "code": null, "e": 559, "s": 552, "text": "Python" }, { "code": "data = [x for x in range(5)]temp = [x for x in range(7) if x in data and x%2==0]print(temp)", "e": 651, "s": 559, "text": null }, { "code": null, "e": 922, "s": 651, "text": "a) [0, 2, 4, 6] b) [0, 2, 4] c) [0, 1, 2, 3, 4, 5] d) Runtime error Ans. (b) Explanation: The is statement checks whether the value lies in list data and if it does whether it’s divisible by 2. It does so for x in (0, 7). 3) What is the output of the following program? " }, { "code": null, "e": 929, "s": 922, "text": "Python" }, { "code": "temp = ['Geeks', 'for', 'Geeks']arr = [i[0].upper() for i in temp]print(arr)", "e": 1006, "s": 929, "text": null }, { "code": null, "e": 1347, "s": 1006, "text": "a) [‘G’, ‘F’, ‘G’] b) [‘GEEKS’] c) [‘GEEKS’, ‘FOR’, ‘GEEKS’] d) Compilation error Ans. (a) Explanation: The variable i is used to iterate over each element in list temp. i[0] represent the character at 0th index of i and .upper() function is used to capitalize the character present at i[0]. 4) What is the output of the following program? " }, { "code": null, "e": 1354, "s": 1347, "text": "Python" }, { "code": "temp = 'Geeks 22536 for 445 Geeks'data = [x for x in (int(x) for x in temp if x.isdigit()) if x%2 == 0]print(data)", "e": 1469, "s": 1354, "text": null }, { "code": null, "e": 1813, "s": 1469, "text": "a) [2, 2, 6, 4, 4] b) Compilation error c) Runtime error d) [‘2’, ‘2’, ‘5’, ‘3’, ‘6’, ‘4’, ‘4’, ‘5’] Ans. (a) Explanation: This is an example of nested list comprehension. The inner list created contains a list of integer in temp. The outer list only procures those x which are a multiple of 2. 5) What is the output of the following program? " }, { "code": null, "e": 1820, "s": 1813, "text": "Python" }, { "code": "data = [x for x in (x for x in 'Geeks 22966 for Geeks' if x.isdigit()) if(x in ([x for x in range(20)]))]print(data)", "e": 1937, "s": 1820, "text": null }, { "code": null, "e": 2567, "s": 1937, "text": "a) [2, 2, 9, 6, 6] b) [] c) Compilation error d) Runtime error Ans. (b) Explanation: Since here x have not been converted to int, the condition in the if statement fails and therefore, the list remains empty. This article is contributed by Mayank Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 2584, "s": 2567, "text": "surinderdawra388" }, { "code": null, "e": 2596, "s": 2584, "text": "python-list" }, { "code": null, "e": 2610, "s": 2596, "text": "Python-Output" }, { "code": null, "e": 2625, "s": 2610, "text": "Program Output" }, { "code": null, "e": 2637, "s": 2625, "text": "python-list" } ]
Highest power of 2 less than or equal to given number
14 Jun, 2022 Given a number n, find the highest power of 2 that is smaller than or equal to n. Examples : Input : n = 10 Output : 8 Input : n = 19 Output : 16 Input : n = 32 Output : 32 A simple solution is to start checking from n and keep decrementing until we find a power of 2. C++ C Java Python3 C# PHP Javascript // C++ program to find highest power of 2 smaller// than or equal to n.#include <bits/stdc++.h>using namespace std; int highestPowerof2(int n){ int res = 0; for (int i = n; i >= 1; i--) { // If i is a power of 2 if ((i & (i - 1)) == 0) { res = i; break; } } return res;} // Driver codeint main(){ int n = 10; cout << highestPowerof2(n); return 0;} // This code is contributed by Sania Kumari Gupta// (kriSania804) // C program to find highest power of 2 smaller// than or equal to n.#include <stdio.h> int highestPowerof2(int n){ int res = 0; for (int i = n; i >= 1; i--) { // If i is a power of 2 if ((i & (i - 1)) == 0) { res = i; break; } } return res;} // Driver codeint main(){ int n = 10; printf("%d", highestPowerof2(n)); return 0;} // This code is contributed by Sania Kumari Gupta// (kriSania804) // Java program to find highest power of// 2 smaller than or equal to n.class GFG{ static int highestPowerof2(int n){ int res = 0; for(int i = n; i >= 1; i--) { // If i is a power of 2 if ((i & (i-1)) == 0) { res = i; break; } } return res;} // Driver codepublic static void main(String[] args){ int n = 10; System.out.print(highestPowerof2(n));}} // This code is contributed by 29AjayKumar # Python3 program to find highest# power of 2 smaller than or# equal to n.def highestPowerof2(n): res = 0; for i in range(n, 0, -1): # If i is a power of 2 if ((i & (i - 1)) == 0): res = i; break; return res; # Driver coden = 10;print(highestPowerof2(n)); # This code is contributed by mits // C# code to find highest power// of 2 smaller than or equal to n.using System; class GFG{public static int highestPowerof2(int n){ int res = 0; for (int i = n; i >= 1; i--) { // If i is a power of 2 if ((i & (i - 1)) == 0) { res = i; break; } } return res;} // Driver Code static public void Main () { int n = 10; Console.WriteLine(highestPowerof2(n)); }} // This code is contributed by ajit <?php// PHP program to find highest// power of 2 smaller than or// equal to n.function highestPowerof2($n){ $res = 0; for ($i = $n; $i >= 1; $i--) { // If i is a power of 2 if (($i & ($i - 1)) == 0) { $res = $i; break; } } return $res;} // Driver code$n = 10;echo highestPowerof2($n); // This code is contributed by m_kit?> <script> // JavaScript program to find highest power// of 2 smaller than or equal to n. function highestPowerof2(n) { let res = 0; for (let i = n; i >= 1; i--) { // If i is a power of 2 if ((i & (i - 1)) == 0) { res = i; break; } } return res; } // Driver code let n = 10; document.write(highestPowerof2(n)); </script> 8 Time complexity : O(n). In worst case, the loop runs floor(n/2) times. The worst case happens when n is of the form 2x – 1. Auxiliary Space : O(1) since only constant space is used for variables An efficient solution is to use bitwise left shift operator to find all powers of 2 starting from 1. For every power check if it is smaller than or equal to n or not. Below is the implementation of the idea. C++ Java python3 C# PHP Javascript // C++ program to find highest power of 2 smaller// than or equal to n.#include<bits/stdc++.h>using namespace std; int highestPowerof2(unsigned int n){ // Invalid input if (n < 1) return 0; int res = 1; // Try all powers starting from 2^1 for (int i=0; i<8*sizeof(unsigned int); i++) { int curr = 1 << i; // If current power is more than n, break if (curr > n) break; res = curr; } return res;} // Driver codeint main(){ int n = 10; cout << highestPowerof2(n); return 0;} // Java program to find// highest power of 2 smaller// than or equal to n.import java.io.*; class GFG{static int highestPowerof2(int n){ // Invalid input if (n < 1) return 0; int res = 1; // Try all powers // starting from 2^1 for (int i = 0; i < 8 * Integer.BYTES; i++) { int curr = 1 << i; // If current power is // more than n, break if (curr > n) break; res = curr; } return res;} // Driver codepublic static void main(String[] args){ int n = 10; System.out.println(highestPowerof2(n));}} // This code is contributed aj_36 # Python3 program to find highest power of 2 smaller# than or equal to n. import sys def highestPowerof2( n): # Invalid input if (n < 1): return 0 res = 1 #Try all powers starting from 2^1 for i in range(8*sys.getsizeof(n)): curr = 1 << i # If current power is more than n, break if (curr > n): break res = curr return res # Driver codeif __name__ == "__main__": n = 10 print(highestPowerof2(n)) // C# program to find// highest power of 2 smaller// than or equal to n.using System; class GFG{static int highestPowerof2(int n){ // Invalid input if (n < 1) return 0; int res = 1; // Try all powers // starting from 2^1 for (int i = 0; i < 8 * sizeof(uint); i++) { int curr = 1 << i; // If current power is // more than n, break if (curr > n) break; res = curr; } return res;} // Driver codestatic public void Main (){ int n = 10; Console.WriteLine(highestPowerof2(n));}} // This code is contributed ajit <?php// PHP program to find highest// power of 2 smaller// than or equal to n. function highestPowerof2($n){ // Invalid input if ($n < 1) return 0; $res = 1; // Try all powers starting // from 2^1 for ($i = 0; $i < 8 * PHP_INT_SIZE; $i++) { $curr = 1 << $i; // If current power is // more than n, break if ($curr > $n) break; $res = $curr; } return $res;} // Driver code$n = 10;echo highestPowerof2($n); // This code is contributed// by m_kit?> <script> function highestPowerof2(n){ // Invalid input if (n < 1) return 0; let res = 1; // Try all powers starting from 2^1 for (let i=0; i<8; i++) { let curr = 1 << i; // If current power is more than n, break if (curr > n) break; res = curr; } return res;} // Driver code let n = 10;document.write(highestPowerof2(n)); </script> 8 Time Complexity: O(32) Auxiliary Space: O(1) A Solution using Log(n)Thanks to Anshuman Jha for suggesting this solution. C++ Java Python3 C# PHP Javascript // C++ program to find highest power of 2 smaller// than or equal to n.#include<bits/stdc++.h>using namespace std; int highestPowerof2(int n){ int p = (int)log2(n); return (int)pow(2, p);} // Driver codeint main(){ int n = 10; cout << highestPowerof2(n); return 0;} // Java program to find// highest power of 2// smaller than or equal to n.import java.io.*; class GFG{static int highestPowerof2(int n){ int p = (int)(Math.log(n) / Math.log(2)); return (int)Math.pow(2, p);} // Driver codepublic static void main (String[] args){ int n = 10; System.out.println(highestPowerof2(n));}} // This code is contributed// by m_kit # Python3 program to find highest# power of 2 smaller than or# equal to n.import math def highestPowerof2(n): p = int(math.log(n, 2)); return int(pow(2, p)); # Driver coden = 10;print(highestPowerof2(n)); # This code is contributed by mits // C# program to find// highest power of 2// smaller than or equal to n.using System; class GFG{static int highestPowerof2(int n){ int p = (int)(Math.Log(n) / Math.Log(2)); return (int)Math.Pow(2, p);} // Driver codestatic public void Main (){ int n = 10; Console.WriteLine(highestPowerof2(n));}} // This code is contributed// by ajit <?php// PHP program to find highest// power of 2 smaller than or// equal to n.function highestPowerof2($n){ $p = (int)log($n, 2); return (int)pow(2, $p);} // Driver code$n = 10;echo highestPowerof2($n); // This code is contributed by ajit?> <script> // Javascript program to find // highest power of 2 // smaller than or equal to n. function highestPowerof2(n) { let p = parseInt(Math.log(n) / Math.log(2), 10); return Math.pow(2, p); } let n = 10; document.write(highestPowerof2(n)); // This code is contributed by divyeshrabadiya07.</script> 8 Time Complexity: O(logn) Auxiliary Space: O(1) Solution using bitmasks : C++ Java Python3 C# Javascript // C++ program to find highest power of 2 smaller// than or equal to n.#include <iostream>using namespace std; unsigned highestPowerof2(unsigned x){ // check for the set bits x |= x >> 1; x |= x >> 2; x |= x >> 4; x |= x >> 8; x |= x >> 16; // Then we remove all but the top bit by xor'ing the // string of 1's with that string of 1's shifted one to // the left, and we end up with just the one top bit // followed by 0's. return x ^ (x >> 1);} int main(){ int n = 10; cout << highestPowerof2(n) << "\n"; return 0;} // This code is contributed by Rudrakshi. // Java program to find highest power of 2 smaller// than or equal to n.import java.io.*;class GFG{ static int highestPowerof2(int x) { // check for the set bits x |= x >> 1; x |= x >> 2; x |= x >> 4; x |= x >> 8; x |= x >> 16; // Then we remove all but the top bit by xor'ing the // string of 1's with that string of 1's shifted one to // the left, and we end up with just the one top bit // followed by 0's. return x ^ (x >> 1); } // Driver code public static void main (String[] args) { int n = 10; System.out.println(highestPowerof2(n)); }} // This code is contributed by avanitrachhadiya2155 # Python3 program to find highest power of 2 smaller than or equal to n. def highestPowerof2(x): # check for the set bits x |= x >> 1 x |= x >> 2 x |= x >> 4 x |= x >> 8 x |= x >> 16 # Then we remove all but the top bit by xor'ing the # string of 1's with that string of 1's shifted one to # the left, and we end up with just the one top bit # followed by 0's. return x ^ (x >> 1) n = 10print(highestPowerof2(n)) # This code is contributed by divyesh072019. // C# program to find highest power of 2 smaller// than or equal to n.using System;public class GFG{ static int highestPowerof2(int x) { // check for the set bits x |= x >> 1; x |= x >> 2; x |= x >> 4; x |= x >> 8; x |= x >> 16; // Then we remove all but the top bit by xor'ing the // string of 1's with that string of 1's shifted one to // the left, and we end up with just the one top bit // followed by 0's. return x ^ (x >> 1); } // Driver code public static void Main(String[] args) { int n = 10; Console.WriteLine(highestPowerof2(n)); }} // This code is contributed by umadevi9616 <script>// Javascript program to find highest power of 2 smaller// than or equal to n.function highestPowerof2(x){ // check for the set bits x |= x >> 1; x |= x >> 2; x |= x >> 4; x |= x >> 8; x |= x >> 16; // Then we remove all but the top bit by xor'ing the // string of 1's with that string of 1's shifted one to // the left, and we end up with just the one top bit // followed by 0's. return x ^ (x >> 1);} let n = 10;document.write(highestPowerof2(n)) // This code is contributed by rag2127</script> 8 Time Complexity: O(1) Auxiliary Space: O(1) since only constant space is used for variables A solution using MSB If the given number is the power of two then it is the required number otherwise set only the most significant bit which gives us the required number. C++ // C++ program to find// smallest power of 2// smaller than or equal to n#include <iostream>using namespace std; long long highestPowerof2(long long N){ // if N is a power of two simply return it if (!(N & (N - 1))) return N; // else set only the most significant bit return 0x8000000000000000 >> (__builtin_clzll(N));} // Driver Codeint main(){ long long n = 5; cout << highestPowerof2(n); return 0;} // This code is contributed by phasing17 4 Time Complexity : O(1) as counting leading zeroes can cause at most O(64) time complexity.Auxiliary Space: O(1) Application Problem: Some people are standing in a queue. A selection process follows a rule where people standing on even positions are selected. Of the selected people a queue is formed and again out of these only people on even position are selected. This continues until we are left with one person. Find out the position of that person in the original queue. Print the position(original queue) of that person who is left. Examples : Input: n = 10 Output:8 Explanation : 1 2 3 4 5 6 7 8 9 10 ===>Given queue 2 4 6 8 10 4 8 8 Input: n = 17 Input: 16 Explanation : 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 ===>Given queue 2 4 6 8 10 12 14 16 4 8 12 16 8 16 16 Related Article : Power of 2 greater than or equal to a given number.This article is contributed by Sahil Chhabra. 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 jit_t Mithun Kumar ukasp AmulyaSahoo chinmoy1997pal mohit kumar 29 divyeshrabadiya07 29AjayKumar sonirudrakshi99 rag2127 avanitrachhadiya2155 umadevi9616 divyesh072019 phasing17 krisania804 technophpfij Amazon Bit Magic Mathematical Recursion Amazon Mathematical Recursion Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Little and Big Endian Mystery Bits manipulation (Important tactics) Binary representation of a given number Josephus problem | Set 1 (A O(n) Solution) Divide two integers without using multiplication, division and mod operator Program for Fibonacci numbers Set in C++ Standard Template Library (STL) Write a program to print all permutations of a given string C++ Data Types Merge two sorted arrays
[ { "code": null, "e": 52, "s": 24, "text": "\n14 Jun, 2022" }, { "code": null, "e": 134, "s": 52, "text": "Given a number n, find the highest power of 2 that is smaller than or equal to n." }, { "code": null, "e": 146, "s": 134, "text": "Examples : " }, { "code": null, "e": 228, "s": 146, "text": "Input : n = 10\nOutput : 8\n\nInput : n = 19\nOutput : 16\n\nInput : n = 32\nOutput : 32" }, { "code": null, "e": 326, "s": 228, "text": "A simple solution is to start checking from n and keep decrementing until we find a power of 2. " }, { "code": null, "e": 330, "s": 326, "text": "C++" }, { "code": null, "e": 332, "s": 330, "text": "C" }, { "code": null, "e": 337, "s": 332, "text": "Java" }, { "code": null, "e": 345, "s": 337, "text": "Python3" }, { "code": null, "e": 348, "s": 345, "text": "C#" }, { "code": null, "e": 352, "s": 348, "text": "PHP" }, { "code": null, "e": 363, "s": 352, "text": "Javascript" }, { "code": "// C++ program to find highest power of 2 smaller// than or equal to n.#include <bits/stdc++.h>using namespace std; int highestPowerof2(int n){ int res = 0; for (int i = n; i >= 1; i--) { // If i is a power of 2 if ((i & (i - 1)) == 0) { res = i; break; } } return res;} // Driver codeint main(){ int n = 10; cout << highestPowerof2(n); return 0;} // This code is contributed by Sania Kumari Gupta// (kriSania804)", "e": 841, "s": 363, "text": null }, { "code": "// C program to find highest power of 2 smaller// than or equal to n.#include <stdio.h> int highestPowerof2(int n){ int res = 0; for (int i = n; i >= 1; i--) { // If i is a power of 2 if ((i & (i - 1)) == 0) { res = i; break; } } return res;} // Driver codeint main(){ int n = 10; printf(\"%d\", highestPowerof2(n)); return 0;} // This code is contributed by Sania Kumari Gupta// (kriSania804)", "e": 1297, "s": 841, "text": null }, { "code": "// Java program to find highest power of// 2 smaller than or equal to n.class GFG{ static int highestPowerof2(int n){ int res = 0; for(int i = n; i >= 1; i--) { // If i is a power of 2 if ((i & (i-1)) == 0) { res = i; break; } } return res;} // Driver codepublic static void main(String[] args){ int n = 10; System.out.print(highestPowerof2(n));}} // This code is contributed by 29AjayKumar", "e": 1773, "s": 1297, "text": null }, { "code": "# Python3 program to find highest# power of 2 smaller than or# equal to n.def highestPowerof2(n): res = 0; for i in range(n, 0, -1): # If i is a power of 2 if ((i & (i - 1)) == 0): res = i; break; return res; # Driver coden = 10;print(highestPowerof2(n)); # This code is contributed by mits", "e": 2141, "s": 1773, "text": null }, { "code": "// C# code to find highest power// of 2 smaller than or equal to n.using System; class GFG{public static int highestPowerof2(int n){ int res = 0; for (int i = n; i >= 1; i--) { // If i is a power of 2 if ((i & (i - 1)) == 0) { res = i; break; } } return res;} // Driver Code static public void Main () { int n = 10; Console.WriteLine(highestPowerof2(n)); }} // This code is contributed by ajit", "e": 2655, "s": 2141, "text": null }, { "code": "<?php// PHP program to find highest// power of 2 smaller than or// equal to n.function highestPowerof2($n){ $res = 0; for ($i = $n; $i >= 1; $i--) { // If i is a power of 2 if (($i & ($i - 1)) == 0) { $res = $i; break; } } return $res;} // Driver code$n = 10;echo highestPowerof2($n); // This code is contributed by m_kit?>", "e": 3048, "s": 2655, "text": null }, { "code": "<script> // JavaScript program to find highest power// of 2 smaller than or equal to n. function highestPowerof2(n) { let res = 0; for (let i = n; i >= 1; i--) { // If i is a power of 2 if ((i & (i - 1)) == 0) { res = i; break; } } return res; } // Driver code let n = 10; document.write(highestPowerof2(n)); </script>", "e": 3488, "s": 3048, "text": null }, { "code": null, "e": 3490, "s": 3488, "text": "8" }, { "code": null, "e": 3614, "s": 3490, "text": "Time complexity : O(n). In worst case, the loop runs floor(n/2) times. The worst case happens when n is of the form 2x – 1." }, { "code": null, "e": 3685, "s": 3614, "text": "Auxiliary Space : O(1) since only constant space is used for variables" }, { "code": null, "e": 3893, "s": 3685, "text": "An efficient solution is to use bitwise left shift operator to find all powers of 2 starting from 1. For every power check if it is smaller than or equal to n or not. Below is the implementation of the idea." }, { "code": null, "e": 3897, "s": 3893, "text": "C++" }, { "code": null, "e": 3902, "s": 3897, "text": "Java" }, { "code": null, "e": 3910, "s": 3902, "text": "python3" }, { "code": null, "e": 3913, "s": 3910, "text": "C#" }, { "code": null, "e": 3917, "s": 3913, "text": "PHP" }, { "code": null, "e": 3928, "s": 3917, "text": "Javascript" }, { "code": "// C++ program to find highest power of 2 smaller// than or equal to n.#include<bits/stdc++.h>using namespace std; int highestPowerof2(unsigned int n){ // Invalid input if (n < 1) return 0; int res = 1; // Try all powers starting from 2^1 for (int i=0; i<8*sizeof(unsigned int); i++) { int curr = 1 << i; // If current power is more than n, break if (curr > n) break; res = curr; } return res;} // Driver codeint main(){ int n = 10; cout << highestPowerof2(n); return 0;}", "e": 4483, "s": 3928, "text": null }, { "code": "// Java program to find// highest power of 2 smaller// than or equal to n.import java.io.*; class GFG{static int highestPowerof2(int n){ // Invalid input if (n < 1) return 0; int res = 1; // Try all powers // starting from 2^1 for (int i = 0; i < 8 * Integer.BYTES; i++) { int curr = 1 << i; // If current power is // more than n, break if (curr > n) break; res = curr; } return res;} // Driver codepublic static void main(String[] args){ int n = 10; System.out.println(highestPowerof2(n));}} // This code is contributed aj_36", "e": 5097, "s": 4483, "text": null }, { "code": "# Python3 program to find highest power of 2 smaller# than or equal to n. import sys def highestPowerof2( n): # Invalid input if (n < 1): return 0 res = 1 #Try all powers starting from 2^1 for i in range(8*sys.getsizeof(n)): curr = 1 << i # If current power is more than n, break if (curr > n): break res = curr return res # Driver codeif __name__ == \"__main__\": n = 10 print(highestPowerof2(n)) ", "e": 5585, "s": 5097, "text": null }, { "code": "// C# program to find// highest power of 2 smaller// than or equal to n.using System; class GFG{static int highestPowerof2(int n){ // Invalid input if (n < 1) return 0; int res = 1; // Try all powers // starting from 2^1 for (int i = 0; i < 8 * sizeof(uint); i++) { int curr = 1 << i; // If current power is // more than n, break if (curr > n) break; res = curr; } return res;} // Driver codestatic public void Main (){ int n = 10; Console.WriteLine(highestPowerof2(n));}} // This code is contributed ajit", "e": 6178, "s": 5585, "text": null }, { "code": "<?php// PHP program to find highest// power of 2 smaller// than or equal to n. function highestPowerof2($n){ // Invalid input if ($n < 1) return 0; $res = 1; // Try all powers starting // from 2^1 for ($i = 0; $i < 8 * PHP_INT_SIZE; $i++) { $curr = 1 << $i; // If current power is // more than n, break if ($curr > $n) break; $res = $curr; } return $res;} // Driver code$n = 10;echo highestPowerof2($n); // This code is contributed// by m_kit?>", "e": 6708, "s": 6178, "text": null }, { "code": "<script> function highestPowerof2(n){ // Invalid input if (n < 1) return 0; let res = 1; // Try all powers starting from 2^1 for (let i=0; i<8; i++) { let curr = 1 << i; // If current power is more than n, break if (curr > n) break; res = curr; } return res;} // Driver code let n = 10;document.write(highestPowerof2(n)); </script>", "e": 7115, "s": 6708, "text": null }, { "code": null, "e": 7117, "s": 7115, "text": "8" }, { "code": null, "e": 7140, "s": 7117, "text": "Time Complexity: O(32)" }, { "code": null, "e": 7162, "s": 7140, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 7239, "s": 7162, "text": "A Solution using Log(n)Thanks to Anshuman Jha for suggesting this solution. " }, { "code": null, "e": 7243, "s": 7239, "text": "C++" }, { "code": null, "e": 7248, "s": 7243, "text": "Java" }, { "code": null, "e": 7256, "s": 7248, "text": "Python3" }, { "code": null, "e": 7259, "s": 7256, "text": "C#" }, { "code": null, "e": 7263, "s": 7259, "text": "PHP" }, { "code": null, "e": 7274, "s": 7263, "text": "Javascript" }, { "code": "// C++ program to find highest power of 2 smaller// than or equal to n.#include<bits/stdc++.h>using namespace std; int highestPowerof2(int n){ int p = (int)log2(n); return (int)pow(2, p);} // Driver codeint main(){ int n = 10; cout << highestPowerof2(n); return 0;}", "e": 7553, "s": 7274, "text": null }, { "code": "// Java program to find// highest power of 2// smaller than or equal to n.import java.io.*; class GFG{static int highestPowerof2(int n){ int p = (int)(Math.log(n) / Math.log(2)); return (int)Math.pow(2, p);} // Driver codepublic static void main (String[] args){ int n = 10; System.out.println(highestPowerof2(n));}} // This code is contributed// by m_kit", "e": 7943, "s": 7553, "text": null }, { "code": "# Python3 program to find highest# power of 2 smaller than or# equal to n.import math def highestPowerof2(n): p = int(math.log(n, 2)); return int(pow(2, p)); # Driver coden = 10;print(highestPowerof2(n)); # This code is contributed by mits", "e": 8190, "s": 7943, "text": null }, { "code": "// C# program to find// highest power of 2// smaller than or equal to n.using System; class GFG{static int highestPowerof2(int n){ int p = (int)(Math.Log(n) / Math.Log(2)); return (int)Math.Pow(2, p);} // Driver codestatic public void Main (){ int n = 10; Console.WriteLine(highestPowerof2(n));}} // This code is contributed// by ajit", "e": 8555, "s": 8190, "text": null }, { "code": "<?php// PHP program to find highest// power of 2 smaller than or// equal to n.function highestPowerof2($n){ $p = (int)log($n, 2); return (int)pow(2, $p);} // Driver code$n = 10;echo highestPowerof2($n); // This code is contributed by ajit?>", "e": 8802, "s": 8555, "text": null }, { "code": "<script> // Javascript program to find // highest power of 2 // smaller than or equal to n. function highestPowerof2(n) { let p = parseInt(Math.log(n) / Math.log(2), 10); return Math.pow(2, p); } let n = 10; document.write(highestPowerof2(n)); // This code is contributed by divyeshrabadiya07.</script>", "e": 9161, "s": 8802, "text": null }, { "code": null, "e": 9163, "s": 9161, "text": "8" }, { "code": null, "e": 9188, "s": 9163, "text": "Time Complexity: O(logn)" }, { "code": null, "e": 9210, "s": 9188, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 9236, "s": 9210, "text": "Solution using bitmasks :" }, { "code": null, "e": 9240, "s": 9236, "text": "C++" }, { "code": null, "e": 9245, "s": 9240, "text": "Java" }, { "code": null, "e": 9253, "s": 9245, "text": "Python3" }, { "code": null, "e": 9256, "s": 9253, "text": "C#" }, { "code": null, "e": 9267, "s": 9256, "text": "Javascript" }, { "code": "// C++ program to find highest power of 2 smaller// than or equal to n.#include <iostream>using namespace std; unsigned highestPowerof2(unsigned x){ // check for the set bits x |= x >> 1; x |= x >> 2; x |= x >> 4; x |= x >> 8; x |= x >> 16; // Then we remove all but the top bit by xor'ing the // string of 1's with that string of 1's shifted one to // the left, and we end up with just the one top bit // followed by 0's. return x ^ (x >> 1);} int main(){ int n = 10; cout << highestPowerof2(n) << \"\\n\"; return 0;} // This code is contributed by Rudrakshi.", "e": 9870, "s": 9267, "text": null }, { "code": "// Java program to find highest power of 2 smaller// than or equal to n.import java.io.*;class GFG{ static int highestPowerof2(int x) { // check for the set bits x |= x >> 1; x |= x >> 2; x |= x >> 4; x |= x >> 8; x |= x >> 16; // Then we remove all but the top bit by xor'ing the // string of 1's with that string of 1's shifted one to // the left, and we end up with just the one top bit // followed by 0's. return x ^ (x >> 1); } // Driver code public static void main (String[] args) { int n = 10; System.out.println(highestPowerof2(n)); }} // This code is contributed by avanitrachhadiya2155", "e": 10616, "s": 9870, "text": null }, { "code": "# Python3 program to find highest power of 2 smaller than or equal to n. def highestPowerof2(x): # check for the set bits x |= x >> 1 x |= x >> 2 x |= x >> 4 x |= x >> 8 x |= x >> 16 # Then we remove all but the top bit by xor'ing the # string of 1's with that string of 1's shifted one to # the left, and we end up with just the one top bit # followed by 0's. return x ^ (x >> 1) n = 10print(highestPowerof2(n)) # This code is contributed by divyesh072019.", "e": 11112, "s": 10616, "text": null }, { "code": "// C# program to find highest power of 2 smaller// than or equal to n.using System;public class GFG{ static int highestPowerof2(int x) { // check for the set bits x |= x >> 1; x |= x >> 2; x |= x >> 4; x |= x >> 8; x |= x >> 16; // Then we remove all but the top bit by xor'ing the // string of 1's with that string of 1's shifted one to // the left, and we end up with just the one top bit // followed by 0's. return x ^ (x >> 1); } // Driver code public static void Main(String[] args) { int n = 10; Console.WriteLine(highestPowerof2(n)); }} // This code is contributed by umadevi9616", "e": 11758, "s": 11112, "text": null }, { "code": "<script>// Javascript program to find highest power of 2 smaller// than or equal to n.function highestPowerof2(x){ // check for the set bits x |= x >> 1; x |= x >> 2; x |= x >> 4; x |= x >> 8; x |= x >> 16; // Then we remove all but the top bit by xor'ing the // string of 1's with that string of 1's shifted one to // the left, and we end up with just the one top bit // followed by 0's. return x ^ (x >> 1);} let n = 10;document.write(highestPowerof2(n)) // This code is contributed by rag2127</script>", "e": 12299, "s": 11758, "text": null }, { "code": null, "e": 12301, "s": 12299, "text": "8" }, { "code": null, "e": 12323, "s": 12301, "text": "Time Complexity: O(1)" }, { "code": null, "e": 12393, "s": 12323, "text": "Auxiliary Space: O(1) since only constant space is used for variables" }, { "code": null, "e": 12414, "s": 12393, "text": "A solution using MSB" }, { "code": null, "e": 12565, "s": 12414, "text": "If the given number is the power of two then it is the required number otherwise set only the most significant bit which gives us the required number." }, { "code": null, "e": 12569, "s": 12565, "text": "C++" }, { "code": "// C++ program to find// smallest power of 2// smaller than or equal to n#include <iostream>using namespace std; long long highestPowerof2(long long N){ // if N is a power of two simply return it if (!(N & (N - 1))) return N; // else set only the most significant bit return 0x8000000000000000 >> (__builtin_clzll(N));} // Driver Codeint main(){ long long n = 5; cout << highestPowerof2(n); return 0;} // This code is contributed by phasing17", "e": 13040, "s": 12569, "text": null }, { "code": null, "e": 13042, "s": 13040, "text": "4" }, { "code": null, "e": 13154, "s": 13042, "text": "Time Complexity : O(1) as counting leading zeroes can cause at most O(64) time complexity.Auxiliary Space: O(1)" }, { "code": null, "e": 13582, "s": 13154, "text": "Application Problem: Some people are standing in a queue. A selection process follows a rule where people standing on even positions are selected. Of the selected people a queue is formed and again out of these only people on even position are selected. This continues until we are left with one person. Find out the position of that person in the original queue. Print the position(original queue) of that person who is left. " }, { "code": null, "e": 13594, "s": 13582, "text": "Examples : " }, { "code": null, "e": 13892, "s": 13594, "text": "Input: n = 10\nOutput:8\nExplanation : \n1 2 3 4 5 6 7 8 9 10 ===>Given queue\n 2 4 6 8 10\n 4 8\n 8\n\nInput: n = 17\nInput: 16\nExplanation : \n1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 ===>Given queue\n 2 4 6 8 10 12 14 16\n 4 8 12 16\n 8 16\n 16" }, { "code": null, "e": 14382, "s": 13892, "text": "Related Article : Power of 2 greater than or equal to a given number.This article is contributed by Sahil Chhabra. 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": 14388, "s": 14382, "text": "jit_t" }, { "code": null, "e": 14401, "s": 14388, "text": "Mithun Kumar" }, { "code": null, "e": 14407, "s": 14401, "text": "ukasp" }, { "code": null, "e": 14419, "s": 14407, "text": "AmulyaSahoo" }, { "code": null, "e": 14434, "s": 14419, "text": "chinmoy1997pal" }, { "code": null, "e": 14449, "s": 14434, "text": "mohit kumar 29" }, { "code": null, "e": 14467, "s": 14449, "text": "divyeshrabadiya07" }, { "code": null, "e": 14479, "s": 14467, "text": "29AjayKumar" }, { "code": null, "e": 14495, "s": 14479, "text": "sonirudrakshi99" }, { "code": null, "e": 14503, "s": 14495, "text": "rag2127" }, { "code": null, "e": 14524, "s": 14503, "text": "avanitrachhadiya2155" }, { "code": null, "e": 14536, "s": 14524, "text": "umadevi9616" }, { "code": null, "e": 14550, "s": 14536, "text": "divyesh072019" }, { "code": null, "e": 14560, "s": 14550, "text": "phasing17" }, { "code": null, "e": 14572, "s": 14560, "text": "krisania804" }, { "code": null, "e": 14585, "s": 14572, "text": "technophpfij" }, { "code": null, "e": 14592, "s": 14585, "text": "Amazon" }, { "code": null, "e": 14602, "s": 14592, "text": "Bit Magic" }, { "code": null, "e": 14615, "s": 14602, "text": "Mathematical" }, { "code": null, "e": 14625, "s": 14615, "text": "Recursion" }, { "code": null, "e": 14632, "s": 14625, "text": "Amazon" }, { "code": null, "e": 14645, "s": 14632, "text": "Mathematical" }, { "code": null, "e": 14655, "s": 14645, "text": "Recursion" }, { "code": null, "e": 14665, "s": 14655, "text": "Bit Magic" }, { "code": null, "e": 14763, "s": 14665, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 14793, "s": 14763, "text": "Little and Big Endian Mystery" }, { "code": null, "e": 14831, "s": 14793, "text": "Bits manipulation (Important tactics)" }, { "code": null, "e": 14871, "s": 14831, "text": "Binary representation of a given number" }, { "code": null, "e": 14914, "s": 14871, "text": "Josephus problem | Set 1 (A O(n) Solution)" }, { "code": null, "e": 14990, "s": 14914, "text": "Divide two integers without using multiplication, division and mod operator" }, { "code": null, "e": 15020, "s": 14990, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 15063, "s": 15020, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 15123, "s": 15063, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 15138, "s": 15123, "text": "C++ Data Types" } ]
JWT Authentication with Node.js
07 Oct, 2021 JSON Web Token is an open standard for securely transferring data within parties using a JSON object. JWT is used for stateless authentication mechanisms for users and providers, this means maintaining session is on the client-side instead of storing sessions on the server. Here, we will implement the JWT authentication system in NodeJs. Modules Required: NodeJs: NodeJs for backend dotenv: For handling configuration data npm install dotenv ExpressJS: ExpressJS for Handling routes. jsonwebtoken module: npm install jsonwebtoken All Steps:Create our project:To create a Node project, npm init -y is used in the folder in which the user wants to create a project. The npm command line will ask a number of questions like name, license, scripts, description, author, keywords, version, main file, etc. After npm is done creating the project, a package.json file will be visible in the project folder as proof that the project has been initialized.npm init -yInstall modulesAfter creating the project, next step is to incorporate the packages and modules to be used in the Node Project. To install packages and modules in the project use the following syntax:npm install express dotenv jsonwebtokenCreate our ServerImporting all the dependencies and creating a server using express.jsJavascriptJavascriptconst express = require('express');const dotenv = require('dotenv');const jwt = require('jsonwebtoken'); const app = express(); // Set up Global configuration accessdotenv.config(); let PORT = process.env.PORT || 5000;app.listen(PORT, () => { console.log(`Server is up and running on ${PORT} ...`);});Create Configuration File (.env)This files contains those variables that we need to pass to our application’s environment.JavascriptJavascriptPORT = 5000 JWT_SECRET_KEY = gfg_jwt_secret_key TOKEN_HEADER_KEY = gfg_token_header_keyCreate Route for Generating JWTCreating a ‘post’ request that sends the JWT token in the response.JavascriptJavascriptapp.post("/user/generateToken", (req, res) => { // Validate User Here // Then generate JWT Token let jwtSecretKey = process.env.JWT_SECRET_KEY; let data = { time: Date(), userId: 12, } const token = jwt.sign(data, jwtSecretKey); res.send(token);});Create Route for Validating JWTCreating a ‘get’ request that contains the JWT token in the header and sends verification status as a response.JavascriptJavascriptapp.get("/user/validateToken", (req, res) => { // Tokens are generally passed in the header of the request // Due to security reasons. let tokenHeaderKey = process.env.TOKEN_HEADER_KEY; let jwtSecretKey = process.env.JWT_SECRET_KEY; try { const token = req.header(tokenHeaderKey); const verified = jwt.verify(token, jwtSecretKey); if(verified){ return res.send("Successfully Verified"); }else{ // Access Denied return res.status(401).send(error); } } catch (error) { // Access Denied return res.status(401).send(error); }});Run Servernode index.jsFull index.js FileJavascriptJavascriptconst express = require('express');const dotenv = require('dotenv');const jwt = require('jsonwebtoken'); const app = express(); // Set up Global configuration accessdotenv.config(); let PORT = process.env.PORT || 5000;app.listen(PORT, () => { console.log(`Server is up and running on ${PORT} ...`);}); // Main Code Here //// Generating JWTapp.post("/user/generateToken", (req, res) => { // Validate User Here // Then generate JWT Token let jwtSecretKey = process.env.JWT_SECRET_KEY; let data = { time: Date(), userId: 12, } const token = jwt.sign(data, jwtSecretKey); res.send(token);}); // Verification of JWTapp.get("/user/validateToken", (req, res) => { // Tokens are generally passed in header of request // Due to security reasons. let tokenHeaderKey = process.env.TOKEN_HEADER_KEY; let jwtSecretKey = process.env.JWT_SECRET_KEY; try { const token = req.header(tokenHeaderKey); const verified = jwt.verify(token, jwtSecretKey); if(verified){ return res.send("Successfully Verified"); }else{ // Access Denied return res.status(401).send(error); } } catch (error) { // Access Denied return res.status(401).send(error); }});Send Requests and Get OutputOutput:POST RequestPOST ResponseeyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0aW1lIjoiTW9uIEphbiAxOCAyMDIxIDE2OjM2OjU3IEdNVCswNTMwIChJbmRpYSBTdGFuZGFyZCBU aW1lKSIsInVzZXJJZCI6MTIsImlhdCI6MTYxMDk2ODAxN30.QmWFjXhP6YtbzDAHlcE7mDMyXIdnTv1c9xOBCakNZ94GET RequestGET Request HeaderGET ResponseSuccessfully Verified All Steps: Create our project:To create a Node project, npm init -y is used in the folder in which the user wants to create a project. The npm command line will ask a number of questions like name, license, scripts, description, author, keywords, version, main file, etc. After npm is done creating the project, a package.json file will be visible in the project folder as proof that the project has been initialized.npm init -y Create our project: To create a Node project, npm init -y is used in the folder in which the user wants to create a project. The npm command line will ask a number of questions like name, license, scripts, description, author, keywords, version, main file, etc. After npm is done creating the project, a package.json file will be visible in the project folder as proof that the project has been initialized. npm init -y Install modulesAfter creating the project, next step is to incorporate the packages and modules to be used in the Node Project. To install packages and modules in the project use the following syntax:npm install express dotenv jsonwebtoken Install modules After creating the project, next step is to incorporate the packages and modules to be used in the Node Project. To install packages and modules in the project use the following syntax: npm install express dotenv jsonwebtoken Create our ServerImporting all the dependencies and creating a server using express.jsJavascriptJavascriptconst express = require('express');const dotenv = require('dotenv');const jwt = require('jsonwebtoken'); const app = express(); // Set up Global configuration accessdotenv.config(); let PORT = process.env.PORT || 5000;app.listen(PORT, () => { console.log(`Server is up and running on ${PORT} ...`);}); Create our Server Importing all the dependencies and creating a server using express.js Javascript const express = require('express');const dotenv = require('dotenv');const jwt = require('jsonwebtoken'); const app = express(); // Set up Global configuration accessdotenv.config(); let PORT = process.env.PORT || 5000;app.listen(PORT, () => { console.log(`Server is up and running on ${PORT} ...`);}); Create Configuration File (.env)This files contains those variables that we need to pass to our application’s environment.JavascriptJavascriptPORT = 5000 JWT_SECRET_KEY = gfg_jwt_secret_key TOKEN_HEADER_KEY = gfg_token_header_key Create Configuration File (.env) This files contains those variables that we need to pass to our application’s environment. Javascript PORT = 5000 JWT_SECRET_KEY = gfg_jwt_secret_key TOKEN_HEADER_KEY = gfg_token_header_key Create Route for Generating JWTCreating a ‘post’ request that sends the JWT token in the response.JavascriptJavascriptapp.post("/user/generateToken", (req, res) => { // Validate User Here // Then generate JWT Token let jwtSecretKey = process.env.JWT_SECRET_KEY; let data = { time: Date(), userId: 12, } const token = jwt.sign(data, jwtSecretKey); res.send(token);}); Create Route for Generating JWT Creating a ‘post’ request that sends the JWT token in the response. Javascript app.post("/user/generateToken", (req, res) => { // Validate User Here // Then generate JWT Token let jwtSecretKey = process.env.JWT_SECRET_KEY; let data = { time: Date(), userId: 12, } const token = jwt.sign(data, jwtSecretKey); res.send(token);}); Create Route for Validating JWTCreating a ‘get’ request that contains the JWT token in the header and sends verification status as a response.JavascriptJavascriptapp.get("/user/validateToken", (req, res) => { // Tokens are generally passed in the header of the request // Due to security reasons. let tokenHeaderKey = process.env.TOKEN_HEADER_KEY; let jwtSecretKey = process.env.JWT_SECRET_KEY; try { const token = req.header(tokenHeaderKey); const verified = jwt.verify(token, jwtSecretKey); if(verified){ return res.send("Successfully Verified"); }else{ // Access Denied return res.status(401).send(error); } } catch (error) { // Access Denied return res.status(401).send(error); }}); Create Route for Validating JWT Creating a ‘get’ request that contains the JWT token in the header and sends verification status as a response. Javascript app.get("/user/validateToken", (req, res) => { // Tokens are generally passed in the header of the request // Due to security reasons. let tokenHeaderKey = process.env.TOKEN_HEADER_KEY; let jwtSecretKey = process.env.JWT_SECRET_KEY; try { const token = req.header(tokenHeaderKey); const verified = jwt.verify(token, jwtSecretKey); if(verified){ return res.send("Successfully Verified"); }else{ // Access Denied return res.status(401).send(error); } } catch (error) { // Access Denied return res.status(401).send(error); }}); Run Servernode index.jsFull index.js FileJavascriptJavascriptconst express = require('express');const dotenv = require('dotenv');const jwt = require('jsonwebtoken'); const app = express(); // Set up Global configuration accessdotenv.config(); let PORT = process.env.PORT || 5000;app.listen(PORT, () => { console.log(`Server is up and running on ${PORT} ...`);}); // Main Code Here //// Generating JWTapp.post("/user/generateToken", (req, res) => { // Validate User Here // Then generate JWT Token let jwtSecretKey = process.env.JWT_SECRET_KEY; let data = { time: Date(), userId: 12, } const token = jwt.sign(data, jwtSecretKey); res.send(token);}); // Verification of JWTapp.get("/user/validateToken", (req, res) => { // Tokens are generally passed in header of request // Due to security reasons. let tokenHeaderKey = process.env.TOKEN_HEADER_KEY; let jwtSecretKey = process.env.JWT_SECRET_KEY; try { const token = req.header(tokenHeaderKey); const verified = jwt.verify(token, jwtSecretKey); if(verified){ return res.send("Successfully Verified"); }else{ // Access Denied return res.status(401).send(error); } } catch (error) { // Access Denied return res.status(401).send(error); }}); Run Server node index.js Full index.js File Javascript const express = require('express');const dotenv = require('dotenv');const jwt = require('jsonwebtoken'); const app = express(); // Set up Global configuration accessdotenv.config(); let PORT = process.env.PORT || 5000;app.listen(PORT, () => { console.log(`Server is up and running on ${PORT} ...`);}); // Main Code Here //// Generating JWTapp.post("/user/generateToken", (req, res) => { // Validate User Here // Then generate JWT Token let jwtSecretKey = process.env.JWT_SECRET_KEY; let data = { time: Date(), userId: 12, } const token = jwt.sign(data, jwtSecretKey); res.send(token);}); // Verification of JWTapp.get("/user/validateToken", (req, res) => { // Tokens are generally passed in header of request // Due to security reasons. let tokenHeaderKey = process.env.TOKEN_HEADER_KEY; let jwtSecretKey = process.env.JWT_SECRET_KEY; try { const token = req.header(tokenHeaderKey); const verified = jwt.verify(token, jwtSecretKey); if(verified){ return res.send("Successfully Verified"); }else{ // Access Denied return res.status(401).send(error); } } catch (error) { // Access Denied return res.status(401).send(error); }}); Send Requests and Get OutputOutput:POST RequestPOST ResponseeyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0aW1lIjoiTW9uIEphbiAxOCAyMDIxIDE2OjM2OjU3IEdNVCswNTMwIChJbmRpYSBTdGFuZGFyZCBU aW1lKSIsInVzZXJJZCI6MTIsImlhdCI6MTYxMDk2ODAxN30.QmWFjXhP6YtbzDAHlcE7mDMyXIdnTv1c9xOBCakNZ94GET RequestGET Request HeaderGET ResponseSuccessfully Verified Send Requests and Get Output Output: POST Request POST Response eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0aW1lIjoiTW9uIEphbiAxOCAyMDIxIDE2OjM2OjU3IEdNVCswNTMwIChJbmRpYSBTdGFuZGFyZCBU aW1lKSIsInVzZXJJZCI6MTIsImlhdCI6MTYxMDk2ODAxN30.QmWFjXhP6YtbzDAHlcE7mDMyXIdnTv1c9xOBCakNZ94 GET Request GET Request Header GET Response Successfully Verified NodeJS-Questions Technical Scripter 2020 Node.js Technical Scripter Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n07 Oct, 2021" }, { "code": null, "e": 394, "s": 54, "text": "JSON Web Token is an open standard for securely transferring data within parties using a JSON object. JWT is used for stateless authentication mechanisms for users and providers, this means maintaining session is on the client-side instead of storing sessions on the server. Here, we will implement the JWT authentication system in NodeJs." }, { "code": null, "e": 412, "s": 394, "text": "Modules Required:" }, { "code": null, "e": 439, "s": 412, "text": "NodeJs: NodeJs for backend" }, { "code": null, "e": 479, "s": 439, "text": "dotenv: For handling configuration data" }, { "code": null, "e": 498, "s": 479, "text": "npm install dotenv" }, { "code": null, "e": 540, "s": 498, "text": "ExpressJS: ExpressJS for Handling routes." }, { "code": null, "e": 561, "s": 540, "text": "jsonwebtoken module:" }, { "code": null, "e": 586, "s": 561, "text": "npm install jsonwebtoken" }, { "code": null, "e": 4772, "s": 586, "text": "All Steps:Create our project:To create a Node project, npm init -y is used in the folder in which the user wants to create a project. The npm command line will ask a number of questions like name, license, scripts, description, author, keywords, version, main file, etc. After npm is done creating the project, a package.json file will be visible in the project folder as proof that the project has been initialized.npm init -yInstall modulesAfter creating the project, next step is to incorporate the packages and modules to be used in the Node Project. To install packages and modules in the project use the following syntax:npm install express dotenv jsonwebtokenCreate our ServerImporting all the dependencies and creating a server using express.jsJavascriptJavascriptconst express = require('express');const dotenv = require('dotenv');const jwt = require('jsonwebtoken'); const app = express(); // Set up Global configuration accessdotenv.config(); let PORT = process.env.PORT || 5000;app.listen(PORT, () => { console.log(`Server is up and running on ${PORT} ...`);});Create Configuration File (.env)This files contains those variables that we need to pass to our application’s environment.JavascriptJavascriptPORT = 5000 JWT_SECRET_KEY = gfg_jwt_secret_key TOKEN_HEADER_KEY = gfg_token_header_keyCreate Route for Generating JWTCreating a ‘post’ request that sends the JWT token in the response.JavascriptJavascriptapp.post(\"/user/generateToken\", (req, res) => { // Validate User Here // Then generate JWT Token let jwtSecretKey = process.env.JWT_SECRET_KEY; let data = { time: Date(), userId: 12, } const token = jwt.sign(data, jwtSecretKey); res.send(token);});Create Route for Validating JWTCreating a ‘get’ request that contains the JWT token in the header and sends verification status as a response.JavascriptJavascriptapp.get(\"/user/validateToken\", (req, res) => { // Tokens are generally passed in the header of the request // Due to security reasons. let tokenHeaderKey = process.env.TOKEN_HEADER_KEY; let jwtSecretKey = process.env.JWT_SECRET_KEY; try { const token = req.header(tokenHeaderKey); const verified = jwt.verify(token, jwtSecretKey); if(verified){ return res.send(\"Successfully Verified\"); }else{ // Access Denied return res.status(401).send(error); } } catch (error) { // Access Denied return res.status(401).send(error); }});Run Servernode index.jsFull index.js FileJavascriptJavascriptconst express = require('express');const dotenv = require('dotenv');const jwt = require('jsonwebtoken'); const app = express(); // Set up Global configuration accessdotenv.config(); let PORT = process.env.PORT || 5000;app.listen(PORT, () => { console.log(`Server is up and running on ${PORT} ...`);}); // Main Code Here //// Generating JWTapp.post(\"/user/generateToken\", (req, res) => { // Validate User Here // Then generate JWT Token let jwtSecretKey = process.env.JWT_SECRET_KEY; let data = { time: Date(), userId: 12, } const token = jwt.sign(data, jwtSecretKey); res.send(token);}); // Verification of JWTapp.get(\"/user/validateToken\", (req, res) => { // Tokens are generally passed in header of request // Due to security reasons. let tokenHeaderKey = process.env.TOKEN_HEADER_KEY; let jwtSecretKey = process.env.JWT_SECRET_KEY; try { const token = req.header(tokenHeaderKey); const verified = jwt.verify(token, jwtSecretKey); if(verified){ return res.send(\"Successfully Verified\"); }else{ // Access Denied return res.status(401).send(error); } } catch (error) { // Access Denied return res.status(401).send(error); }});Send Requests and Get OutputOutput:POST RequestPOST ResponseeyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0aW1lIjoiTW9uIEphbiAxOCAyMDIxIDE2OjM2OjU3IEdNVCswNTMwIChJbmRpYSBTdGFuZGFyZCBU\naW1lKSIsInVzZXJJZCI6MTIsImlhdCI6MTYxMDk2ODAxN30.QmWFjXhP6YtbzDAHlcE7mDMyXIdnTv1c9xOBCakNZ94GET RequestGET Request HeaderGET ResponseSuccessfully Verified" }, { "code": null, "e": 4783, "s": 4772, "text": "All Steps:" }, { "code": null, "e": 5201, "s": 4783, "text": "Create our project:To create a Node project, npm init -y is used in the folder in which the user wants to create a project. The npm command line will ask a number of questions like name, license, scripts, description, author, keywords, version, main file, etc. After npm is done creating the project, a package.json file will be visible in the project folder as proof that the project has been initialized.npm init -y" }, { "code": null, "e": 5221, "s": 5201, "text": "Create our project:" }, { "code": null, "e": 5609, "s": 5221, "text": "To create a Node project, npm init -y is used in the folder in which the user wants to create a project. The npm command line will ask a number of questions like name, license, scripts, description, author, keywords, version, main file, etc. After npm is done creating the project, a package.json file will be visible in the project folder as proof that the project has been initialized." }, { "code": null, "e": 5621, "s": 5609, "text": "npm init -y" }, { "code": null, "e": 5861, "s": 5621, "text": "Install modulesAfter creating the project, next step is to incorporate the packages and modules to be used in the Node Project. To install packages and modules in the project use the following syntax:npm install express dotenv jsonwebtoken" }, { "code": null, "e": 5877, "s": 5861, "text": "Install modules" }, { "code": null, "e": 6063, "s": 5877, "text": "After creating the project, next step is to incorporate the packages and modules to be used in the Node Project. To install packages and modules in the project use the following syntax:" }, { "code": null, "e": 6103, "s": 6063, "text": "npm install express dotenv jsonwebtoken" }, { "code": null, "e": 6515, "s": 6103, "text": "Create our ServerImporting all the dependencies and creating a server using express.jsJavascriptJavascriptconst express = require('express');const dotenv = require('dotenv');const jwt = require('jsonwebtoken'); const app = express(); // Set up Global configuration accessdotenv.config(); let PORT = process.env.PORT || 5000;app.listen(PORT, () => { console.log(`Server is up and running on ${PORT} ...`);});" }, { "code": null, "e": 6533, "s": 6515, "text": "Create our Server" }, { "code": null, "e": 6603, "s": 6533, "text": "Importing all the dependencies and creating a server using express.js" }, { "code": null, "e": 6614, "s": 6603, "text": "Javascript" }, { "code": "const express = require('express');const dotenv = require('dotenv');const jwt = require('jsonwebtoken'); const app = express(); // Set up Global configuration accessdotenv.config(); let PORT = process.env.PORT || 5000;app.listen(PORT, () => { console.log(`Server is up and running on ${PORT} ...`);});", "e": 6920, "s": 6614, "text": null }, { "code": null, "e": 7152, "s": 6920, "text": "Create Configuration File (.env)This files contains those variables that we need to pass to our application’s environment.JavascriptJavascriptPORT = 5000 JWT_SECRET_KEY = gfg_jwt_secret_key TOKEN_HEADER_KEY = gfg_token_header_key" }, { "code": null, "e": 7185, "s": 7152, "text": "Create Configuration File (.env)" }, { "code": null, "e": 7276, "s": 7185, "text": "This files contains those variables that we need to pass to our application’s environment." }, { "code": null, "e": 7287, "s": 7276, "text": "Javascript" }, { "code": "PORT = 5000 JWT_SECRET_KEY = gfg_jwt_secret_key TOKEN_HEADER_KEY = gfg_token_header_key", "e": 7377, "s": 7287, "text": null }, { "code": null, "e": 7785, "s": 7377, "text": "Create Route for Generating JWTCreating a ‘post’ request that sends the JWT token in the response.JavascriptJavascriptapp.post(\"/user/generateToken\", (req, res) => { // Validate User Here // Then generate JWT Token let jwtSecretKey = process.env.JWT_SECRET_KEY; let data = { time: Date(), userId: 12, } const token = jwt.sign(data, jwtSecretKey); res.send(token);});" }, { "code": null, "e": 7817, "s": 7785, "text": "Create Route for Generating JWT" }, { "code": null, "e": 7885, "s": 7817, "text": "Creating a ‘post’ request that sends the JWT token in the response." }, { "code": null, "e": 7896, "s": 7885, "text": "Javascript" }, { "code": "app.post(\"/user/generateToken\", (req, res) => { // Validate User Here // Then generate JWT Token let jwtSecretKey = process.env.JWT_SECRET_KEY; let data = { time: Date(), userId: 12, } const token = jwt.sign(data, jwtSecretKey); res.send(token);});", "e": 8186, "s": 7896, "text": null }, { "code": null, "e": 8982, "s": 8186, "text": "Create Route for Validating JWTCreating a ‘get’ request that contains the JWT token in the header and sends verification status as a response.JavascriptJavascriptapp.get(\"/user/validateToken\", (req, res) => { // Tokens are generally passed in the header of the request // Due to security reasons. let tokenHeaderKey = process.env.TOKEN_HEADER_KEY; let jwtSecretKey = process.env.JWT_SECRET_KEY; try { const token = req.header(tokenHeaderKey); const verified = jwt.verify(token, jwtSecretKey); if(verified){ return res.send(\"Successfully Verified\"); }else{ // Access Denied return res.status(401).send(error); } } catch (error) { // Access Denied return res.status(401).send(error); }});" }, { "code": null, "e": 9014, "s": 8982, "text": "Create Route for Validating JWT" }, { "code": null, "e": 9126, "s": 9014, "text": "Creating a ‘get’ request that contains the JWT token in the header and sends verification status as a response." }, { "code": null, "e": 9137, "s": 9126, "text": "Javascript" }, { "code": "app.get(\"/user/validateToken\", (req, res) => { // Tokens are generally passed in the header of the request // Due to security reasons. let tokenHeaderKey = process.env.TOKEN_HEADER_KEY; let jwtSecretKey = process.env.JWT_SECRET_KEY; try { const token = req.header(tokenHeaderKey); const verified = jwt.verify(token, jwtSecretKey); if(verified){ return res.send(\"Successfully Verified\"); }else{ // Access Denied return res.status(401).send(error); } } catch (error) { // Access Denied return res.status(401).send(error); }});", "e": 9771, "s": 9137, "text": null }, { "code": null, "e": 11116, "s": 9771, "text": "Run Servernode index.jsFull index.js FileJavascriptJavascriptconst express = require('express');const dotenv = require('dotenv');const jwt = require('jsonwebtoken'); const app = express(); // Set up Global configuration accessdotenv.config(); let PORT = process.env.PORT || 5000;app.listen(PORT, () => { console.log(`Server is up and running on ${PORT} ...`);}); // Main Code Here //// Generating JWTapp.post(\"/user/generateToken\", (req, res) => { // Validate User Here // Then generate JWT Token let jwtSecretKey = process.env.JWT_SECRET_KEY; let data = { time: Date(), userId: 12, } const token = jwt.sign(data, jwtSecretKey); res.send(token);}); // Verification of JWTapp.get(\"/user/validateToken\", (req, res) => { // Tokens are generally passed in header of request // Due to security reasons. let tokenHeaderKey = process.env.TOKEN_HEADER_KEY; let jwtSecretKey = process.env.JWT_SECRET_KEY; try { const token = req.header(tokenHeaderKey); const verified = jwt.verify(token, jwtSecretKey); if(verified){ return res.send(\"Successfully Verified\"); }else{ // Access Denied return res.status(401).send(error); } } catch (error) { // Access Denied return res.status(401).send(error); }});" }, { "code": null, "e": 11127, "s": 11116, "text": "Run Server" }, { "code": null, "e": 11141, "s": 11127, "text": "node index.js" }, { "code": null, "e": 11160, "s": 11141, "text": "Full index.js File" }, { "code": null, "e": 11171, "s": 11160, "text": "Javascript" }, { "code": "const express = require('express');const dotenv = require('dotenv');const jwt = require('jsonwebtoken'); const app = express(); // Set up Global configuration accessdotenv.config(); let PORT = process.env.PORT || 5000;app.listen(PORT, () => { console.log(`Server is up and running on ${PORT} ...`);}); // Main Code Here //// Generating JWTapp.post(\"/user/generateToken\", (req, res) => { // Validate User Here // Then generate JWT Token let jwtSecretKey = process.env.JWT_SECRET_KEY; let data = { time: Date(), userId: 12, } const token = jwt.sign(data, jwtSecretKey); res.send(token);}); // Verification of JWTapp.get(\"/user/validateToken\", (req, res) => { // Tokens are generally passed in header of request // Due to security reasons. let tokenHeaderKey = process.env.TOKEN_HEADER_KEY; let jwtSecretKey = process.env.JWT_SECRET_KEY; try { const token = req.header(tokenHeaderKey); const verified = jwt.verify(token, jwtSecretKey); if(verified){ return res.send(\"Successfully Verified\"); }else{ // Access Denied return res.status(401).send(error); } } catch (error) { // Access Denied return res.status(401).send(error); }});", "e": 12455, "s": 11171, "text": null }, { "code": null, "e": 12787, "s": 12455, "text": "Send Requests and Get OutputOutput:POST RequestPOST ResponseeyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0aW1lIjoiTW9uIEphbiAxOCAyMDIxIDE2OjM2OjU3IEdNVCswNTMwIChJbmRpYSBTdGFuZGFyZCBU\naW1lKSIsInVzZXJJZCI6MTIsImlhdCI6MTYxMDk2ODAxN30.QmWFjXhP6YtbzDAHlcE7mDMyXIdnTv1c9xOBCakNZ94GET RequestGET Request HeaderGET ResponseSuccessfully Verified" }, { "code": null, "e": 12816, "s": 12787, "text": "Send Requests and Get Output" }, { "code": null, "e": 12824, "s": 12816, "text": "Output:" }, { "code": null, "e": 12837, "s": 12824, "text": "POST Request" }, { "code": null, "e": 12851, "s": 12837, "text": "POST Response" }, { "code": null, "e": 13061, "s": 12851, "text": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0aW1lIjoiTW9uIEphbiAxOCAyMDIxIDE2OjM2OjU3IEdNVCswNTMwIChJbmRpYSBTdGFuZGFyZCBU\naW1lKSIsInVzZXJJZCI6MTIsImlhdCI6MTYxMDk2ODAxN30.QmWFjXhP6YtbzDAHlcE7mDMyXIdnTv1c9xOBCakNZ94" }, { "code": null, "e": 13073, "s": 13061, "text": "GET Request" }, { "code": null, "e": 13092, "s": 13073, "text": "GET Request Header" }, { "code": null, "e": 13105, "s": 13092, "text": "GET Response" }, { "code": null, "e": 13127, "s": 13105, "text": "Successfully Verified" }, { "code": null, "e": 13144, "s": 13127, "text": "NodeJS-Questions" }, { "code": null, "e": 13168, "s": 13144, "text": "Technical Scripter 2020" }, { "code": null, "e": 13176, "s": 13168, "text": "Node.js" }, { "code": null, "e": 13195, "s": 13176, "text": "Technical Scripter" }, { "code": null, "e": 13212, "s": 13195, "text": "Web Technologies" } ]
How to Implement Forward DNS Look Up Cache?
22 Mar, 2017 We have discussed implementation of Reverse DNS Look Up Cache. Forward DNS look up is getting IP address for a given domain name typed in the web browser. The cache should do the following operations :1. Add a mapping from URL to IP address2. Find IP address for a given URL. There are a few changes from reverse DNS look up cache that we need to incorporate.1. Instead of [0-9] and (.) dot we need to take care of [A-Z], [a-z] and (.) dot. As most of the domain name contains only lowercase characters we can assume that there will be [a-z] and (.) 27 children for each trie node. 2. When we type www.google.in and google.in the browser takes us to the same page. So, we need to add a domain name into trie for the words after www(.). Similarly while searching for a domain name corresponding IP address remove the www(.) if the user has provided it. This is left as an exercise and for simplicity we have taken care of www. also. One solution is to use Hashing. In this post, a Trie based solution is discussed. One advantage of Trie based solutions is, worst case upper bound is O(1) for Trie, for hashing, the best possible average case time complexity is O(1). Also, with Trie we can implement prefix search (finding all IPs for a common prefix of URLs). The general disadvantage of Trie is large amount of memory requirement.The idea is to store URLs in Trie nodes and store the corresponding IP address in last or leaf node. Following is C style implementation in C++. // C based program to implement reverse DNS lookup#include<stdio.h>#include<stdlib.h>#include<string.h> // There are atmost 27 different chars in a valid URL// assuming URL consists [a-z] and (.)#define CHARS 27 // Maximum length of a valid URL#define MAX 100 // A utility function to find index of child for a given character 'c'int getIndex(char c){ return (c == '.') ? 26 : (c - 'a');} // A utility function to find character for a given child index.char getCharFromIndex(int i){ return (i == 26) ? '.' : ('a' + i);} // Trie Node.struct trieNode{ bool isLeaf; char *ipAdd; struct trieNode *child[CHARS];}; // Function to create a new trie node.struct trieNode *newTrieNode(void){ struct trieNode *newNode = new trieNode; newNode->isLeaf = false; newNode->ipAdd = NULL; for (int i = 0; i<CHARS; i++) newNode->child[i] = NULL; return newNode;} // This method inserts a URL and corresponding IP address// in the trie. The last node in Trie contains the ip address.void insert(struct trieNode *root, char *URL, char *ipAdd){ // Length of the URL int len = strlen(URL); struct trieNode *pCrawl = root; // Traversing over the length of the URL. for (int level = 0; level<len; level++) { // Get index of child node from current character // in URL[] Index must be from 0 to 26 where // 0 to 25 is used for alphabets and 26 for dot int index = getIndex(URL[level]); // Create a new child if not exist already if (!pCrawl->child[index]) pCrawl->child[index] = newTrieNode(); // Move to the child pCrawl = pCrawl->child[index]; } //Below needs to be carried out for the last node. //Save the corresponding ip address of the URL in the //last node of trie. pCrawl->isLeaf = true; pCrawl->ipAdd = new char[strlen(ipAdd) + 1]; strcpy(pCrawl->ipAdd, ipAdd);} // This function returns IP address if given URL is// present in DNS cache. Else returns NULLchar *searchDNSCache(struct trieNode *root, char *URL){ // Root node of trie. struct trieNode *pCrawl = root; int len = strlen(URL); // Traversal over the length of URL. for (int level = 0; level<len; level++) { int index = getIndex(URL[level]); if (!pCrawl->child[index]) return NULL; pCrawl = pCrawl->child[index]; } // If we find the last node for a given ip address, // print the ip address. if (pCrawl != NULL && pCrawl->isLeaf) return pCrawl->ipAdd; return NULL;} // Driver function.int main(){ char URL[][50] = { "www.samsung.com", "www.samsung.net", "www.google.in" }; char ipAdd[][MAX] = { "107.108.11.123", "107.109.123.255", "74.125.200.106" }; int n = sizeof(URL) / sizeof(URL[0]); struct trieNode *root = newTrieNode(); // Inserts all the domain name and their corresponding // ip address for (int i = 0; i<n; i++) insert(root, URL[i], ipAdd[i]); // If forward DNS look up succeeds print the url along // with the resolved ip address. char url[] = "www.samsung.com"; char *res_ip = searchDNSCache(root, url); if (res_ip != NULL) printf("Forward DNS look up resolved in cache:\n%s --> %s", url, res_ip); else printf("Forward DNS look up not resolved in cache "); return 0;} Output: Forward DNS look up resolved in cache: www.samsung.com --> 107.108.11.123 This article is contributed by Kumar Gautam. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Advanced Data Structure Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n22 Mar, 2017" }, { "code": null, "e": 209, "s": 54, "text": "We have discussed implementation of Reverse DNS Look Up Cache. Forward DNS look up is getting IP address for a given domain name typed in the web browser." }, { "code": null, "e": 330, "s": 209, "text": "The cache should do the following operations :1. Add a mapping from URL to IP address2. Find IP address for a given URL." }, { "code": null, "e": 636, "s": 330, "text": "There are a few changes from reverse DNS look up cache that we need to incorporate.1. Instead of [0-9] and (.) dot we need to take care of [A-Z], [a-z] and (.) dot. As most of the domain name contains only lowercase characters we can assume that there will be [a-z] and (.) 27 children for each trie node." }, { "code": null, "e": 906, "s": 636, "text": "2. When we type www.google.in and google.in the browser takes us to the same page. So, we need to add a domain name into trie for the words after www(.). Similarly while searching for a domain name corresponding IP address remove the www(.) if the user has provided it." }, { "code": null, "e": 986, "s": 906, "text": "This is left as an exercise and for simplicity we have taken care of www. also." }, { "code": null, "e": 1486, "s": 986, "text": "One solution is to use Hashing. In this post, a Trie based solution is discussed. One advantage of Trie based solutions is, worst case upper bound is O(1) for Trie, for hashing, the best possible average case time complexity is O(1). Also, with Trie we can implement prefix search (finding all IPs for a common prefix of URLs). The general disadvantage of Trie is large amount of memory requirement.The idea is to store URLs in Trie nodes and store the corresponding IP address in last or leaf node." }, { "code": null, "e": 1530, "s": 1486, "text": "Following is C style implementation in C++." }, { "code": "// C based program to implement reverse DNS lookup#include<stdio.h>#include<stdlib.h>#include<string.h> // There are atmost 27 different chars in a valid URL// assuming URL consists [a-z] and (.)#define CHARS 27 // Maximum length of a valid URL#define MAX 100 // A utility function to find index of child for a given character 'c'int getIndex(char c){ return (c == '.') ? 26 : (c - 'a');} // A utility function to find character for a given child index.char getCharFromIndex(int i){ return (i == 26) ? '.' : ('a' + i);} // Trie Node.struct trieNode{ bool isLeaf; char *ipAdd; struct trieNode *child[CHARS];}; // Function to create a new trie node.struct trieNode *newTrieNode(void){ struct trieNode *newNode = new trieNode; newNode->isLeaf = false; newNode->ipAdd = NULL; for (int i = 0; i<CHARS; i++) newNode->child[i] = NULL; return newNode;} // This method inserts a URL and corresponding IP address// in the trie. The last node in Trie contains the ip address.void insert(struct trieNode *root, char *URL, char *ipAdd){ // Length of the URL int len = strlen(URL); struct trieNode *pCrawl = root; // Traversing over the length of the URL. for (int level = 0; level<len; level++) { // Get index of child node from current character // in URL[] Index must be from 0 to 26 where // 0 to 25 is used for alphabets and 26 for dot int index = getIndex(URL[level]); // Create a new child if not exist already if (!pCrawl->child[index]) pCrawl->child[index] = newTrieNode(); // Move to the child pCrawl = pCrawl->child[index]; } //Below needs to be carried out for the last node. //Save the corresponding ip address of the URL in the //last node of trie. pCrawl->isLeaf = true; pCrawl->ipAdd = new char[strlen(ipAdd) + 1]; strcpy(pCrawl->ipAdd, ipAdd);} // This function returns IP address if given URL is// present in DNS cache. Else returns NULLchar *searchDNSCache(struct trieNode *root, char *URL){ // Root node of trie. struct trieNode *pCrawl = root; int len = strlen(URL); // Traversal over the length of URL. for (int level = 0; level<len; level++) { int index = getIndex(URL[level]); if (!pCrawl->child[index]) return NULL; pCrawl = pCrawl->child[index]; } // If we find the last node for a given ip address, // print the ip address. if (pCrawl != NULL && pCrawl->isLeaf) return pCrawl->ipAdd; return NULL;} // Driver function.int main(){ char URL[][50] = { \"www.samsung.com\", \"www.samsung.net\", \"www.google.in\" }; char ipAdd[][MAX] = { \"107.108.11.123\", \"107.109.123.255\", \"74.125.200.106\" }; int n = sizeof(URL) / sizeof(URL[0]); struct trieNode *root = newTrieNode(); // Inserts all the domain name and their corresponding // ip address for (int i = 0; i<n; i++) insert(root, URL[i], ipAdd[i]); // If forward DNS look up succeeds print the url along // with the resolved ip address. char url[] = \"www.samsung.com\"; char *res_ip = searchDNSCache(root, url); if (res_ip != NULL) printf(\"Forward DNS look up resolved in cache:\\n%s --> %s\", url, res_ip); else printf(\"Forward DNS look up not resolved in cache \"); return 0;}", "e": 4971, "s": 1530, "text": null }, { "code": null, "e": 4979, "s": 4971, "text": "Output:" }, { "code": null, "e": 5053, "s": 4979, "text": "Forward DNS look up resolved in cache:\nwww.samsung.com --> 107.108.11.123" }, { "code": null, "e": 5223, "s": 5053, "text": "This article is contributed by Kumar Gautam. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 5247, "s": 5223, "text": "Advanced Data Structure" } ]
Python | Pandas Series.dtype
28 Jan, 2019 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index. Pandas Series.dtype attribute returns the data type of the underlying data for the given Series object. Syntax: Series.dtype Parameter : None Returns : data type Example #1: Use Series.dtype attribute to find the data type of the underlying data for the given Series object. # importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon']) # Creating the row axis labelssr.index = ['City 1', 'City 2', 'City 3', 'City 4'] # Print the seriesprint(sr) Output : Now we will use Series.dtype attribute to find the data type of the given Series object. # return the data typesr.dtype Output : As we can see in the output, the Series.dtype attribute has returned ‘O’ indicating the data type of the underlying data is object type. Example #2 : Use Series.dtype attribute to find the data type of the underlying data for the given Series object. # importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([1000, 5000, 1500, 8222]) # Print the seriesprint(sr) Output : Now we will use Series.dtype attribute to find the data type of the given Series object. # return the data typesr.dtype Output :As we can see in the output, the Series.dtype attribute has returned ‘int64’ indicating the data type of the underlying data is of int64 type. Python pandas-series Python pandas-series-methods Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Jan, 2019" }, { "code": null, "e": 242, "s": 28, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier." }, { "code": null, "e": 499, "s": 242, "text": "Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index." }, { "code": null, "e": 603, "s": 499, "text": "Pandas Series.dtype attribute returns the data type of the underlying data for the given Series object." }, { "code": null, "e": 624, "s": 603, "text": "Syntax: Series.dtype" }, { "code": null, "e": 641, "s": 624, "text": "Parameter : None" }, { "code": null, "e": 661, "s": 641, "text": "Returns : data type" }, { "code": null, "e": 774, "s": 661, "text": "Example #1: Use Series.dtype attribute to find the data type of the underlying data for the given Series object." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon']) # Creating the row axis labelssr.index = ['City 1', 'City 2', 'City 3', 'City 4'] # Print the seriesprint(sr)", "e": 1014, "s": 774, "text": null }, { "code": null, "e": 1023, "s": 1014, "text": "Output :" }, { "code": null, "e": 1112, "s": 1023, "text": "Now we will use Series.dtype attribute to find the data type of the given Series object." }, { "code": "# return the data typesr.dtype", "e": 1143, "s": 1112, "text": null }, { "code": null, "e": 1152, "s": 1143, "text": "Output :" }, { "code": null, "e": 1289, "s": 1152, "text": "As we can see in the output, the Series.dtype attribute has returned ‘O’ indicating the data type of the underlying data is object type." }, { "code": null, "e": 1403, "s": 1289, "text": "Example #2 : Use Series.dtype attribute to find the data type of the underlying data for the given Series object." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([1000, 5000, 1500, 8222]) # Print the seriesprint(sr)", "e": 1539, "s": 1403, "text": null }, { "code": null, "e": 1548, "s": 1539, "text": "Output :" }, { "code": null, "e": 1637, "s": 1548, "text": "Now we will use Series.dtype attribute to find the data type of the given Series object." }, { "code": "# return the data typesr.dtype", "e": 1668, "s": 1637, "text": null }, { "code": null, "e": 1819, "s": 1668, "text": "Output :As we can see in the output, the Series.dtype attribute has returned ‘int64’ indicating the data type of the underlying data is of int64 type." }, { "code": null, "e": 1840, "s": 1819, "text": "Python pandas-series" }, { "code": null, "e": 1869, "s": 1840, "text": "Python pandas-series-methods" }, { "code": null, "e": 1883, "s": 1869, "text": "Python-pandas" }, { "code": null, "e": 1890, "s": 1883, "text": "Python" } ]
JSP - Filters
In this chapter, we will discuss Filters in JSP. Servlet and JSP Filters are Java classes that can be used in Servlet and JSP Programming for the following purposes − To intercept requests from a client before they access a resource at back end. To intercept requests from a client before they access a resource at back end. To manipulate responses from server before they are sent back to the client. To manipulate responses from server before they are sent back to the client. There are various types of filters suggested by the specifications − Authentication Filters Data compression Filters Encryption Filters Filters that trigger resource access events Image Conversion Filters Logging and Auditing Filters MIME-TYPE Chain Filters Tokenizing Filters XSL/T Filters That Transform XML Content Filters are deployed in the deployment descriptor file web.xml and then map to either servlet or JSP names or URL patterns in your application's deployment descriptor. The deployment descriptor file web.xml can be found in <Tomcat-installation-directory>\conf directory. When the JSP container starts up your web application, it creates an instance of each filter that you have declared in the deployment descriptor. The filters execute in the order that they are declared in the deployment descriptor. A filter is simply a Java class that implements the javax.servlet.Filter interface. The javax.servlet.Filter interface defines three methods − public void doFilter (ServletRequest, ServletResponse, FilterChain) This method is called by the container each time a request/response pair is passed through the chain due to a client request for a resource at the end of the chain. public void init(FilterConfig filterConfig) This method is called by the web container to indicate to a filter that it is being placed into service. public void destroy() This method is called by the web container to indicate to a filter that it is being taken out of service. Following example shows how to print the client’s IP address and the current date time, each time it would access any JSP file. This example will give you a basic understanding of the JSP Filter, but you can write more sophisticated filter applications using the same concept − // Import required java libraries import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.*; // Implements Filter class public class LogFilter implements Filter { public void init(FilterConfig config) throws ServletException { // Get init parameter String testParam = config.getInitParameter("test-param"); //Print the init parameter System.out.println("Test Param: " + testParam); } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws java.io.IOException, ServletException { // Get the IP address of client machine. String ipAddress = request.getRemoteAddr(); // Log the IP address and current timestamp. System.out.println("IP "+ ipAddress + ", Time "+ new Date().toString()); // Pass request back down the filter chain chain.doFilter(request,response); } public void destroy( ) { /* Called before the Filter instance is removed from service by the web container*/ } } Compile LogFilter.java in the usual way and put your LogFilter.class file in <Tomcat-installation-directory>/webapps/ROOT/WEB-INF/classes. Filters are defined and then mapped to a URL or JSP file name, in much the same way as Servlet is defined and then mapped to a URL pattern in web.xml file. Create the following entry for filter tag in the deployment descriptor file web.xml <filter> <filter-name>LogFilter</filter-name> <filter-class>LogFilter</filter-class> <init-param> <param-name>test-param</param-name> <param-value>Initialization Paramter</param-value> </init-param> </filter> <filter-mapping> <filter-name>LogFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> The above filter will apply to all the servlets and JSP because we specified /* in our configuration. You can specify a particular servlet or the JSP path if you want to apply filter on few servlets or JSP only. Now try to call any servlet or JSP and you will see generated log in you web server log. You can use Log4J logger to log above log in a separate file. Your web application may define several different filters with a specific purpose. Consider, you define two filters AuthenFilter and LogFilter. Rest of the process will remain as explained above except you need to create a different mapping as mentioned below − <filter> <filter-name>LogFilter</filter-name> <filter-class>LogFilter</filter-class> <init-param> <param-name>test-param</param-name> <param-value>Initialization Paramter</param-value> </init-param> </filter> <filter> <filter-name>AuthenFilter</filter-name> <filter-class>AuthenFilter</filter-class> <init-param> <param-name>test-param</param-name> <param-value>Initialization Paramter</param-value> </init-param> </filter> <filter-mapping> <filter-name>LogFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <filter-mapping> <filter-name>AuthenFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> The order of filter-mapping elements in web.xml determines the order in which the web container applies the filter to the servlet or JSP. To reverse the order of the filter, you just need to reverse the filter-mapping elements in the web.xml file. For example, the above example will apply the LogFilter first and then it will apply AuthenFilter to any servlet or JSP; the following example will reverse the order − <filter-mapping> <filter-name>AuthenFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <filter-mapping> <filter-name>LogFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> 108 Lectures 11 hours Chaand Sheikh 517 Lectures 57 hours Chaand Sheikh 41 Lectures 4.5 hours Karthikeya T 42 Lectures 5.5 hours TELCOMA Global 15 Lectures 3 hours TELCOMA Global 44 Lectures 15 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 2406, "s": 2239, "text": "In this chapter, we will discuss Filters in JSP. Servlet and JSP Filters are Java classes that can be used in Servlet and JSP Programming for the following purposes −" }, { "code": null, "e": 2485, "s": 2406, "text": "To intercept requests from a client before they access a resource at back end." }, { "code": null, "e": 2564, "s": 2485, "text": "To intercept requests from a client before they access a resource at back end." }, { "code": null, "e": 2641, "s": 2564, "text": "To manipulate responses from server before they are sent back to the client." }, { "code": null, "e": 2718, "s": 2641, "text": "To manipulate responses from server before they are sent back to the client." }, { "code": null, "e": 2787, "s": 2718, "text": "There are various types of filters suggested by the specifications −" }, { "code": null, "e": 2810, "s": 2787, "text": "Authentication Filters" }, { "code": null, "e": 2835, "s": 2810, "text": "Data compression Filters" }, { "code": null, "e": 2854, "s": 2835, "text": "Encryption Filters" }, { "code": null, "e": 2898, "s": 2854, "text": "Filters that trigger resource access events" }, { "code": null, "e": 2923, "s": 2898, "text": "Image Conversion Filters" }, { "code": null, "e": 2952, "s": 2923, "text": "Logging and Auditing Filters" }, { "code": null, "e": 2976, "s": 2952, "text": "MIME-TYPE Chain Filters" }, { "code": null, "e": 2995, "s": 2976, "text": "Tokenizing Filters" }, { "code": null, "e": 3036, "s": 2995, "text": "XSL/T Filters That Transform XML Content" }, { "code": null, "e": 3307, "s": 3036, "text": "Filters are deployed in the deployment descriptor file web.xml and then map to either servlet or JSP names or URL patterns in your application's deployment descriptor. The deployment descriptor file web.xml can be found in <Tomcat-installation-directory>\\conf directory." }, { "code": null, "e": 3539, "s": 3307, "text": "When the JSP container starts up your web application, it creates an instance of each filter that you have declared in the deployment descriptor. The filters execute in the order that they are declared in the deployment descriptor." }, { "code": null, "e": 3682, "s": 3539, "text": "A filter is simply a Java class that implements the javax.servlet.Filter interface. The javax.servlet.Filter interface defines three methods −" }, { "code": null, "e": 3750, "s": 3682, "text": "public void doFilter (ServletRequest, ServletResponse, FilterChain)" }, { "code": null, "e": 3915, "s": 3750, "text": "This method is called by the container each time a request/response pair is passed through the chain due to a client request for a resource at the end of the chain." }, { "code": null, "e": 3959, "s": 3915, "text": "public void init(FilterConfig filterConfig)" }, { "code": null, "e": 4064, "s": 3959, "text": "This method is called by the web container to indicate to a filter that it is being placed into service." }, { "code": null, "e": 4086, "s": 4064, "text": "public void destroy()" }, { "code": null, "e": 4192, "s": 4086, "text": "This method is called by the web container to indicate to a filter that it is being taken out of service." }, { "code": null, "e": 4470, "s": 4192, "text": "Following example shows how to print the client’s IP address and the current date time, each time it would access any JSP file. This example will give you a basic understanding of the JSP Filter, but you can write more sophisticated filter applications using the same concept −" }, { "code": null, "e": 5551, "s": 4470, "text": "// Import required java libraries\nimport java.io.*;\nimport javax.servlet.*;\nimport javax.servlet.http.*;\nimport java.util.*;\n \n// Implements Filter class\npublic class LogFilter implements Filter {\n public void init(FilterConfig config) throws ServletException {\n // Get init parameter \n String testParam = config.getInitParameter(\"test-param\"); \n \n //Print the init parameter \n System.out.println(\"Test Param: \" + testParam); \n }\n public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) \n throws java.io.IOException, ServletException {\n \n // Get the IP address of client machine. \n String ipAddress = request.getRemoteAddr();\n \n // Log the IP address and current timestamp.\n System.out.println(\"IP \"+ ipAddress + \", Time \"+ new Date().toString());\n \n // Pass request back down the filter chain\n chain.doFilter(request,response);\n }\n public void destroy( ) {\n /* Called before the Filter instance is removed \n from service by the web container*/\n }\n}" }, { "code": null, "e": 5690, "s": 5551, "text": "Compile LogFilter.java in the usual way and put your LogFilter.class file in <Tomcat-installation-directory>/webapps/ROOT/WEB-INF/classes." }, { "code": null, "e": 5930, "s": 5690, "text": "Filters are defined and then mapped to a URL or JSP file name, in much the same way as Servlet is defined and then mapped to a URL pattern in web.xml file. Create the following entry for filter tag in the deployment descriptor file web.xml" }, { "code": null, "e": 6276, "s": 5930, "text": "<filter>\n <filter-name>LogFilter</filter-name>\n <filter-class>LogFilter</filter-class>\n \n <init-param>\n <param-name>test-param</param-name>\n <param-value>Initialization Paramter</param-value>\n </init-param>\n</filter>\n\n<filter-mapping>\n <filter-name>LogFilter</filter-name>\n <url-pattern>/*</url-pattern>\n</filter-mapping>" }, { "code": null, "e": 6488, "s": 6276, "text": "The above filter will apply to all the servlets and JSP because we specified /* in our configuration. You can specify a particular servlet or the JSP path if you want to apply filter on few servlets or JSP only." }, { "code": null, "e": 6639, "s": 6488, "text": "Now try to call any servlet or JSP and you will see generated log in you web server log. You can use Log4J logger to log above log in a separate file." }, { "code": null, "e": 6901, "s": 6639, "text": "Your web application may define several different filters with a specific purpose. Consider, you define two filters AuthenFilter and LogFilter. Rest of the process will remain as explained above except you need to create a different mapping as mentioned below −" }, { "code": null, "e": 7602, "s": 6901, "text": "<filter>\n <filter-name>LogFilter</filter-name>\n <filter-class>LogFilter</filter-class>\n \n <init-param>\n <param-name>test-param</param-name>\n <param-value>Initialization Paramter</param-value>\n </init-param>\n</filter>\n \n<filter>\n <filter-name>AuthenFilter</filter-name>\n <filter-class>AuthenFilter</filter-class>\n <init-param>\n <param-name>test-param</param-name>\n <param-value>Initialization Paramter</param-value>\n </init-param>\n</filter>\n \n<filter-mapping>\n <filter-name>LogFilter</filter-name>\n <url-pattern>/*</url-pattern>\n</filter-mapping>\n \n<filter-mapping>\n <filter-name>AuthenFilter</filter-name>\n <url-pattern>/*</url-pattern>\n</filter-mapping>" }, { "code": null, "e": 7850, "s": 7602, "text": "The order of filter-mapping elements in web.xml determines the order in which the web container applies the filter to the servlet or JSP. To reverse the order of the filter, you just need to reverse the filter-mapping elements in the web.xml file." }, { "code": null, "e": 8018, "s": 7850, "text": "For example, the above example will apply the LogFilter first and then it will apply AuthenFilter to any servlet or JSP; the following example will reverse the order −" }, { "code": null, "e": 8239, "s": 8018, "text": "<filter-mapping>\n <filter-name>AuthenFilter</filter-name>\n <url-pattern>/*</url-pattern>\n</filter-mapping>\n \n<filter-mapping>\n <filter-name>LogFilter</filter-name>\n <url-pattern>/*</url-pattern>\n</filter-mapping>" }, { "code": null, "e": 8274, "s": 8239, "text": "\n 108 Lectures \n 11 hours \n" }, { "code": null, "e": 8289, "s": 8274, "text": " Chaand Sheikh" }, { "code": null, "e": 8324, "s": 8289, "text": "\n 517 Lectures \n 57 hours \n" }, { "code": null, "e": 8339, "s": 8324, "text": " Chaand Sheikh" }, { "code": null, "e": 8374, "s": 8339, "text": "\n 41 Lectures \n 4.5 hours \n" }, { "code": null, "e": 8388, "s": 8374, "text": " Karthikeya T" }, { "code": null, "e": 8423, "s": 8388, "text": "\n 42 Lectures \n 5.5 hours \n" }, { "code": null, "e": 8439, "s": 8423, "text": " TELCOMA Global" }, { "code": null, "e": 8472, "s": 8439, "text": "\n 15 Lectures \n 3 hours \n" }, { "code": null, "e": 8488, "s": 8472, "text": " TELCOMA Global" }, { "code": null, "e": 8522, "s": 8488, "text": "\n 44 Lectures \n 15 hours \n" }, { "code": null, "e": 8530, "s": 8522, "text": " Uplatz" }, { "code": null, "e": 8537, "s": 8530, "text": " Print" }, { "code": null, "e": 8548, "s": 8537, "text": " Add Notes" } ]
How to set dropdown and search box in same line using Bootstrap ? - GeeksforGeeks
21 Dec, 2020 A dropdown menu is a type of menu, by using the dropdown menu user can select something from the given predefined set. It is a toggleable menu, which means it appears when the user clicks on the menu. A search box is a type of box in which you can write the string which you want to search. The main aim is to align the dropdown menu and search box in a straight line. Example 1: We will create a navigation bar and create a dropdown menu and search box, which will initially not appear in a straight line. We can use the unordered list “ul” of HTML structure which is in the form of a list. HTML <!DOCTYPE html><html> <head> <meta charset="utf-8"> <meta name="viewport" content= "width=device-width, initial-scale=1"> <!-- Bootstrap CSS library --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="sha384-UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/" crossorigin="anonymous"> <!-- jQuery library --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"> </script></head> <body> <!-- Navigation Bar --> <nav class="navbar navbar-expand-sm bg-dark navbar-dark"> <h5 class="navbar-brand">Geeks For Geeks</h5> <ul class="navbar nav ml-auto"> <!-- Dropdown list --> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false" style="color:white;"> Courses </a> <div class="dropdown-menu"> <a class="dropdown-item" href="#">Live courses </a> <a class="dropdown-item" href="#">Online courses </a> </div> </li> <li> <!-- Search Box --> <input type="text" placeholder="Search.."> </li> </ul> </nav></body> </html> Output: Example 2: HTML <!DOCTYPE html><html> <head> <meta charset="utf-8"> <meta name="viewport" content= "width=device-width, initial-scale=1"> <!-- Bootstrap CSS library --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> <link rel="stylesheet" href= "https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="sha384-UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/" crossorigin="anonymous"> <!-- jQuery library --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"> </script></head> <body> <h2 align="Center" style="color:green;"> Dropdown menu and search box without navigation bar </h2> <ul class="navbar nav ml-auto" style="color:white;background-color:green"> <!-- Dropdown list --> <li> <a class="nav-link dropdown-toggle" data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false" style="color:white;"> Courses </a> <div class="dropdown-menu"> <a class="dropdown-item" href="#">Live courses </a> <a class="dropdown-item" href="#">Online courses </a> </div> <!-- Search Box --> <li> <input class="form-control form-control-sm mr-3 w-75" type="text" placeholder="Search" aria-label="Search"> </li> </li> </ul></body> </html> Output: Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. Bootstrap-4 Bootstrap-Misc HTML-Misc Picked Bootstrap HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Show Images on Click using HTML ? How to set Bootstrap Timepicker using datetimepicker library ? How to Use Bootstrap with React? Tailwind CSS vs Bootstrap How to keep gap between columns using Bootstrap? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to set the default value for an HTML <select> element ? How to update Node.js and NPM to next version ? How to set input type date in dd-mm-yyyy format using HTML ?
[ { "code": null, "e": 25227, "s": 25199, "text": "\n21 Dec, 2020" }, { "code": null, "e": 25518, "s": 25227, "text": "A dropdown menu is a type of menu, by using the dropdown menu user can select something from the given predefined set. It is a toggleable menu, which means it appears when the user clicks on the menu. A search box is a type of box in which you can write the string which you want to search." }, { "code": null, "e": 25596, "s": 25518, "text": "The main aim is to align the dropdown menu and search box in a straight line." }, { "code": null, "e": 25819, "s": 25596, "text": "Example 1: We will create a navigation bar and create a dropdown menu and search box, which will initially not appear in a straight line. We can use the unordered list “ul” of HTML structure which is in the form of a list." }, { "code": null, "e": 25824, "s": 25819, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1\"> <!-- Bootstrap CSS library --> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css\"> <link rel=\"stylesheet\" href=\"https://use.fontawesome.com/releases/v5.6.3/css/all.css\" integrity=\"sha384-UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/\" crossorigin=\"anonymous\"> <!-- jQuery library --> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js\"> </script></head> <body> <!-- Navigation Bar --> <nav class=\"navbar navbar-expand-sm bg-dark navbar-dark\"> <h5 class=\"navbar-brand\">Geeks For Geeks</h5> <ul class=\"navbar nav ml-auto\"> <!-- Dropdown list --> <li class=\"nav-item dropdown\"> <a class=\"nav-link dropdown-toggle\" data-toggle=\"dropdown\" href=\"#\" role=\"button\" aria-haspopup=\"true\" aria-expanded=\"false\" style=\"color:white;\"> Courses </a> <div class=\"dropdown-menu\"> <a class=\"dropdown-item\" href=\"#\">Live courses </a> <a class=\"dropdown-item\" href=\"#\">Online courses </a> </div> </li> <li> <!-- Search Box --> <input type=\"text\" placeholder=\"Search..\"> </li> </ul> </nav></body> </html>", "e": 27737, "s": 25824, "text": null }, { "code": null, "e": 27745, "s": 27737, "text": "Output:" }, { "code": null, "e": 27756, "s": 27745, "text": "Example 2:" }, { "code": null, "e": 27761, "s": 27756, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1\"> <!-- Bootstrap CSS library --> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css\"> <link rel=\"stylesheet\" href= \"https://use.fontawesome.com/releases/v5.6.3/css/all.css\" integrity=\"sha384-UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/\" crossorigin=\"anonymous\"> <!-- jQuery library --> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js\"> </script></head> <body> <h2 align=\"Center\" style=\"color:green;\"> Dropdown menu and search box without navigation bar </h2> <ul class=\"navbar nav ml-auto\" style=\"color:white;background-color:green\"> <!-- Dropdown list --> <li> <a class=\"nav-link dropdown-toggle\" data-toggle=\"dropdown\" href=\"#\" role=\"button\" aria-haspopup=\"true\" aria-expanded=\"false\" style=\"color:white;\"> Courses </a> <div class=\"dropdown-menu\"> <a class=\"dropdown-item\" href=\"#\">Live courses </a> <a class=\"dropdown-item\" href=\"#\">Online courses </a> </div> <!-- Search Box --> <li> <input class=\"form-control form-control-sm mr-3 w-75\" type=\"text\" placeholder=\"Search\" aria-label=\"Search\"> </li> </li> </ul></body> </html>", "e": 29659, "s": 27761, "text": null }, { "code": null, "e": 29667, "s": 29659, "text": "Output:" }, { "code": null, "e": 29804, "s": 29667, "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": 29816, "s": 29804, "text": "Bootstrap-4" }, { "code": null, "e": 29831, "s": 29816, "text": "Bootstrap-Misc" }, { "code": null, "e": 29841, "s": 29831, "text": "HTML-Misc" }, { "code": null, "e": 29848, "s": 29841, "text": "Picked" }, { "code": null, "e": 29858, "s": 29848, "text": "Bootstrap" }, { "code": null, "e": 29863, "s": 29858, "text": "HTML" }, { "code": null, "e": 29880, "s": 29863, "text": "Web Technologies" }, { "code": null, "e": 29885, "s": 29880, "text": "HTML" }, { "code": null, "e": 29983, "s": 29885, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29992, "s": 29983, "text": "Comments" }, { "code": null, "e": 30005, "s": 29992, "text": "Old Comments" }, { "code": null, "e": 30046, "s": 30005, "text": "How to Show Images on Click using HTML ?" }, { "code": null, "e": 30109, "s": 30046, "text": "How to set Bootstrap Timepicker using datetimepicker library ?" }, { "code": null, "e": 30142, "s": 30109, "text": "How to Use Bootstrap with React?" }, { "code": null, "e": 30168, "s": 30142, "text": "Tailwind CSS vs Bootstrap" }, { "code": null, "e": 30217, "s": 30168, "text": "How to keep gap between columns using Bootstrap?" }, { "code": null, "e": 30279, "s": 30217, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 30329, "s": 30279, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 30389, "s": 30329, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 30437, "s": 30389, "text": "How to update Node.js and NPM to next version ?" } ]
Training a Naive Bayes model to identify the author of an email or document | by Ivan Duran | Towards Data Science
In this example, we use a set of emails or documents that were written by two different individuals. The purpose is to train a Naive Bayes model to be able to predict who wrote a document/email, given the words used in it The Github repository with the files used in this example can be found here. The file nb_email_author.py contains the script that loads the data, trains the model, and find the score of the prediction for train and test sets. Here, we explain the main parts of the script and the results. The first section of the script loads the data. The only particularity here is that ‘pickle’ is used deserialize the original data file (for more on pickle and serialization/deserialization, take a look at this link). Two files are loaded, one that contains the emails or documents, and another one with just the emails’ authors. Once we deserialize and load the files, we have two arrays (lists), one named words, and one named authors, each of size 17,578. Each element in words is a single string that contains an email or document. Each element in `authors` is either 0 or 1. As usual, we split the data into train and test sets using the Scikit-learn method sklearn.model_selection.train_test_split. from sklearn.model_selection import train_test_splitfeatures_train, features_test, labels_train, labels_test = train_test_split(words, authors, test_size=0.1, random_state=10) When dealing with texts in machine learning, it is quite common to transform the text into data that can be easily analyzed and quantify. For this, the most commonly used technique is the tf-idf short for “term frequency-inverse document frequency”, which basically reflects how important a word is to a document (email) in a collection or corpus (our set of emails or documents). The tf-idf is an statistic that increases with the number of times a word appears in the document, penalized by the number of documents in the corpus that contain the word (Wikipedia). Fortunately for us, Scikit-learn has a method that does just this (sklearn.feature_extraction.text.TfidfVectorizer). See the documentation here). So we apply this method to our data in the following way: from sklearn.feature_extraction.text import TfidfVectorizervectorizer = TfidfVectorizer(sublinear_tf=True, max_df=0.5, stop_words='english')features_train = vectorizer.fit_transform(features_train)features_test = vectorizer.transform(features_test) TfidfVectorizer sets the vectorizer up. Here we change sublinear_tf to true, which replaces tf with 1 + log(tf). This addresses the issue that “twenty occurrences of a term in a document” does not represent “twenty times the significance of a single occurrence” (link). Therefore, it reduces the importance of high frequency words (note that 1+log(1) = 1, while 1+log(20) = 2.3). Additionally, stop_words is set to ‘english’, so stop words such as “and”, “the”, “him” will be ignored in this case, and max_df=0.5 means that we are ignoring terms that have a document frequency higher than 0.5 (i.e., the proportion of documents in which the term is found). Next, we fit and transform the features (terms or words in our case) for both train and test sets. Notice that for the train set we use fit_transform, and for the test set we use just transform. This makes sense since we want the model to learn the vocabulary and the document frequencies by the train set, and then transform the train features into a terms-document matrix. For the test set we just want to use the learned document frequencies (idf’s) and vocabulary to transform it into a term-document matrix. Let’s see how this look like with a simplified example: Suppose we have the following train corpus, again, each item represents one document/email: corpus = [ "This is my first email.", "I'm trying to learn machine learning.", "This is the second email", "Learning is fun"] Now, let’s fit and transform it: vectorizer = TfidfVectorizer()X = vectorizer.fit_transform(corpus)print(X.__str__)# <4x13 sparse matrix of type ‘<class ‘numpy.float64’>’ with 18 stored elements in Compressed Sparse Row format> fit_transform returns a sparse matrix: print(X)# (0, 10) 0.41263976171812644# (0, 3) 0.3340674500232949# (0, 7) 0.5233812152405496# (0, 1) 0.5233812152405496# (0, 0) 0.41263976171812644# (1, 12) 0.4651619335222394# (1, 11) 0.4651619335222394# (1, 4) 0.4651619335222394# (1, 6) 0.4651619335222394# (1, 5) 0.3667390112974172# (2, 10) 0.41263976171812644# (2, 3) 0.3340674500232949# (2, 0) 0.41263976171812644# (2, 9) 0.5233812152405496# (2, 8) 0.5233812152405496# (3, 3) 0.4480997313625986# (3, 5) 0.5534923152870045# (3, 2) 0.7020348194149619 If we transform X into a 2D array, it looks like this (there are 13 columns in total, each represent a word/term, odd columns are omitted for brevity): vocabulary = vectorizer.get_feature_names()pd.DataFrame(data=X.toarray(), columns=vocabulary).iloc[:,0::2] print(vocabulary)# [‘email’, ‘first’, ‘fun’, ‘is’, ‘learn’, ‘learning’, ‘machine’, ‘my’, ‘second’, ‘the’, ‘this’, ‘to’, ‘trying’] Now let’s suppose that we have the following ‘test’ document: test = [“I’m also trying to learn python”] Let’s transform it and take a look at it: X_test = vectorizer.transform(test)pd.DataFrame(data=X_test.toarray(), columns=vocabulary).iloc[:, 0::2] There you have it, this is how texts or documents are vectorized for further analysis. Although selecting a smaller set of features is not strictly necessary, it could be computationally challenging to train a model with too many words or features. In this example, we use Scikit-learn’s SelectPercentile to choose features with highest scores (documentation): from sklearn.feature_selection import SelectPercentile, f_classifselector = SelectPercentile(f_classif, percentile=10)selector.fit(features_train, labels_train)features_train = selector.transform(features_train).toarray()features_test = selector.transform(features_test).toarray() The selector uses f_classif as score function, which computes the ANOVA F-values for the sample. Basically we are choosing the terms with largest F-values (i.e. terms or words for which the frequency mean is most likely to be different across classes or authors). This is common in order to choose the best discriminatory features across classes (out of 38,209 words initially, we end up with 3,821). For this example, we use a Gaussian Naive Bayes (NB) implementation (Scikit-learn documentation here). In future articles, we will discuss in detail the theory behind Naive Bayes. For now, it is worth saying that NB is based on applying the Bayes’ rule to calculate the probability or likelihood that a set of words (document/email) is written by someone or some class (e.g. P(“Chris”| “learn”, “machine”, “trying”,...)). However, there is no such a thing as a naive Bayes’ rule. The ‘naive’ term arises due to assuming that features are independent from each other (conditional independence), which means, for our emails analysis, that we are assuming that the location of words in a sentence is completely random (i.e. ‘am’ or ‘robot’ are equally likely to follow the word ‘I’, which of course is not true). In general, training machine learning models with Scikit-learn is straightforward and it normally follows the same pattern: initialize an instance of the class model, fit the train data, predict the test data (we omit that here), compute scores for both train and test sets. from sklearn.naive_bayes import GaussianNBfrom time import timet0 = time()model = GaussianNB()model.fit(features_train, labels_train)print(f”\nTraining time: {round(time()-t0, 3)}s”)t0 = time()score_train = model.score(features_train, labels_train)print(f”Prediction time (train): {round(time()-t0, 3)}s”)t0 = time()score_test = model.score(features_test, labels_test)print(f”Prediction time (test): {round(time()-t0, 3)}s”)print(“\nTrain set score:”, score_train)print(“Test set score:”, score_test) The results are the following: >>> Training time: 1.601s>>> Prediction time (train): 1.787s>>> Prediction time (test): 0.151s>>> Train set score: 0.9785082174462706>>> Test set score: 0.9783845278725825
[ { "code": null, "e": 394, "s": 172, "text": "In this example, we use a set of emails or documents that were written by two different individuals. The purpose is to train a Naive Bayes model to be able to predict who wrote a document/email, given the words used in it" }, { "code": null, "e": 620, "s": 394, "text": "The Github repository with the files used in this example can be found here. The file nb_email_author.py contains the script that loads the data, trains the model, and find the score of the prediction for train and test sets." }, { "code": null, "e": 683, "s": 620, "text": "Here, we explain the main parts of the script and the results." }, { "code": null, "e": 901, "s": 683, "text": "The first section of the script loads the data. The only particularity here is that ‘pickle’ is used deserialize the original data file (for more on pickle and serialization/deserialization, take a look at this link)." }, { "code": null, "e": 1263, "s": 901, "text": "Two files are loaded, one that contains the emails or documents, and another one with just the emails’ authors. Once we deserialize and load the files, we have two arrays (lists), one named words, and one named authors, each of size 17,578. Each element in words is a single string that contains an email or document. Each element in `authors` is either 0 or 1." }, { "code": null, "e": 1388, "s": 1263, "text": "As usual, we split the data into train and test sets using the Scikit-learn method sklearn.model_selection.train_test_split." }, { "code": null, "e": 1564, "s": 1388, "text": "from sklearn.model_selection import train_test_splitfeatures_train, features_test, labels_train, labels_test = train_test_split(words, authors, test_size=0.1, random_state=10)" }, { "code": null, "e": 1702, "s": 1564, "text": "When dealing with texts in machine learning, it is quite common to transform the text into data that can be easily analyzed and quantify." }, { "code": null, "e": 1945, "s": 1702, "text": "For this, the most commonly used technique is the tf-idf short for “term frequency-inverse document frequency”, which basically reflects how important a word is to a document (email) in a collection or corpus (our set of emails or documents)." }, { "code": null, "e": 2130, "s": 1945, "text": "The tf-idf is an statistic that increases with the number of times a word appears in the document, penalized by the number of documents in the corpus that contain the word (Wikipedia)." }, { "code": null, "e": 2276, "s": 2130, "text": "Fortunately for us, Scikit-learn has a method that does just this (sklearn.feature_extraction.text.TfidfVectorizer). See the documentation here)." }, { "code": null, "e": 2334, "s": 2276, "text": "So we apply this method to our data in the following way:" }, { "code": null, "e": 2583, "s": 2334, "text": "from sklearn.feature_extraction.text import TfidfVectorizervectorizer = TfidfVectorizer(sublinear_tf=True, max_df=0.5, stop_words='english')features_train = vectorizer.fit_transform(features_train)features_test = vectorizer.transform(features_test)" }, { "code": null, "e": 2963, "s": 2583, "text": "TfidfVectorizer sets the vectorizer up. Here we change sublinear_tf to true, which replaces tf with 1 + log(tf). This addresses the issue that “twenty occurrences of a term in a document” does not represent “twenty times the significance of a single occurrence” (link). Therefore, it reduces the importance of high frequency words (note that 1+log(1) = 1, while 1+log(20) = 2.3)." }, { "code": null, "e": 3240, "s": 2963, "text": "Additionally, stop_words is set to ‘english’, so stop words such as “and”, “the”, “him” will be ignored in this case, and max_df=0.5 means that we are ignoring terms that have a document frequency higher than 0.5 (i.e., the proportion of documents in which the term is found)." }, { "code": null, "e": 3435, "s": 3240, "text": "Next, we fit and transform the features (terms or words in our case) for both train and test sets. Notice that for the train set we use fit_transform, and for the test set we use just transform." }, { "code": null, "e": 3753, "s": 3435, "text": "This makes sense since we want the model to learn the vocabulary and the document frequencies by the train set, and then transform the train features into a terms-document matrix. For the test set we just want to use the learned document frequencies (idf’s) and vocabulary to transform it into a term-document matrix." }, { "code": null, "e": 3809, "s": 3753, "text": "Let’s see how this look like with a simplified example:" }, { "code": null, "e": 3901, "s": 3809, "text": "Suppose we have the following train corpus, again, each item represents one document/email:" }, { "code": null, "e": 4039, "s": 3901, "text": "corpus = [ \"This is my first email.\", \"I'm trying to learn machine learning.\", \"This is the second email\", \"Learning is fun\"]" }, { "code": null, "e": 4072, "s": 4039, "text": "Now, let’s fit and transform it:" }, { "code": null, "e": 4267, "s": 4072, "text": "vectorizer = TfidfVectorizer()X = vectorizer.fit_transform(corpus)print(X.__str__)# <4x13 sparse matrix of type ‘<class ‘numpy.float64’>’ with 18 stored elements in Compressed Sparse Row format>" }, { "code": null, "e": 4306, "s": 4267, "text": "fit_transform returns a sparse matrix:" }, { "code": null, "e": 4859, "s": 4306, "text": "print(X)# (0, 10) 0.41263976171812644# (0, 3) 0.3340674500232949# (0, 7) 0.5233812152405496# (0, 1) 0.5233812152405496# (0, 0) 0.41263976171812644# (1, 12) 0.4651619335222394# (1, 11) 0.4651619335222394# (1, 4) 0.4651619335222394# (1, 6) 0.4651619335222394# (1, 5) 0.3667390112974172# (2, 10) 0.41263976171812644# (2, 3) 0.3340674500232949# (2, 0) 0.41263976171812644# (2, 9) 0.5233812152405496# (2, 8) 0.5233812152405496# (3, 3) 0.4480997313625986# (3, 5) 0.5534923152870045# (3, 2) 0.7020348194149619" }, { "code": null, "e": 5011, "s": 4859, "text": "If we transform X into a 2D array, it looks like this (there are 13 columns in total, each represent a word/term, odd columns are omitted for brevity):" }, { "code": null, "e": 5118, "s": 5011, "text": "vocabulary = vectorizer.get_feature_names()pd.DataFrame(data=X.toarray(), columns=vocabulary).iloc[:,0::2]" }, { "code": null, "e": 5248, "s": 5118, "text": "print(vocabulary)# [‘email’, ‘first’, ‘fun’, ‘is’, ‘learn’, ‘learning’, ‘machine’, ‘my’, ‘second’, ‘the’, ‘this’, ‘to’, ‘trying’]" }, { "code": null, "e": 5310, "s": 5248, "text": "Now let’s suppose that we have the following ‘test’ document:" }, { "code": null, "e": 5353, "s": 5310, "text": "test = [“I’m also trying to learn python”]" }, { "code": null, "e": 5395, "s": 5353, "text": "Let’s transform it and take a look at it:" }, { "code": null, "e": 5500, "s": 5395, "text": "X_test = vectorizer.transform(test)pd.DataFrame(data=X_test.toarray(), columns=vocabulary).iloc[:, 0::2]" }, { "code": null, "e": 5587, "s": 5500, "text": "There you have it, this is how texts or documents are vectorized for further analysis." }, { "code": null, "e": 5749, "s": 5587, "text": "Although selecting a smaller set of features is not strictly necessary, it could be computationally challenging to train a model with too many words or features." }, { "code": null, "e": 5861, "s": 5749, "text": "In this example, we use Scikit-learn’s SelectPercentile to choose features with highest scores (documentation):" }, { "code": null, "e": 6142, "s": 5861, "text": "from sklearn.feature_selection import SelectPercentile, f_classifselector = SelectPercentile(f_classif, percentile=10)selector.fit(features_train, labels_train)features_train = selector.transform(features_train).toarray()features_test = selector.transform(features_test).toarray()" }, { "code": null, "e": 6543, "s": 6142, "text": "The selector uses f_classif as score function, which computes the ANOVA F-values for the sample. Basically we are choosing the terms with largest F-values (i.e. terms or words for which the frequency mean is most likely to be different across classes or authors). This is common in order to choose the best discriminatory features across classes (out of 38,209 words initially, we end up with 3,821)." }, { "code": null, "e": 6723, "s": 6543, "text": "For this example, we use a Gaussian Naive Bayes (NB) implementation (Scikit-learn documentation here). In future articles, we will discuss in detail the theory behind Naive Bayes." }, { "code": null, "e": 6965, "s": 6723, "text": "For now, it is worth saying that NB is based on applying the Bayes’ rule to calculate the probability or likelihood that a set of words (document/email) is written by someone or some class (e.g. P(“Chris”| “learn”, “machine”, “trying”,...))." }, { "code": null, "e": 7353, "s": 6965, "text": "However, there is no such a thing as a naive Bayes’ rule. The ‘naive’ term arises due to assuming that features are independent from each other (conditional independence), which means, for our emails analysis, that we are assuming that the location of words in a sentence is completely random (i.e. ‘am’ or ‘robot’ are equally likely to follow the word ‘I’, which of course is not true)." }, { "code": null, "e": 7477, "s": 7353, "text": "In general, training machine learning models with Scikit-learn is straightforward and it normally follows the same pattern:" }, { "code": null, "e": 7520, "s": 7477, "text": "initialize an instance of the class model," }, { "code": null, "e": 7540, "s": 7520, "text": "fit the train data," }, { "code": null, "e": 7583, "s": 7540, "text": "predict the test data (we omit that here)," }, { "code": null, "e": 7628, "s": 7583, "text": "compute scores for both train and test sets." }, { "code": null, "e": 8129, "s": 7628, "text": "from sklearn.naive_bayes import GaussianNBfrom time import timet0 = time()model = GaussianNB()model.fit(features_train, labels_train)print(f”\\nTraining time: {round(time()-t0, 3)}s”)t0 = time()score_train = model.score(features_train, labels_train)print(f”Prediction time (train): {round(time()-t0, 3)}s”)t0 = time()score_test = model.score(features_test, labels_test)print(f”Prediction time (test): {round(time()-t0, 3)}s”)print(“\\nTrain set score:”, score_train)print(“Test set score:”, score_test)" }, { "code": null, "e": 8160, "s": 8129, "text": "The results are the following:" } ]
Fastest Way to Install & Load Libraries in R | by Catherine Williams | Towards Data Science
After working collaboratively with a classmate, it became apparent that I needed a new way of loading libraries from what I was taught in school. Not everyone has the same libraries installed and this can run into errors. I wanted the code to run seamlessly for everyone. Additionally, it is painful to have to write the same functions over and over again to install and load different libraries. My classmate and I worked to find a simple way to do this. I then used a package called tictoc to measure the speed of different methods. Note: The testing was done with a clean global environment. All of the packages have already been installed and loaded as well so that testing can stay consistent (the packages will just re-load). First, the tictoc package needs to be installed and loaded in order to do the analysis. I will also define a variable for the list of packages to be loaded. install.packages("tictoc")library(tictoc)packages <- c("tidyverse", "dplyr", "stringr", "zoo", "ROCR", "caret", "class", "gmodels", "randomForest") Method 1 — Load and install each library separately: I commented out install.packages because it will reinstall whether the package exists or not. This is not the most efficient method since you will either reinstall everything or get an error if install.packages is omitted and the package does not exist in the current installation. Total time: 0.11 sec tic("basic")#install.packages(packages)library(tidyverse)library(dplyr)library(stringr)library(zoo)library(ROCR)library(caret)library(class)library(gmodels)library(randomForest)toc(log = TRUE)log.txt <- tic.log(format = TRUE) Method 2 — Use a for loop Total time: 0.13 sec tic("for loop")libraries <- function(packages){ for(package in packages){ #checks if package is installed if(!require(package, character.only = TRUE)){ #If package does not exist, then it will install install.packages(package, dependencies = TRUE) #Loads package library(package, character.only = TRUE) } }}libraries(packages)toc(log = TRUE)log.txt <- tic.log(format = TRUE) Method 3 — Use apply method Total time: 0.07 sec tic("apply")ipak <- function(pkg){ new.pkg <- pkg[!(pkg %in% installed.packages()[, "Package"])] if (length(new.pkg)) install.packages(new.pkg, dependencies = TRUE) sapply(pkg, require, character.only = TRUE)}ipak(packages)toc(log = TRUE)log.txt <- tic.log(format = TRUE) Method 4 — Use the install.load package For the purposes of this post, I calculated the time with the assumption that the user already has install.load installed, since this would only have to happen once. The code to install is just there for reproducibility purposes. Total time: 0.12 sec tic("install.load")if (!require("install.load")) install.packages("install.load")library(install.load)install_load(packages)toc(log = TRUE)log.txt <- tic.log(format = TRUE) Method 5 — Use the pacman package This was also calculated with the assumption that the user already has pacman installed. Total time: 0.06 sec tic("pacman")if (!require("pacman")) install.packages("pacman")#pacman will not accept a character vector so the same packages are repeatedpacman::p_load("tidyverse", "dplyr", "stringr", "zoo", "ROCR", "caret", "class", "gmodels", "randomForest")toc(log = TRUE)log.txt <- tic.log(format = TRUE) Final Verdict The fastest way to install and/or load many packages is to use the pacman package. However, if you did not want to install an extra package, using the apply method will be the best. It is only minutely slower. It is important to also mention that with the “basic” test, if the user is unsure of the packages they currently have installed, this method can become drastically slower for the reasons mentioned above.
[ { "code": null, "e": 707, "s": 172, "text": "After working collaboratively with a classmate, it became apparent that I needed a new way of loading libraries from what I was taught in school. Not everyone has the same libraries installed and this can run into errors. I wanted the code to run seamlessly for everyone. Additionally, it is painful to have to write the same functions over and over again to install and load different libraries. My classmate and I worked to find a simple way to do this. I then used a package called tictoc to measure the speed of different methods." }, { "code": null, "e": 904, "s": 707, "text": "Note: The testing was done with a clean global environment. All of the packages have already been installed and loaded as well so that testing can stay consistent (the packages will just re-load)." }, { "code": null, "e": 1061, "s": 904, "text": "First, the tictoc package needs to be installed and loaded in order to do the analysis. I will also define a variable for the list of packages to be loaded." }, { "code": null, "e": 1209, "s": 1061, "text": "install.packages(\"tictoc\")library(tictoc)packages <- c(\"tidyverse\", \"dplyr\", \"stringr\", \"zoo\", \"ROCR\", \"caret\", \"class\", \"gmodels\", \"randomForest\")" }, { "code": null, "e": 1262, "s": 1209, "text": "Method 1 — Load and install each library separately:" }, { "code": null, "e": 1544, "s": 1262, "text": "I commented out install.packages because it will reinstall whether the package exists or not. This is not the most efficient method since you will either reinstall everything or get an error if install.packages is omitted and the package does not exist in the current installation." }, { "code": null, "e": 1565, "s": 1544, "text": "Total time: 0.11 sec" }, { "code": null, "e": 1791, "s": 1565, "text": "tic(\"basic\")#install.packages(packages)library(tidyverse)library(dplyr)library(stringr)library(zoo)library(ROCR)library(caret)library(class)library(gmodels)library(randomForest)toc(log = TRUE)log.txt <- tic.log(format = TRUE)" }, { "code": null, "e": 1817, "s": 1791, "text": "Method 2 — Use a for loop" }, { "code": null, "e": 1838, "s": 1817, "text": "Total time: 0.13 sec" }, { "code": null, "e": 2244, "s": 1838, "text": "tic(\"for loop\")libraries <- function(packages){ for(package in packages){ #checks if package is installed if(!require(package, character.only = TRUE)){ #If package does not exist, then it will install install.packages(package, dependencies = TRUE) #Loads package library(package, character.only = TRUE) } }}libraries(packages)toc(log = TRUE)log.txt <- tic.log(format = TRUE)" }, { "code": null, "e": 2272, "s": 2244, "text": "Method 3 — Use apply method" }, { "code": null, "e": 2293, "s": 2272, "text": "Total time: 0.07 sec" }, { "code": null, "e": 2571, "s": 2293, "text": "tic(\"apply\")ipak <- function(pkg){ new.pkg <- pkg[!(pkg %in% installed.packages()[, \"Package\"])] if (length(new.pkg)) install.packages(new.pkg, dependencies = TRUE) sapply(pkg, require, character.only = TRUE)}ipak(packages)toc(log = TRUE)log.txt <- tic.log(format = TRUE)" }, { "code": null, "e": 2611, "s": 2571, "text": "Method 4 — Use the install.load package" }, { "code": null, "e": 2841, "s": 2611, "text": "For the purposes of this post, I calculated the time with the assumption that the user already has install.load installed, since this would only have to happen once. The code to install is just there for reproducibility purposes." }, { "code": null, "e": 2862, "s": 2841, "text": "Total time: 0.12 sec" }, { "code": null, "e": 3035, "s": 2862, "text": "tic(\"install.load\")if (!require(\"install.load\")) install.packages(\"install.load\")library(install.load)install_load(packages)toc(log = TRUE)log.txt <- tic.log(format = TRUE)" }, { "code": null, "e": 3069, "s": 3035, "text": "Method 5 — Use the pacman package" }, { "code": null, "e": 3158, "s": 3069, "text": "This was also calculated with the assumption that the user already has pacman installed." }, { "code": null, "e": 3179, "s": 3158, "text": "Total time: 0.06 sec" }, { "code": null, "e": 3474, "s": 3179, "text": "tic(\"pacman\")if (!require(\"pacman\")) install.packages(\"pacman\")#pacman will not accept a character vector so the same packages are repeatedpacman::p_load(\"tidyverse\", \"dplyr\", \"stringr\", \"zoo\", \"ROCR\", \"caret\", \"class\", \"gmodels\", \"randomForest\")toc(log = TRUE)log.txt <- tic.log(format = TRUE)" }, { "code": null, "e": 3488, "s": 3474, "text": "Final Verdict" }, { "code": null, "e": 3698, "s": 3488, "text": "The fastest way to install and/or load many packages is to use the pacman package. However, if you did not want to install an extra package, using the apply method will be the best. It is only minutely slower." } ]
Developing a Timeseries Heatmap in Python Using Plotly | by M Khorasani | Towards Data Science
Anyone who has ever been exposed to the data, knows that time series data is arguably the most abundant type of datum that we deal with on a routine basis. Data that is indexed with date, time and/or both is thereby classified as a timeseries dataset. Often, it may be helpful to render our timeseries as a monthly and hourly heatmap visualization. Such powerful visualizations are supremely helpful in being able to digest data that is otherwise presented in form that may not be ingested into our highly visual selves. These renderings, will usually depict hour horizontally, month vertically, and will utilize color to communicate the intensity of the value the underlying cell represents. Here, we are going to transform a randomly generated timeseries dataset into an interactive heatmap useful some of Python’s most powerful bindings. Python aside, we will be availing ourselves of Plotly, Pandas and Streamlit — some of the most formidable workhouses of the data science community. I gather that many will be more than acquainted with Pandas; Plotly and Streamlit on the other hand may not ring as many bells. The following offers a quick recap of each: 1. Pandas Pandas is without any shred of doubt one of the most effective bindings in Python when it comes to processing data. Pandas enables you to perform a whole slew of transformations on your set, all by invoking a couple of short commands. In our application we will use Pandas to read/write our data from/into a CSV files and to regroup our timestamps into months and hours of the day. 2. Plotly Plotly is a robust and agile data visualization library that is specifically tailored towards tools for machine learning and data science. While it is based on plotly.js which itself is a native Javascript binding, it has been expanded to support Python, R and other popular scripting languages. By employing a few lines of JSON in your Python script, you can easily invoke interactive visualizations including but not limited to line charts, histograms, radar plots, heatmaps and more. In this instance, we will be using Plotly, to render our month vs. hour heatmap. 3. Streamlit Streamlit is the unsung hero of Python libraries. It is a pure Python web framework that allows you develop and deploy your applications as web apps without writing a single line of HTML or CSS, kid you not. For me personally, I started using Streamlit in the summer of 2020 and since then I do not recall ever NOT using it for the scripts that I have written since. Streamlit allows you to instantaneously render your applications with an elegant and highly interactive user interface. For this application we will be using Streamlit to depict our heatmap and data frame on a local browser. First thing’s first, go ahead and install the following packages on an Anaconda environment of your choosing. Each package can be installed by typing the following corresponding command into Anaconda prompt. pip install plotly We will be using this randomly generated dataset, that has a column for the date, hour and value as shown below. The date is formatted as follows: YYYYMMDD While the hour is formatted as: HHMM You can format your date and/or hour using any other formatting that suits your needs, but you will have to make sure that you declare it in your script as explained in the following section. Before we can go any further, we need to preprocess our dataset to ensure that the dates and hours are in a format that may be processed further. Initially, we need to remove any trailing decimal places from the values in our hour column and add leading zeroes in case the time is less than a whole hour, i.e. 12:00AM quoted as 0. Subsequently, we need to append our dates to hours and parse them in a format that is comprehensible by using the datetime.strptime binding in Python. Finally, we can transform the dates into months and the hours into the 12 hour format by using the strftime function: In order to use other datetime formatting’s please refer to this article. Once our data has been preprocessed, we can then use the powerful groubpy class in Pandas to regroup our dataset into time averaged values for months and hours as shown below: Please note that other methods may be used instead of averaging, i.e summations, maximum or minimum by changing: df.groupby(['Month','Hour'],sort=False,as_index=False).mean() to df.groupby(['Month','Hour'],sort=False,as_index=False).sum() Now that we have regrouped our data into months and hours, we first need to transform our Pandas data frame into a dictionary and then an array that can be input into Plotly to create our heatmap. Declare a dictionary and please make sure to add all of the months of the year without the truncation shown below: Subsequently, we will insert the values from our Pandas data frame into the dictionary, and will use it to create an array of arrays corresponding to the averaged values of each month and hour respectively, as shown below: Finally, we will render our Plotly heatmap using the array previously created: You may find it convenient to download your regrouped month vs. hour data frame as a CSV file. If so please use the following function to create a downloadable file in your Streamlit app. This function’s arguments — name and df correspond to the name of the downloadable file and data frame that needs to be converted to a CSV file respectively. Finally, we can combine everything together in the form of a Streamlit application that will render the heatmap, data frame and a link to download our regrouped data as a CSV file. You can run your final app, by typing the following commands in Anaconda prompt. First, change your root directory to where your source code is saved: cd C:/Users/... Then type the following to run your app: streamlit run file_name.py And there you go, an interactive rendering that enables you to visualize your timeseries dataset as month vs. hour heatmap. If you want to learn more about data visualization and Python, then feel free to check out the following (affiliate linked) courses:
[ { "code": null, "e": 1013, "s": 172, "text": "Anyone who has ever been exposed to the data, knows that time series data is arguably the most abundant type of datum that we deal with on a routine basis. Data that is indexed with date, time and/or both is thereby classified as a timeseries dataset. Often, it may be helpful to render our timeseries as a monthly and hourly heatmap visualization. Such powerful visualizations are supremely helpful in being able to digest data that is otherwise presented in form that may not be ingested into our highly visual selves. These renderings, will usually depict hour horizontally, month vertically, and will utilize color to communicate the intensity of the value the underlying cell represents. Here, we are going to transform a randomly generated timeseries dataset into an interactive heatmap useful some of Python’s most powerful bindings." }, { "code": null, "e": 1333, "s": 1013, "text": "Python aside, we will be availing ourselves of Plotly, Pandas and Streamlit — some of the most formidable workhouses of the data science community. I gather that many will be more than acquainted with Pandas; Plotly and Streamlit on the other hand may not ring as many bells. The following offers a quick recap of each:" }, { "code": null, "e": 1343, "s": 1333, "text": "1. Pandas" }, { "code": null, "e": 1725, "s": 1343, "text": "Pandas is without any shred of doubt one of the most effective bindings in Python when it comes to processing data. Pandas enables you to perform a whole slew of transformations on your set, all by invoking a couple of short commands. In our application we will use Pandas to read/write our data from/into a CSV files and to regroup our timestamps into months and hours of the day." }, { "code": null, "e": 1735, "s": 1725, "text": "2. Plotly" }, { "code": null, "e": 2303, "s": 1735, "text": "Plotly is a robust and agile data visualization library that is specifically tailored towards tools for machine learning and data science. While it is based on plotly.js which itself is a native Javascript binding, it has been expanded to support Python, R and other popular scripting languages. By employing a few lines of JSON in your Python script, you can easily invoke interactive visualizations including but not limited to line charts, histograms, radar plots, heatmaps and more. In this instance, we will be using Plotly, to render our month vs. hour heatmap." }, { "code": null, "e": 2316, "s": 2303, "text": "3. Streamlit" }, { "code": null, "e": 2908, "s": 2316, "text": "Streamlit is the unsung hero of Python libraries. It is a pure Python web framework that allows you develop and deploy your applications as web apps without writing a single line of HTML or CSS, kid you not. For me personally, I started using Streamlit in the summer of 2020 and since then I do not recall ever NOT using it for the scripts that I have written since. Streamlit allows you to instantaneously render your applications with an elegant and highly interactive user interface. For this application we will be using Streamlit to depict our heatmap and data frame on a local browser." }, { "code": null, "e": 3018, "s": 2908, "text": "First thing’s first, go ahead and install the following packages on an Anaconda environment of your choosing." }, { "code": null, "e": 3116, "s": 3018, "text": "Each package can be installed by typing the following corresponding command into Anaconda prompt." }, { "code": null, "e": 3135, "s": 3116, "text": "pip install plotly" }, { "code": null, "e": 3248, "s": 3135, "text": "We will be using this randomly generated dataset, that has a column for the date, hour and value as shown below." }, { "code": null, "e": 3282, "s": 3248, "text": "The date is formatted as follows:" }, { "code": null, "e": 3291, "s": 3282, "text": "YYYYMMDD" }, { "code": null, "e": 3323, "s": 3291, "text": "While the hour is formatted as:" }, { "code": null, "e": 3328, "s": 3323, "text": "HHMM" }, { "code": null, "e": 3520, "s": 3328, "text": "You can format your date and/or hour using any other formatting that suits your needs, but you will have to make sure that you declare it in your script as explained in the following section." }, { "code": null, "e": 3666, "s": 3520, "text": "Before we can go any further, we need to preprocess our dataset to ensure that the dates and hours are in a format that may be processed further." }, { "code": null, "e": 4120, "s": 3666, "text": "Initially, we need to remove any trailing decimal places from the values in our hour column and add leading zeroes in case the time is less than a whole hour, i.e. 12:00AM quoted as 0. Subsequently, we need to append our dates to hours and parse them in a format that is comprehensible by using the datetime.strptime binding in Python. Finally, we can transform the dates into months and the hours into the 12 hour format by using the strftime function:" }, { "code": null, "e": 4194, "s": 4120, "text": "In order to use other datetime formatting’s please refer to this article." }, { "code": null, "e": 4370, "s": 4194, "text": "Once our data has been preprocessed, we can then use the powerful groubpy class in Pandas to regroup our dataset into time averaged values for months and hours as shown below:" }, { "code": null, "e": 4483, "s": 4370, "text": "Please note that other methods may be used instead of averaging, i.e summations, maximum or minimum by changing:" }, { "code": null, "e": 4545, "s": 4483, "text": "df.groupby(['Month','Hour'],sort=False,as_index=False).mean()" }, { "code": null, "e": 4548, "s": 4545, "text": "to" }, { "code": null, "e": 4609, "s": 4548, "text": "df.groupby(['Month','Hour'],sort=False,as_index=False).sum()" }, { "code": null, "e": 4806, "s": 4609, "text": "Now that we have regrouped our data into months and hours, we first need to transform our Pandas data frame into a dictionary and then an array that can be input into Plotly to create our heatmap." }, { "code": null, "e": 4921, "s": 4806, "text": "Declare a dictionary and please make sure to add all of the months of the year without the truncation shown below:" }, { "code": null, "e": 5144, "s": 4921, "text": "Subsequently, we will insert the values from our Pandas data frame into the dictionary, and will use it to create an array of arrays corresponding to the averaged values of each month and hour respectively, as shown below:" }, { "code": null, "e": 5223, "s": 5144, "text": "Finally, we will render our Plotly heatmap using the array previously created:" }, { "code": null, "e": 5411, "s": 5223, "text": "You may find it convenient to download your regrouped month vs. hour data frame as a CSV file. If so please use the following function to create a downloadable file in your Streamlit app." }, { "code": null, "e": 5569, "s": 5411, "text": "This function’s arguments — name and df correspond to the name of the downloadable file and data frame that needs to be converted to a CSV file respectively." }, { "code": null, "e": 5750, "s": 5569, "text": "Finally, we can combine everything together in the form of a Streamlit application that will render the heatmap, data frame and a link to download our regrouped data as a CSV file." }, { "code": null, "e": 5901, "s": 5750, "text": "You can run your final app, by typing the following commands in Anaconda prompt. First, change your root directory to where your source code is saved:" }, { "code": null, "e": 5917, "s": 5901, "text": "cd C:/Users/..." }, { "code": null, "e": 5958, "s": 5917, "text": "Then type the following to run your app:" }, { "code": null, "e": 5985, "s": 5958, "text": "streamlit run file_name.py" }, { "code": null, "e": 6109, "s": 5985, "text": "And there you go, an interactive rendering that enables you to visualize your timeseries dataset as month vs. hour heatmap." } ]
Difference between = and IN operator in SQL - GeeksforGeeks
21 Aug, 2020 Prerequisite – SQL CommandsIn this article we are going to see the difference between = and IN operator in SQL. 1. = Operator :The = operator is used with Where Clause in SQL.For Example consider the student table given below, Query :To fetch record of students with address as Delhi or ROHTAK.The SQL query using = operator would be, SELECT * FROM Student WHERE ADDRESS='Delhi' OR ADDRESS='ROHTAK'; Output : 2. IN Operator :The IN operator is used with Where Clause to test if the expression matches any value in the list of values. The advantage of using IN operator is that it avoids the use of multiple OR Operator. Query :To fetch record of students with address as Delhi or ROHTAK.The SQL query using IN operator would be, SELECT * FROM Student WHERE ADDRESS IN ('Delhi', 'ROHTAK'); Output : Difference between = and IN Operator : DBMS-SQL DBMS Difference Between GATE CS SQL DBMS SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Second Normal Form (2NF) Introduction of Relational Algebra in DBMS What is Temporary Table in SQL? Types of Functional dependencies in DBMS Difference between Where and Having Clause in SQL Difference between BFS and DFS Class method vs Static method in Python Difference between var, let and const keywords in JavaScript Differences between TCP and UDP Difference between Process and Thread
[ { "code": null, "e": 23913, "s": 23885, "text": "\n21 Aug, 2020" }, { "code": null, "e": 24025, "s": 23913, "text": "Prerequisite – SQL CommandsIn this article we are going to see the difference between = and IN operator in SQL." }, { "code": null, "e": 24140, "s": 24025, "text": "1. = Operator :The = operator is used with Where Clause in SQL.For Example consider the student table given below," }, { "code": null, "e": 24248, "s": 24140, "text": "Query :To fetch record of students with address as Delhi or ROHTAK.The SQL query using = operator would be," }, { "code": null, "e": 24317, "s": 24248, "text": " SELECT * \nFROM Student \nWHERE ADDRESS='Delhi' OR ADDRESS='ROHTAK'; " }, { "code": null, "e": 24326, "s": 24317, "text": "Output :" }, { "code": null, "e": 24537, "s": 24326, "text": "2. IN Operator :The IN operator is used with Where Clause to test if the expression matches any value in the list of values. The advantage of using IN operator is that it avoids the use of multiple OR Operator." }, { "code": null, "e": 24646, "s": 24537, "text": "Query :To fetch record of students with address as Delhi or ROHTAK.The SQL query using IN operator would be," }, { "code": null, "e": 24709, "s": 24646, "text": "SELECT * \nFROM Student \nWHERE ADDRESS IN ('Delhi', 'ROHTAK'); " }, { "code": null, "e": 24718, "s": 24709, "text": "Output :" }, { "code": null, "e": 24757, "s": 24718, "text": "Difference between = and IN Operator :" }, { "code": null, "e": 24766, "s": 24757, "text": "DBMS-SQL" }, { "code": null, "e": 24771, "s": 24766, "text": "DBMS" }, { "code": null, "e": 24790, "s": 24771, "text": "Difference Between" }, { "code": null, "e": 24798, "s": 24790, "text": "GATE CS" }, { "code": null, "e": 24802, "s": 24798, "text": "SQL" }, { "code": null, "e": 24807, "s": 24802, "text": "DBMS" }, { "code": null, "e": 24811, "s": 24807, "text": "SQL" }, { "code": null, "e": 24909, "s": 24811, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 24918, "s": 24909, "text": "Comments" }, { "code": null, "e": 24931, "s": 24918, "text": "Old Comments" }, { "code": null, "e": 24956, "s": 24931, "text": "Second Normal Form (2NF)" }, { "code": null, "e": 24999, "s": 24956, "text": "Introduction of Relational Algebra in DBMS" }, { "code": null, "e": 25031, "s": 24999, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 25072, "s": 25031, "text": "Types of Functional dependencies in DBMS" }, { "code": null, "e": 25122, "s": 25072, "text": "Difference between Where and Having Clause in SQL" }, { "code": null, "e": 25153, "s": 25122, "text": "Difference between BFS and DFS" }, { "code": null, "e": 25193, "s": 25153, "text": "Class method vs Static method in Python" }, { "code": null, "e": 25254, "s": 25193, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 25286, "s": 25254, "text": "Differences between TCP and UDP" } ]
jQuery - Effects
jQuery provides a trivially simple interface for doing various kind of amazing effects. jQuery methods allow us to quickly apply commonly used effects with a minimum configuration. This tutorial covers all the important jQuery methods to create visual effects. The commands for showing and hiding elements are pretty much what we would expect − show() to show the elements in a wrapped set and hide() to hide them. Here is the simple syntax for show() method − [selector].show( speed, [callback] ); Here is the description of all the parameters − speed − A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds to run the animation (e.g. 1000). speed − A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds to run the animation (e.g. 1000). callback − This optional parameter represents a function to be executed whenever the animation completes; executes once for each element animated against. callback − This optional parameter represents a function to be executed whenever the animation completes; executes once for each element animated against. Following is the simple syntax for hide() method − [selector].hide( speed, [callback] ); Here is the description of all the parameters − speed − A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds to run the animation (e.g. 1000). speed − A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds to run the animation (e.g. 1000). callback − This optional parameter represents a function to be executed whenever the animation completes; executes once for each element animated against. callback − This optional parameter represents a function to be executed whenever the animation completes; executes once for each element animated against. Consider the following HTML file with a small JQuery coding − <html> <head> <title>The jQuery Example</title> <script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script> <script type = "text/javascript" language = "javascript"> $(document).ready(function() { $("#show").click(function () { $(".mydiv").show( 1000 ); }); $("#hide").click(function () { $(".mydiv").hide( 1000 ); }); }); </script> <style> .mydiv{ margin:10px; padding:12px; border:2px solid #666; width:100px; height:100px; } </style> </head> <body> <div class = "mydiv"> This is a SQUARE </div> <input id = "hide" type = "button" value = "Hide" /> <input id = "show" type = "button" value = "Show" /> </body> </html> This will produce following result − jQuery provides methods to toggle the display state of elements between revealed or hidden. If the element is initially displayed, it will be hidden; if hidden, it will be shown. Here is the simple syntax for one of the toggle() methods − [selector]..toggle([speed][, callback]); Here is the description of all the parameters − speed − A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds to run the animation (e.g. 1000). speed − A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds to run the animation (e.g. 1000). callback − This optional parameter represents a function to be executed whenever the animation completes; executes once for each element animated against. callback − This optional parameter represents a function to be executed whenever the animation completes; executes once for each element animated against. We can animate any element, such as a simple <div> containing an image − <html> <head> <title>The jQuery Example</title> <script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script> <script type = "text/javascript" language = "javascript"> $(document).ready(function() { $(".clickme").click(function(event){ $(".target").toggle('slow', function(){ $(".log").text('Transition Complete'); }); }); }); </script> <style> .clickme{ margin:10px; padding:12px; border:2px solid #666; width:100px; height:50px; } </style> </head> <body> <div class = "content"> <div class = "clickme">Click Me</div> <div class = "target"> <img src = "./images/jquery.jpg" alt = "jQuery" /> </div> <div class = "log"></div> </div> </body> </html> This will produce following result − You have seen basic concept of jQuery Effects. Following table lists down all the important methods to create different kind of effects − A function for making custom animations. Fade in all matched elements by adjusting their opacity and firing an optional callback after completion. Fade out all matched elements by adjusting their opacity to 0, then setting display to "none" and firing an optional callback after completion. Fade the opacity of all matched elements to a specified opacity and firing an optional callback after completion. Hides each of the set of matched elements if they are shown. Hide all matched elements using a graceful animation and firing an optional callback after completion. Displays each of the set of matched elements if they are hidden. Show all matched elements using a graceful animation and firing an optional callback after completion. Reveal all matched elements by adjusting their height and firing an optional callback after completion. Toggle the visibility of all matched elements by adjusting their height and firing an optional callback after completion. Hide all matched elements by adjusting their height and firing an optional callback after completion. Stops all the currently running animations on all the specified elements. Toggle displaying each of the set of matched elements. Toggle displaying each of the set of matched elements using a graceful animation and firing an optional callback after completion. Toggle displaying each of the set of matched elements based upon the switch (true shows all elements, false hides all elements). Globally disable all animations. To use these effects you can either download latest jQuery UI Library jquery-ui-1.11.4.custom.zip from jQuery UI Library or use Google CDN to use it in the similar way as we have done for jQuery. We have used Google CDN for jQuery UI using following code snippet in the HTML page so we can use jQuery UI − <head> <script src = "https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/jquery-ui.min.js"> </script> </head> Blinds the element away or shows it by blinding it in. Bounces the element vertically or horizontally n-times. Clips the element on or off, vertically or horizontally. Drops the element away or shows it by dropping it in. Explodes the element into multiple pieces. Folds the element like a piece of paper. Highlights the background with a defined color. Scale and fade out animations create the puff effect. Pulsates the opacity of the element multiple times. Shrink or grow an element by a percentage factor. Shakes the element vertically or horizontally n-times. Resize an element to a specified width and height. Slides the element out of the viewport. Transfers the outline of an element to another. 27 Lectures 1 hours Mahesh Kumar 27 Lectures 1.5 hours Pratik Singh 72 Lectures 4.5 hours Frahaan Hussain 60 Lectures 9 hours Eduonix Learning Solutions 17 Lectures 2 hours Sandip Bhattacharya 12 Lectures 53 mins Laurence Svekis Print Add Notes Bookmark this page
[ { "code": null, "e": 2583, "s": 2322, "text": "jQuery provides a trivially simple interface for doing various kind of amazing effects. jQuery methods allow us to quickly apply commonly used effects with a minimum configuration. This tutorial covers all the important jQuery methods to create visual effects." }, { "code": null, "e": 2737, "s": 2583, "text": "The commands for showing and hiding elements are pretty much what we would expect − show() to show the elements in a wrapped set and hide() to hide them." }, { "code": null, "e": 2783, "s": 2737, "text": "Here is the simple syntax for show() method −" }, { "code": null, "e": 2822, "s": 2783, "text": "[selector].show( speed, [callback] );\n" }, { "code": null, "e": 2870, "s": 2822, "text": "Here is the description of all the parameters −" }, { "code": null, "e": 3029, "s": 2870, "text": "speed − A string representing one of the three predefined speeds (\"slow\", \"normal\", or \"fast\") or the number of milliseconds to run the animation (e.g. 1000)." }, { "code": null, "e": 3188, "s": 3029, "text": "speed − A string representing one of the three predefined speeds (\"slow\", \"normal\", or \"fast\") or the number of milliseconds to run the animation (e.g. 1000)." }, { "code": null, "e": 3343, "s": 3188, "text": "callback − This optional parameter represents a function to be executed whenever the animation completes; executes once for each element animated against." }, { "code": null, "e": 3498, "s": 3343, "text": "callback − This optional parameter represents a function to be executed whenever the animation completes; executes once for each element animated against." }, { "code": null, "e": 3549, "s": 3498, "text": "Following is the simple syntax for hide() method −" }, { "code": null, "e": 3588, "s": 3549, "text": "[selector].hide( speed, [callback] );\n" }, { "code": null, "e": 3636, "s": 3588, "text": "Here is the description of all the parameters −" }, { "code": null, "e": 3795, "s": 3636, "text": "speed − A string representing one of the three predefined speeds (\"slow\", \"normal\", or \"fast\") or the number of milliseconds to run the animation (e.g. 1000)." }, { "code": null, "e": 3954, "s": 3795, "text": "speed − A string representing one of the three predefined speeds (\"slow\", \"normal\", or \"fast\") or the number of milliseconds to run the animation (e.g. 1000)." }, { "code": null, "e": 4109, "s": 3954, "text": "callback − This optional parameter represents a function to be executed whenever the animation completes; executes once for each element animated against." }, { "code": null, "e": 4264, "s": 4109, "text": "callback − This optional parameter represents a function to be executed whenever the animation completes; executes once for each element animated against." }, { "code": null, "e": 4326, "s": 4264, "text": "Consider the following HTML file with a small JQuery coding −" }, { "code": null, "e": 5297, "s": 4326, "text": "<html>\n <head>\n <title>The jQuery Example</title>\n <script type = \"text/javascript\" \n src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\">\n </script>\n\t\t\n <script type = \"text/javascript\" language = \"javascript\">\n $(document).ready(function() {\n\n $(\"#show\").click(function () {\n $(\".mydiv\").show( 1000 );\n });\n\n $(\"#hide\").click(function () {\n $(\".mydiv\").hide( 1000 );\n });\n\t\t\t\t\n });\n </script>\n\t\t\n <style>\n .mydiv{ \n margin:10px;\n padding:12px; \n border:2px solid #666; \n width:100px; \n height:100px;\n }\n </style>\n </head>\n\t\n <body>\n <div class = \"mydiv\">\n This is a SQUARE\n </div>\n\n <input id = \"hide\" type = \"button\" value = \"Hide\" /> \n <input id = \"show\" type = \"button\" value = \"Show\" />\n </body>\n</html>" }, { "code": null, "e": 5334, "s": 5297, "text": "This will produce following result −" }, { "code": null, "e": 5513, "s": 5334, "text": "jQuery provides methods to toggle the display state of elements between revealed or hidden. If the element is initially displayed, it will be hidden; if hidden, it will be shown." }, { "code": null, "e": 5573, "s": 5513, "text": "Here is the simple syntax for one of the toggle() methods −" }, { "code": null, "e": 5615, "s": 5573, "text": "[selector]..toggle([speed][, callback]);\n" }, { "code": null, "e": 5663, "s": 5615, "text": "Here is the description of all the parameters −" }, { "code": null, "e": 5822, "s": 5663, "text": "speed − A string representing one of the three predefined speeds (\"slow\", \"normal\", or \"fast\") or the number of milliseconds to run the animation (e.g. 1000)." }, { "code": null, "e": 5981, "s": 5822, "text": "speed − A string representing one of the three predefined speeds (\"slow\", \"normal\", or \"fast\") or the number of milliseconds to run the animation (e.g. 1000)." }, { "code": null, "e": 6136, "s": 5981, "text": "callback − This optional parameter represents a function to be executed whenever the animation completes; executes once for each element animated against." }, { "code": null, "e": 6291, "s": 6136, "text": "callback − This optional parameter represents a function to be executed whenever the animation completes; executes once for each element animated against." }, { "code": null, "e": 6364, "s": 6291, "text": "We can animate any element, such as a simple <div> containing an image −" }, { "code": null, "e": 7372, "s": 6364, "text": "<html>\n <head>\n <title>The jQuery Example</title>\n <script type = \"text/javascript\" \n src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\">\n </script>\n\t\t\n <script type = \"text/javascript\" language = \"javascript\">\n $(document).ready(function() {\n $(\".clickme\").click(function(event){\n $(\".target\").toggle('slow', function(){\n $(\".log\").text('Transition Complete');\n });\n });\n });\n </script>\n\t\t\n <style>\n .clickme{ \n margin:10px;\n padding:12px; \n border:2px solid #666; \n width:100px; \n height:50px;\n }\n </style>\n </head>\n\t\n <body>\n <div class = \"content\">\n <div class = \"clickme\">Click Me</div>\n <div class = \"target\">\n <img src = \"./images/jquery.jpg\" alt = \"jQuery\" />\n </div>\n <div class = \"log\"></div>\n </div>\n </body>\n</html>" }, { "code": null, "e": 7409, "s": 7372, "text": "This will produce following result −" }, { "code": null, "e": 7547, "s": 7409, "text": "You have seen basic concept of jQuery Effects. Following table lists down all the important methods to create different kind of effects −" }, { "code": null, "e": 7588, "s": 7547, "text": "A function for making custom animations." }, { "code": null, "e": 7694, "s": 7588, "text": "Fade in all matched elements by adjusting their opacity and firing an optional callback after completion." }, { "code": null, "e": 7838, "s": 7694, "text": "Fade out all matched elements by adjusting their opacity to 0, then setting display to \"none\" and firing an optional callback after completion." }, { "code": null, "e": 7952, "s": 7838, "text": "Fade the opacity of all matched elements to a specified opacity and firing an optional callback after completion." }, { "code": null, "e": 8013, "s": 7952, "text": "Hides each of the set of matched elements if they are shown." }, { "code": null, "e": 8116, "s": 8013, "text": "Hide all matched elements using a graceful animation and firing an optional callback after completion." }, { "code": null, "e": 8181, "s": 8116, "text": "Displays each of the set of matched elements if they are hidden." }, { "code": null, "e": 8284, "s": 8181, "text": "Show all matched elements using a graceful animation and firing an optional callback after completion." }, { "code": null, "e": 8388, "s": 8284, "text": "Reveal all matched elements by adjusting their height and firing an optional callback after completion." }, { "code": null, "e": 8510, "s": 8388, "text": "Toggle the visibility of all matched elements by adjusting their height and firing an optional callback after completion." }, { "code": null, "e": 8612, "s": 8510, "text": "Hide all matched elements by adjusting their height and firing an optional callback after completion." }, { "code": null, "e": 8686, "s": 8612, "text": "Stops all the currently running animations on all the specified elements." }, { "code": null, "e": 8741, "s": 8686, "text": "Toggle displaying each of the set of matched elements." }, { "code": null, "e": 8872, "s": 8741, "text": "Toggle displaying each of the set of matched elements using a graceful animation and firing an optional callback after completion." }, { "code": null, "e": 9001, "s": 8872, "text": "Toggle displaying each of the set of matched elements based upon the switch (true shows all elements, false hides all elements)." }, { "code": null, "e": 9034, "s": 9001, "text": "Globally disable all animations." }, { "code": null, "e": 9230, "s": 9034, "text": "To use these effects you can either download latest jQuery UI Library jquery-ui-1.11.4.custom.zip from jQuery UI Library or use Google CDN to use it in the similar way as we have done for jQuery." }, { "code": null, "e": 9340, "s": 9230, "text": "We have used Google CDN for jQuery UI using following code snippet in the HTML page so we can use jQuery UI −" }, { "code": null, "e": 9459, "s": 9340, "text": "<head>\n <script src = \"https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/jquery-ui.min.js\">\n </script>\n</head>" }, { "code": null, "e": 9514, "s": 9459, "text": "Blinds the element away or shows it by blinding it in." }, { "code": null, "e": 9570, "s": 9514, "text": "Bounces the element vertically or horizontally n-times." }, { "code": null, "e": 9627, "s": 9570, "text": "Clips the element on or off, vertically or horizontally." }, { "code": null, "e": 9681, "s": 9627, "text": "Drops the element away or shows it by dropping it in." }, { "code": null, "e": 9724, "s": 9681, "text": "Explodes the element into multiple pieces." }, { "code": null, "e": 9765, "s": 9724, "text": "Folds the element like a piece of paper." }, { "code": null, "e": 9813, "s": 9765, "text": "Highlights the background with a defined color." }, { "code": null, "e": 9867, "s": 9813, "text": "Scale and fade out animations create the puff effect." }, { "code": null, "e": 9919, "s": 9867, "text": "Pulsates the opacity of the element multiple times." }, { "code": null, "e": 9969, "s": 9919, "text": "Shrink or grow an element by a percentage factor." }, { "code": null, "e": 10024, "s": 9969, "text": "Shakes the element vertically or horizontally n-times." }, { "code": null, "e": 10075, "s": 10024, "text": "Resize an element to a specified width and height." }, { "code": null, "e": 10115, "s": 10075, "text": "Slides the element out of the viewport." }, { "code": null, "e": 10163, "s": 10115, "text": "Transfers the outline of an element to another." }, { "code": null, "e": 10196, "s": 10163, "text": "\n 27 Lectures \n 1 hours \n" }, { "code": null, "e": 10210, "s": 10196, "text": " Mahesh Kumar" }, { "code": null, "e": 10245, "s": 10210, "text": "\n 27 Lectures \n 1.5 hours \n" }, { "code": null, "e": 10259, "s": 10245, "text": " Pratik Singh" }, { "code": null, "e": 10294, "s": 10259, "text": "\n 72 Lectures \n 4.5 hours \n" }, { "code": null, "e": 10311, "s": 10294, "text": " Frahaan Hussain" }, { "code": null, "e": 10344, "s": 10311, "text": "\n 60 Lectures \n 9 hours \n" }, { "code": null, "e": 10372, "s": 10344, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 10405, "s": 10372, "text": "\n 17 Lectures \n 2 hours \n" }, { "code": null, "e": 10426, "s": 10405, "text": " Sandip Bhattacharya" }, { "code": null, "e": 10458, "s": 10426, "text": "\n 12 Lectures \n 53 mins\n" }, { "code": null, "e": 10475, "s": 10458, "text": " Laurence Svekis" }, { "code": null, "e": 10482, "s": 10475, "text": " Print" }, { "code": null, "e": 10493, "s": 10482, "text": " Add Notes" } ]
How can we sort a JSONArray in Java?
The JSON is one of the widely used data-interchange formats and is a lightweight and language independent. A JSONArray can parse text from a String to produce a vector-like object and supports java.util.List interface. We can sort a JSONArray in the below example. import java.util.*; import org.json.*; public class SortJSONArrayTest { public static void main(String[] args) { String jsonStr = "[ { \"ID\": \"115\", \"Name\": \"Raja\" },{ \"ID\": \"120\", \"Name\": \"Jai\" },{ \"ID\": \"125\", \"Name\": \"Adithya\" }]"; JSONArray jsonArray = new JSONArray(jsonStr); JSONArray sortedJsonArray = new JSONArray(); List list = new ArrayList(); for(int i = 0; i < jsonArray.length(); i++) { list.add(jsonArray.getJSONObject(i)); } System.out.println("Before Sorted JSONArray: " + jsonArray); Collections.sort(list, new Comparator() { private static final String KEY_NAME = "Name"; @Override public int compare(JSONObject a, JSONObject b) { String str1 = new String(); String str2 = new String(); try { str1 = (String)a.get(KEY_NAME); str2 = (String)b.get(KEY_NAME); } catch(JSONException e) { e.printStackTrace(); } return str1.compareTo(str2); } }); for(int i = 0; i < jsonArray.length(); i++) { sortedJsonArray.put(list.get(i)); } System.out.println("Sorted JSON Array with Name: " + sortedJsonArray); } } Before Sorted JSONArray: [{"ID":"115","Name":"Raja"}, {"ID":"120","Name":"Jai"}, {"ID":"125","Name":"Adithya"}] Sorted JSON Array with Name: [{"ID":"125","Name":"Adithya"}, {"ID":"120","Name":"Jai"}, {"ID":"115","Name":"Raja"}]
[ { "code": null, "e": 1282, "s": 1062, "text": "The JSON is one of the widely used data-interchange formats and is a lightweight and language independent. A JSONArray can parse text from a String to produce a vector-like object and supports java.util.List interface. " }, { "code": null, "e": 1328, "s": 1282, "text": "We can sort a JSONArray in the below example." }, { "code": null, "e": 2618, "s": 1328, "text": "import java.util.*;\nimport org.json.*;\npublic class SortJSONArrayTest {\n public static void main(String[] args) {\n String jsonStr = \"[ { \\\"ID\\\": \\\"115\\\", \\\"Name\\\": \\\"Raja\\\" },{ \\\"ID\\\": \\\"120\\\", \\\"Name\\\": \\\"Jai\\\" },{ \\\"ID\\\": \\\"125\\\", \\\"Name\\\": \\\"Adithya\\\" }]\";\n JSONArray jsonArray = new JSONArray(jsonStr);\n JSONArray sortedJsonArray = new JSONArray();\n List list = new ArrayList();\n for(int i = 0; i < jsonArray.length(); i++) {\n list.add(jsonArray.getJSONObject(i));\n }\n System.out.println(\"Before Sorted JSONArray: \" + jsonArray);\n Collections.sort(list, new Comparator() {\n private static final String KEY_NAME = \"Name\";\n @Override\n public int compare(JSONObject a, JSONObject b) {\n String str1 = new String();\n String str2 = new String();\n try {\n str1 = (String)a.get(KEY_NAME);\n str2 = (String)b.get(KEY_NAME);\n } catch(JSONException e) {\n e.printStackTrace();\n }\n return str1.compareTo(str2);\n }\n });\n for(int i = 0; i < jsonArray.length(); i++) {\n sortedJsonArray.put(list.get(i));\n }\n System.out.println(\"Sorted JSON Array with Name: \" + sortedJsonArray);\n }\n}" }, { "code": null, "e": 2858, "s": 2618, "text": "Before Sorted JSONArray:\n[{\"ID\":\"115\",\"Name\":\"Raja\"},\n {\"ID\":\"120\",\"Name\":\"Jai\"},\n {\"ID\":\"125\",\"Name\":\"Adithya\"}]\nSorted JSON Array with Name:\n[{\"ID\":\"125\",\"Name\":\"Adithya\"},\n {\"ID\":\"120\",\"Name\":\"Jai\"},\n {\"ID\":\"115\",\"Name\":\"Raja\"}]" } ]
Kotlin Strings
Strings are used for storing text. A string contains a collection of characters surrounded by double quotes: var greeting = "Hello" Unlike Java, you do not have to specify that the variable should be a String. Kotlin is smart enough to understand that the greeting variable in the example above is a String because of the double quotes. However, just like with other data types, you can specify the type if you insist: var greeting: String = "Hello" Note: If you want to create a String without assigning the value (and assign the value later), you must specify the type while declaring the variable: This works fine: var name: String name = "John" println(name) This will generate an error: var name name = "John" println(name) To access the characters (elements) of a string, you must refer to the index number inside square brackets. String indexes start with 0. In the example below, we access the first and third element in txt: var txt = "Hello World" println(txt[0]) // first element (H) println(txt[2]) // third element (l) [0] is the first element. [1] is the second element, [2] is the third element, etc. A String in Kotlin is an object, which contain properties and functions that can perform certain operations on strings, by writing a dot character (.) after the specific string variable. For example, the length of a string can be found with the length property: var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" println("The length of the txt string is: " + txt.length) There are many string functions available, for example toUpperCase() and toLowerCase(): var txt = "Hello World" println(txt.toUpperCase()) // Outputs "HELLO WORLD" println(txt.toLowerCase()) // Outputs "hello world" The compareTo(string) function compares two strings and returns 0 if both are equal: var txt1 = "Hello World"var txt2 = "Hello World" println(txt1.compareTo(txt2)) // Outputs 0 (they are equal) The indexOf() function returns the index (the position) of the first occurrence of a specified text in a string (including whitespace): var txt = "Please locate where 'locate' occurs!" println(txt.indexOf("locate")) // Outputs 7 Remember that Kotlin counts positions from zero.0 is the first position in a string, 1 is the second, 2 is the third ... To use quotes inside a string, use single quotes ('): var txt1 = "It's alright" var txt2 = "That's great" The + operator can be used between strings to add them together to make a new string. This is called concatenation: var firstName = "John" var lastName = "Doe" println(firstName + " " + lastName) Note that we have added an empty text (" ") to create a space between firstName and lastName on print. You can also use the plus() function to concatenate two strings: var firstName = "John " var lastName = "Doe" println(firstName.plus(lastName)) Instead of concatenation, you can also use "string templates", which is an easy way to add variables and expressions inside a string. Just refer to the variable with the $ symbol: var firstName = "John" var lastName = "Doe" println("My name is $firstName $lastName") "String Templates" is a popular feature of Kotlin, as it reduces the amount of code. For example, you do not have to specify a whitespace between firstName and lastName, like we did in the concatenation example. 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": 35, "s": 0, "text": "Strings are used for storing text." }, { "code": null, "e": 109, "s": 35, "text": "A string contains a collection of characters surrounded by double quotes:" }, { "code": null, "e": 132, "s": 109, "text": "var greeting = \"Hello\"" }, { "code": null, "e": 338, "s": 132, "text": "Unlike Java, you do not have to specify that the variable should be a String. Kotlin is smart enough to understand that the greeting variable in the example \nabove is a String because of the double quotes." }, { "code": null, "e": 420, "s": 338, "text": "However, just like with other data types, you can specify the type if you insist:" }, { "code": null, "e": 451, "s": 420, "text": "var greeting: String = \"Hello\"" }, { "code": null, "e": 602, "s": 451, "text": "Note: If you want to create a String without assigning the value (and assign the value later), you must specify the type while declaring the variable:" }, { "code": null, "e": 619, "s": 602, "text": "This works fine:" }, { "code": null, "e": 664, "s": 619, "text": "var name: String\nname = \"John\"\nprintln(name)" }, { "code": null, "e": 693, "s": 664, "text": "This will generate an error:" }, { "code": null, "e": 730, "s": 693, "text": "var name\nname = \"John\"\nprintln(name)" }, { "code": null, "e": 839, "s": 730, "text": "To access the characters (elements) of a string, you must refer to the index number \ninside square brackets." }, { "code": null, "e": 937, "s": 839, "text": "String indexes start with 0. In the example below, we access the first and third element in \ntxt:" }, { "code": null, "e": 1035, "s": 937, "text": "var txt = \"Hello World\"\nprintln(txt[0]) // first element (H)\nprintln(txt[2]) // third element (l)" }, { "code": null, "e": 1119, "s": 1035, "text": "[0] is the first element. [1] is the second element, [2] is the third element, etc." }, { "code": null, "e": 1383, "s": 1119, "text": "A String in Kotlin is an object, which contain properties and functions that can perform certain operations on strings, \nby writing a dot character (.) after the specific string variable. For example, the length of a string can be found with the length \nproperty:" }, { "code": null, "e": 1480, "s": 1383, "text": "var txt = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\nprintln(\"The length of the txt string is: \" + txt.length)" }, { "code": null, "e": 1568, "s": 1480, "text": "There are many string functions available, for example toUpperCase() and toLowerCase():" }, { "code": null, "e": 1700, "s": 1568, "text": "var txt = \"Hello World\"\nprintln(txt.toUpperCase()) // Outputs \"HELLO WORLD\"\nprintln(txt.toLowerCase()) // Outputs \"hello world\"" }, { "code": null, "e": 1786, "s": 1700, "text": "The compareTo(string) function \ncompares two strings and returns 0 if both are equal:" }, { "code": null, "e": 1896, "s": 1786, "text": "var txt1 = \"Hello World\"var txt2 = \"Hello World\"\nprintln(txt1.compareTo(txt2)) // Outputs 0 (they are equal)" }, { "code": null, "e": 2034, "s": 1896, "text": "The indexOf() function returns the index (the position) \nof the first occurrence of a specified text in a string \n(including whitespace):" }, { "code": null, "e": 2128, "s": 2034, "text": "var txt = \"Please locate where 'locate' occurs!\"\nprintln(txt.indexOf(\"locate\")) // Outputs 7" }, { "code": null, "e": 2250, "s": 2128, "text": "Remember that Kotlin counts positions from zero.0 is the first position in a \nstring, 1 is the second, 2 is the third ..." }, { "code": null, "e": 2304, "s": 2250, "text": "To use quotes inside a string, use single quotes ('):" }, { "code": null, "e": 2356, "s": 2304, "text": "var txt1 = \"It's alright\"\nvar txt2 = \"That's great\"" }, { "code": null, "e": 2473, "s": 2356, "text": "The + operator can be used between strings to add them together to make a new \nstring. This is called concatenation:" }, { "code": null, "e": 2553, "s": 2473, "text": "var firstName = \"John\"\nvar lastName = \"Doe\"\nprintln(firstName + \" \" + lastName)" }, { "code": null, "e": 2656, "s": 2553, "text": "Note that we have added an empty text (\" \") to create a space between firstName and lastName on print." }, { "code": null, "e": 2721, "s": 2656, "text": "You can also use the plus() function to concatenate two strings:" }, { "code": null, "e": 2800, "s": 2721, "text": "var firstName = \"John \"\nvar lastName = \"Doe\"\nprintln(firstName.plus(lastName))" }, { "code": null, "e": 2935, "s": 2800, "text": "Instead of concatenation, you can also use \"string templates\", which is an \neasy way to add variables and expressions inside a string." }, { "code": null, "e": 2981, "s": 2935, "text": "Just refer to the variable with the $ symbol:" }, { "code": null, "e": 3068, "s": 2981, "text": "var firstName = \"John\"\nvar lastName = \"Doe\"\nprintln(\"My name is $firstName $lastName\")" }, { "code": null, "e": 3282, "s": 3068, "text": "\"String Templates\" is a popular feature of Kotlin, as it reduces the amount \nof code. For example, you do not have to specify a whitespace between firstName \nand lastName, like we did in the concatenation example." }, { "code": null, "e": 3315, "s": 3282, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 3357, "s": 3315, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 3464, "s": 3357, "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": 3483, "s": 3464, "text": "[email protected]" } ]
Model Selection in Text Classification | by Christophe Pere | Towards Data Science
Update 2020–11–24: Added resource in the conclusion Update 2020–08–21: The pipeline can now being used with binary and multiclass classification problem. There is still an error with the transformers when dealing with the save of the model. Update 2020–07–16: The pipeline can now save models, bugs corrected inside the main function. Adaboost, Catboost, LightGBM, ExtratreesClassifier added In the beginning, there was a simple problem. My manager came to me to ask if we could classify mails and associated documents with NLP methods. Doesn’t sound very funky but I’ll start with thousands of sample. The first thing asked was to use “XGBoost” because: “We can do everything with XGBoost”. Interesting job if data science all comes down to XGBoost... After implementing a notebook with different algorithms, metrics, and visualization something was still in my mind. I couldn’t select between the different models in one run. Simply because you can have luck with one model and don’t know how to reproduce the good accuracy, precision etc... So at this moment, I ask myself, how to do a model selection? I looked on the web, read posts, articles, and so on. It was very interesting to see the different manners to implement this kind of thing. But, it was blurry when considering the neural networks. At this moment, I had one thing in mind, how to compare classical methods (multinomial Naïve Bayes, SVM, Logistic Regression, boosting ...) and neural networks (shallow, deep, lstm, rnn, cnn...). I present here a short explanation of the notebook. Comments are welcome. The notebook is available on GitHub: hereThe notebook is available on Colab: here Every project starts with an exploratory data analysis (EDA in short), followed directly by preprocessing (the texts were very dirty, signatures in emails, url, mails header, etc...). The different functions will be presented in the Github repository. A quick way to see if the preprocessing is correct is to determine the most common n-grams (uni, bi, tri... grams). Another post will guide you on this way. We will apply the method of model selection with IMDB dataset. If you are not familiar with the IMDB dataset, it’s a dataset containing movie reviews (text) for sentiment analysis (binary — positive or negative). More details can be found here. To download it: $ wget http://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz$ tar -xzf aclImdb_v1.tar.gz One-Hot encoding (Countvectorizing):It’s the method where words will be replaced by vectors of 0's and 1's. The goal is to take a corpus (important volume of words) and make a vector of each unique word contained in the corpus. After, each word will be projected in this vector where 0 indicates non-existent while 1 indicates existent. | bird | cat | dog | monkey |bird | 1 | 0 | 0 | 0 |cat | 0 | 1 | 0 | 0 |dog | 0 | 0 | 1 | 0 |monkey | 0 | 0 | 0 | 1 | The corresponding python code: # create a count vectorizer object count_vect = CountVectorizer(analyzer='word', token_pattern=r'\w{1,}')count_vect.fit(df[TEXT]) # text without stopwords# transform the training and validation data using count vectorizer objectxtrain_count = count_vect.transform(train_x)xvalid_count = count_vect.transform(valid_x) TF-IDF:Term Frequency-Inverse Document Frequency is a weight often used in information retrieval and text mining. This weight is a statistical measure used to evaluate how important a word is to a document in a collection or corpus (source: tf-idf). This method is powerful when dealing with an important number of stopwords (this type of word is not relevant for the information → I, me, my, myself, we, our, ours, ourselves, you... for the English language). The IDF term permits to reveal the important words and rare words. # word level tf-idftfidf_vect = TfidfVectorizer(analyzer='word', token_pattern=r'\w{1,}', max_features=10000)tfidf_vect.fit(df[TEXT])xtrain_tfidf = tfidf_vect.transform(train_x_sw)xvalid_tfidf = tfidf_vect.transform(valid_x_sw) TF-IDF n-grams:The difference with the previous tf-idf based on one word, the tf-idf n-grams take into account n successive words. # ngram level tf-idftfidf_vect_ngram = TfidfVectorizer(analyzer='word', token_pattern=r'\w{1,}', ngram_range=(2,3), max_features=10000)tfidf_vect_ngram.fit(df[TEXT])xtrain_tfidf_ngram = tfidf_vect_ngram.transform(train_x_sw)xvalid_tfidf_ngram = tfidf_vect_ngram.transform(valid_x_sw) TF-IDF chars n-grams:Same as the previous method but the focus is on the character level, the method will focus on n successive characters. # characters level tf-idftfidf_vect_ngram_chars = TfidfVectorizer(analyzer='char', ngram_range=(2,3), max_features=10000) tfidf_vect_ngram_chars.fit(df[TEXT])xtrain_tfidf_ngram_chars = tfidf_vect_ngram_chars.transform(train_x_sw) xvalid_tfidf_ngram_chars = tfidf_vect_ngram_chars.transform(valid_x_sw) Pre-trained model — FastText FastText is an open-source, free, lightweight library that allows users to learn text representations and text classifiers. It works on standard, generic hardware. Models can later be reduced in size to even fit on mobile devices. (source: here) How to load fastText? From the official documentation: $ git clone https://github.com/facebookresearch/fastText.git $ cd fastText $ sudo pip install . $ # or : $ sudo python setup.py install Download the right model. You have models for 157 languages here. To download the English model: $ wget https://dl.fbaipublicfiles.com/fasttext/vectors-english/crawl-300d-2M-subword.zip& unzip crawl-300d-2M-subword.zip When the download is complete load it in python: pretrained = fasttext.FastText.load_model('crawl-300d-2M-subword.bin') Word Embeddings or Word vectors (WE): Another popular and powerful way to associate a vector with a word is the use of dense “word vectors”, also called “word embeddings”. While the vectors obtained through one-hot encoding are binary, sparse (mostly made of zeros) and very high-dimensional (same dimensionality as the number of words in the vocabulary), “word embeddings” are low-dimensional floating point vectors (i.e. “dense” vectors, as opposed to sparse vectors). Unlike word vectors obtained via one-hot encoding, word embeddings are learned from data. It is common to see word embeddings that are 256-dimensional, 512-dimensional, or 1024-dimensional when dealing with very large vocabularies. On the other hand, one-hot encoding words generally leads to vectors that are 20,000-dimensional or higher (capturing a vocabulary of 20,000 token in this case). So, word embeddings pack more information into far fewer dimensions. (source: Deep Learning with Python, François Chollet 2017) How to map a sentence with int numbers: # create a tokenizer token = Tokenizer()token.fit_on_texts(df[TEXT])word_index = token.word_index# convert text to sequence of tokens and pad them to ensure equal length vectors train_seq_x = sequence.pad_sequences(token.texts_to_sequences(train_x), maxlen=300)valid_seq_x = sequence.pad_sequences(token.texts_to_sequences(valid_x), maxlen=300)# create token-embedding mappingembedding_matrix = np.zeros((len(word_index) + 1, 300))words = []for word, i in tqdm(word_index.items()): embedding_vector = pretrained.get_word_vector(word) #embeddings_index.get(word) words.append(word) if embedding_vector is not None: embedding_matrix[i] = embedding_vector What is model selection in computer science? Specifically in the field of AI? Model selection is the process of choosing between different machine learning approaches. So in short, different models. But, how could we compare them? To do that we need metrics (see this link for more details). The dataset will be split into train and test parts (the validation set will be determined in the deep learning models). What sort of metrics do we use in this binary or multiclass classification model selection? Aparté:For classification we will use the terms:- tp: True positive prediction- tn: True negative prediction- fp: False-positive prediction- fn: False-negative predictionHere a link for more details. Accuracy: All positive predictions on all predictions (tp + tn) / (tp + tn + fp + fn) Balanced Accuracy: It is defined as the average of recall obtained on each class for an imbalanced dataset Precision: The precision is intuitively the ability of the classifier not to label as positive a sample that is negative tp / (tp + fp) Recall (or sensitivity): The recall is intuitively the ability of the classifier to find all the positive samples tp / (tp + fn) f1-score: The f1 score can be interpreted as a weighted average of the precision and recall -> 2 * (precision * recall) / (precision + recall) Cohen kappa: It’s a score that expresses the level of agreement between two annotators on a classification problem. So if the value is less than 0.4 is pretty bad, between 0.4 and 0.6 it,s equivalent to human, 0.6 to 0.8 it’s a great value, more than 0.8 it’s exceptional. Matthews Correlation Coefficient: The Matthews correlation coefficient (MCC) is used in machine learning as a measure of the quality of binary (two-class) classifications [...] The coefficient takes into account true and false positives and negatives and is generally regarded as a balanced measure that can be used even if the classes are of very different sizes. The MCC is in essence a correlation coefficient between the observed and predicted binary classifications; it returns a value between −1 and +1. A coefficient of +1 represents a perfect prediction, 0 no better than random prediction and −1 indicates total disagreement between prediction and observation. (source: Wikipedia) Area Under the Receiver Operating Characteristic Curve (ROC AUC) Time fit: The time needed to train the model Time Score: The time needed to predict results Great !! We are our metrics. What’s next? To be able to realize a robust comparison between models we need to validate the robustness of each model. The figure below shows that the global dataset needs to be splitting into train and test data. Train data to train the model and test data to test the model. Cross-validation is the process of separate the dataset in k-fold. k is the number of proportions we need to realize the data. Generally, k is 5 or 10 it will depend on the size of the dataset (small dataset small k, big dataset big k). The goal is to compute each metric on each fold and compute their average (mean) and the standard deviation (std). In python, this process will be done with the cross_validate function in scikit-learn. What models will we compare? We will test machine learning models, deep learning models, and NLP specialized models. Machine Learning Models Multinomial Naïve Bayes (NB) Logistic Regression (LR) SVM (SVM) Stochastic Gradient Descent (SGD) k-Nearest-Neighbors (kNN) RandomForest (RF) Gradient Boosting (GB) XGBoost (the famous) (XGB) Adaboost Catboost LigthGBM ExtraTreesClassifier Deep Learning Models Shallow Neural Network Deep neural network (and 2 variations) Recurrent Neural Network (RNN) Long Short Term Memory (LSTM) Convolutional Neural Network (CNN) Gated Recurrent Unit (GRU) CNN+LSTM CNN+GRU Bidirectional RNN Bidirectional LSTM Bidirectional GRU Recurrent Convolutional Neural Network (RCNN) (and 3 variations) Transformers That’s all but, 30 models are not bad. This can be resume here: Machine Learning I will use cross_validate() function in sklearn (version 0.23) for classic algorithms to take multiple-metrics into account. The function below, report, take a classifier, X,y data, and a custom list of metrics and it computes the cross-validation on them with the argument. It returns a dataframe containing values for all the metrics and the mean and the standard deviation (std) for each of them. How to use it? Here an example for multinomial Naive Bayes: The term if multinomial_naive_bayes is present because this code is part of the notebook with parameters (boolean) at the beginning. All the code is available in GitHub and Colab. Deep Learning I haven’t found a function like cross_validate for deep learning, only posts about using k-fold cross-validation for neural networks. Here I will share a custom cross_validate function for deep learning with the same input and output as the report function. It will permit us to have the same metrics and to compare all models together. The goal is to take a neural network function as: And call this function inside the cross_validate_NN function. All the Deep Learning received the same implementation and will compare. For the full implementation of the different models go to the notebook. When all the models computed the different folds and metrics we can easily compare them with the dataframe. On the IMDB data set the model performing better is: Here I just show the results for accuracy > 80% and for accuracy, precision, and recall metrics. Build a function within argument a dictionary of models and concatenate all the work in a loop Use distributed Deep Learning Use TensorNetwork to accelerate Neural Networks Use GridSearch for Hyper-tuning You have now an import pipeline to made model selection for text classification with lots of parameters. All of the models are automatics. Enjoy. Another great resource about Model Selection in Machine Learning Era (more theoretic article) was written by Samadrita Ghosh on Neptune.ai blog.
[ { "code": null, "e": 224, "s": 172, "text": "Update 2020–11–24: Added resource in the conclusion" }, { "code": null, "e": 413, "s": 224, "text": "Update 2020–08–21: The pipeline can now being used with binary and multiclass classification problem. There is still an error with the transformers when dealing with the save of the model." }, { "code": null, "e": 564, "s": 413, "text": "Update 2020–07–16: The pipeline can now save models, bugs corrected inside the main function. Adaboost, Catboost, LightGBM, ExtratreesClassifier added" }, { "code": null, "e": 709, "s": 564, "text": "In the beginning, there was a simple problem. My manager came to me to ask if we could classify mails and associated documents with NLP methods." }, { "code": null, "e": 925, "s": 709, "text": "Doesn’t sound very funky but I’ll start with thousands of sample. The first thing asked was to use “XGBoost” because: “We can do everything with XGBoost”. Interesting job if data science all comes down to XGBoost..." }, { "code": null, "e": 1216, "s": 925, "text": "After implementing a notebook with different algorithms, metrics, and visualization something was still in my mind. I couldn’t select between the different models in one run. Simply because you can have luck with one model and don’t know how to reproduce the good accuracy, precision etc..." }, { "code": null, "e": 1672, "s": 1216, "text": "So at this moment, I ask myself, how to do a model selection? I looked on the web, read posts, articles, and so on. It was very interesting to see the different manners to implement this kind of thing. But, it was blurry when considering the neural networks. At this moment, I had one thing in mind, how to compare classical methods (multinomial Naïve Bayes, SVM, Logistic Regression, boosting ...) and neural networks (shallow, deep, lstm, rnn, cnn...)." }, { "code": null, "e": 1746, "s": 1672, "text": "I present here a short explanation of the notebook. Comments are welcome." }, { "code": null, "e": 1828, "s": 1746, "text": "The notebook is available on GitHub: hereThe notebook is available on Colab: here" }, { "code": null, "e": 2080, "s": 1828, "text": "Every project starts with an exploratory data analysis (EDA in short), followed directly by preprocessing (the texts were very dirty, signatures in emails, url, mails header, etc...). The different functions will be presented in the Github repository." }, { "code": null, "e": 2237, "s": 2080, "text": "A quick way to see if the preprocessing is correct is to determine the most common n-grams (uni, bi, tri... grams). Another post will guide you on this way." }, { "code": null, "e": 2498, "s": 2237, "text": "We will apply the method of model selection with IMDB dataset. If you are not familiar with the IMDB dataset, it’s a dataset containing movie reviews (text) for sentiment analysis (binary — positive or negative). More details can be found here. To download it:" }, { "code": null, "e": 2596, "s": 2498, "text": "$ wget http://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz$ tar -xzf aclImdb_v1.tar.gz" }, { "code": null, "e": 2933, "s": 2596, "text": "One-Hot encoding (Countvectorizing):It’s the method where words will be replaced by vectors of 0's and 1's. The goal is to take a corpus (important volume of words) and make a vector of each unique word contained in the corpus. After, each word will be projected in this vector where 0 indicates non-existent while 1 indicates existent." }, { "code": null, "e": 3114, "s": 2933, "text": " | bird | cat | dog | monkey |bird | 1 | 0 | 0 | 0 |cat | 0 | 1 | 0 | 0 |dog | 0 | 0 | 1 | 0 |monkey | 0 | 0 | 0 | 1 |" }, { "code": null, "e": 3145, "s": 3114, "text": "The corresponding python code:" }, { "code": null, "e": 3465, "s": 3145, "text": "# create a count vectorizer object count_vect = CountVectorizer(analyzer='word', token_pattern=r'\\w{1,}')count_vect.fit(df[TEXT]) # text without stopwords# transform the training and validation data using count vectorizer objectxtrain_count = count_vect.transform(train_x)xvalid_count = count_vect.transform(valid_x)" }, { "code": null, "e": 3993, "s": 3465, "text": "TF-IDF:Term Frequency-Inverse Document Frequency is a weight often used in information retrieval and text mining. This weight is a statistical measure used to evaluate how important a word is to a document in a collection or corpus (source: tf-idf). This method is powerful when dealing with an important number of stopwords (this type of word is not relevant for the information → I, me, my, myself, we, our, ours, ourselves, you... for the English language). The IDF term permits to reveal the important words and rare words." }, { "code": null, "e": 4223, "s": 3993, "text": "# word level tf-idftfidf_vect = TfidfVectorizer(analyzer='word', token_pattern=r'\\w{1,}', max_features=10000)tfidf_vect.fit(df[TEXT])xtrain_tfidf = tfidf_vect.transform(train_x_sw)xvalid_tfidf = tfidf_vect.transform(valid_x_sw)" }, { "code": null, "e": 4354, "s": 4223, "text": "TF-IDF n-grams:The difference with the previous tf-idf based on one word, the tf-idf n-grams take into account n successive words." }, { "code": null, "e": 4640, "s": 4354, "text": "# ngram level tf-idftfidf_vect_ngram = TfidfVectorizer(analyzer='word', token_pattern=r'\\w{1,}', ngram_range=(2,3), max_features=10000)tfidf_vect_ngram.fit(df[TEXT])xtrain_tfidf_ngram = tfidf_vect_ngram.transform(train_x_sw)xvalid_tfidf_ngram = tfidf_vect_ngram.transform(valid_x_sw)" }, { "code": null, "e": 4780, "s": 4640, "text": "TF-IDF chars n-grams:Same as the previous method but the focus is on the character level, the method will focus on n successive characters." }, { "code": null, "e": 5085, "s": 4780, "text": "# characters level tf-idftfidf_vect_ngram_chars = TfidfVectorizer(analyzer='char', ngram_range=(2,3), max_features=10000) tfidf_vect_ngram_chars.fit(df[TEXT])xtrain_tfidf_ngram_chars = tfidf_vect_ngram_chars.transform(train_x_sw) xvalid_tfidf_ngram_chars = tfidf_vect_ngram_chars.transform(valid_x_sw)" }, { "code": null, "e": 5114, "s": 5085, "text": "Pre-trained model — FastText" }, { "code": null, "e": 5360, "s": 5114, "text": "FastText is an open-source, free, lightweight library that allows users to learn text representations and text classifiers. It works on standard, generic hardware. Models can later be reduced in size to even fit on mobile devices. (source: here)" }, { "code": null, "e": 5415, "s": 5360, "text": "How to load fastText? From the official documentation:" }, { "code": null, "e": 5551, "s": 5415, "text": "$ git clone https://github.com/facebookresearch/fastText.git $ cd fastText $ sudo pip install . $ # or : $ sudo python setup.py install" }, { "code": null, "e": 5648, "s": 5551, "text": "Download the right model. You have models for 157 languages here. To download the English model:" }, { "code": null, "e": 5770, "s": 5648, "text": "$ wget https://dl.fbaipublicfiles.com/fasttext/vectors-english/crawl-300d-2M-subword.zip& unzip crawl-300d-2M-subword.zip" }, { "code": null, "e": 5819, "s": 5770, "text": "When the download is complete load it in python:" }, { "code": null, "e": 5890, "s": 5819, "text": "pretrained = fasttext.FastText.load_model('crawl-300d-2M-subword.bin')" }, { "code": null, "e": 5928, "s": 5890, "text": "Word Embeddings or Word vectors (WE):" }, { "code": null, "e": 6884, "s": 5928, "text": "Another popular and powerful way to associate a vector with a word is the use of dense “word vectors”, also called “word embeddings”. While the vectors obtained through one-hot encoding are binary, sparse (mostly made of zeros) and very high-dimensional (same dimensionality as the number of words in the vocabulary), “word embeddings” are low-dimensional floating point vectors (i.e. “dense” vectors, as opposed to sparse vectors). Unlike word vectors obtained via one-hot encoding, word embeddings are learned from data. It is common to see word embeddings that are 256-dimensional, 512-dimensional, or 1024-dimensional when dealing with very large vocabularies. On the other hand, one-hot encoding words generally leads to vectors that are 20,000-dimensional or higher (capturing a vocabulary of 20,000 token in this case). So, word embeddings pack more information into far fewer dimensions. (source: Deep Learning with Python, François Chollet 2017)" }, { "code": null, "e": 6924, "s": 6884, "text": "How to map a sentence with int numbers:" }, { "code": null, "e": 7593, "s": 6924, "text": "# create a tokenizer token = Tokenizer()token.fit_on_texts(df[TEXT])word_index = token.word_index# convert text to sequence of tokens and pad them to ensure equal length vectors train_seq_x = sequence.pad_sequences(token.texts_to_sequences(train_x), maxlen=300)valid_seq_x = sequence.pad_sequences(token.texts_to_sequences(valid_x), maxlen=300)# create token-embedding mappingembedding_matrix = np.zeros((len(word_index) + 1, 300))words = []for word, i in tqdm(word_index.items()): embedding_vector = pretrained.get_word_vector(word) #embeddings_index.get(word) words.append(word) if embedding_vector is not None: embedding_matrix[i] = embedding_vector" }, { "code": null, "e": 7792, "s": 7593, "text": "What is model selection in computer science? Specifically in the field of AI? Model selection is the process of choosing between different machine learning approaches. So in short, different models." }, { "code": null, "e": 8006, "s": 7792, "text": "But, how could we compare them? To do that we need metrics (see this link for more details). The dataset will be split into train and test parts (the validation set will be determined in the deep learning models)." }, { "code": null, "e": 8098, "s": 8006, "text": "What sort of metrics do we use in this binary or multiclass classification model selection?" }, { "code": null, "e": 8299, "s": 8098, "text": "Aparté:For classification we will use the terms:- tp: True positive prediction- tn: True negative prediction- fp: False-positive prediction- fn: False-negative predictionHere a link for more details." }, { "code": null, "e": 8385, "s": 8299, "text": "Accuracy: All positive predictions on all predictions (tp + tn) / (tp + tn + fp + fn)" }, { "code": null, "e": 8492, "s": 8385, "text": "Balanced Accuracy: It is defined as the average of recall obtained on each class for an imbalanced dataset" }, { "code": null, "e": 8628, "s": 8492, "text": "Precision: The precision is intuitively the ability of the classifier not to label as positive a sample that is negative tp / (tp + fp)" }, { "code": null, "e": 8757, "s": 8628, "text": "Recall (or sensitivity): The recall is intuitively the ability of the classifier to find all the positive samples tp / (tp + fn)" }, { "code": null, "e": 8900, "s": 8757, "text": "f1-score: The f1 score can be interpreted as a weighted average of the precision and recall -> 2 * (precision * recall) / (precision + recall)" }, { "code": null, "e": 9173, "s": 8900, "text": "Cohen kappa: It’s a score that expresses the level of agreement between two annotators on a classification problem. So if the value is less than 0.4 is pretty bad, between 0.4 and 0.6 it,s equivalent to human, 0.6 to 0.8 it’s a great value, more than 0.8 it’s exceptional." }, { "code": null, "e": 9863, "s": 9173, "text": "Matthews Correlation Coefficient: The Matthews correlation coefficient (MCC) is used in machine learning as a measure of the quality of binary (two-class) classifications [...] The coefficient takes into account true and false positives and negatives and is generally regarded as a balanced measure that can be used even if the classes are of very different sizes. The MCC is in essence a correlation coefficient between the observed and predicted binary classifications; it returns a value between −1 and +1. A coefficient of +1 represents a perfect prediction, 0 no better than random prediction and −1 indicates total disagreement between prediction and observation. (source: Wikipedia)" }, { "code": null, "e": 9928, "s": 9863, "text": "Area Under the Receiver Operating Characteristic Curve (ROC AUC)" }, { "code": null, "e": 9973, "s": 9928, "text": "Time fit: The time needed to train the model" }, { "code": null, "e": 10020, "s": 9973, "text": "Time Score: The time needed to predict results" }, { "code": null, "e": 10062, "s": 10020, "text": "Great !! We are our metrics. What’s next?" }, { "code": null, "e": 10169, "s": 10062, "text": "To be able to realize a robust comparison between models we need to validate the robustness of each model." }, { "code": null, "e": 10454, "s": 10169, "text": "The figure below shows that the global dataset needs to be splitting into train and test data. Train data to train the model and test data to test the model. Cross-validation is the process of separate the dataset in k-fold. k is the number of proportions we need to realize the data." }, { "code": null, "e": 10564, "s": 10454, "text": "Generally, k is 5 or 10 it will depend on the size of the dataset (small dataset small k, big dataset big k)." }, { "code": null, "e": 10679, "s": 10564, "text": "The goal is to compute each metric on each fold and compute their average (mean) and the standard deviation (std)." }, { "code": null, "e": 10766, "s": 10679, "text": "In python, this process will be done with the cross_validate function in scikit-learn." }, { "code": null, "e": 10795, "s": 10766, "text": "What models will we compare?" }, { "code": null, "e": 10883, "s": 10795, "text": "We will test machine learning models, deep learning models, and NLP specialized models." }, { "code": null, "e": 10907, "s": 10883, "text": "Machine Learning Models" }, { "code": null, "e": 10937, "s": 10907, "text": "Multinomial Naïve Bayes (NB)" }, { "code": null, "e": 10962, "s": 10937, "text": "Logistic Regression (LR)" }, { "code": null, "e": 10972, "s": 10962, "text": "SVM (SVM)" }, { "code": null, "e": 11006, "s": 10972, "text": "Stochastic Gradient Descent (SGD)" }, { "code": null, "e": 11032, "s": 11006, "text": "k-Nearest-Neighbors (kNN)" }, { "code": null, "e": 11050, "s": 11032, "text": "RandomForest (RF)" }, { "code": null, "e": 11073, "s": 11050, "text": "Gradient Boosting (GB)" }, { "code": null, "e": 11100, "s": 11073, "text": "XGBoost (the famous) (XGB)" }, { "code": null, "e": 11109, "s": 11100, "text": "Adaboost" }, { "code": null, "e": 11118, "s": 11109, "text": "Catboost" }, { "code": null, "e": 11127, "s": 11118, "text": "LigthGBM" }, { "code": null, "e": 11148, "s": 11127, "text": "ExtraTreesClassifier" }, { "code": null, "e": 11169, "s": 11148, "text": "Deep Learning Models" }, { "code": null, "e": 11192, "s": 11169, "text": "Shallow Neural Network" }, { "code": null, "e": 11231, "s": 11192, "text": "Deep neural network (and 2 variations)" }, { "code": null, "e": 11262, "s": 11231, "text": "Recurrent Neural Network (RNN)" }, { "code": null, "e": 11292, "s": 11262, "text": "Long Short Term Memory (LSTM)" }, { "code": null, "e": 11327, "s": 11292, "text": "Convolutional Neural Network (CNN)" }, { "code": null, "e": 11354, "s": 11327, "text": "Gated Recurrent Unit (GRU)" }, { "code": null, "e": 11363, "s": 11354, "text": "CNN+LSTM" }, { "code": null, "e": 11371, "s": 11363, "text": "CNN+GRU" }, { "code": null, "e": 11389, "s": 11371, "text": "Bidirectional RNN" }, { "code": null, "e": 11408, "s": 11389, "text": "Bidirectional LSTM" }, { "code": null, "e": 11426, "s": 11408, "text": "Bidirectional GRU" }, { "code": null, "e": 11491, "s": 11426, "text": "Recurrent Convolutional Neural Network (RCNN) (and 3 variations)" }, { "code": null, "e": 11504, "s": 11491, "text": "Transformers" }, { "code": null, "e": 11543, "s": 11504, "text": "That’s all but, 30 models are not bad." }, { "code": null, "e": 11568, "s": 11543, "text": "This can be resume here:" }, { "code": null, "e": 11585, "s": 11568, "text": "Machine Learning" }, { "code": null, "e": 11985, "s": 11585, "text": "I will use cross_validate() function in sklearn (version 0.23) for classic algorithms to take multiple-metrics into account. The function below, report, take a classifier, X,y data, and a custom list of metrics and it computes the cross-validation on them with the argument. It returns a dataframe containing values for all the metrics and the mean and the standard deviation (std) for each of them." }, { "code": null, "e": 12000, "s": 11985, "text": "How to use it?" }, { "code": null, "e": 12045, "s": 12000, "text": "Here an example for multinomial Naive Bayes:" }, { "code": null, "e": 12225, "s": 12045, "text": "The term if multinomial_naive_bayes is present because this code is part of the notebook with parameters (boolean) at the beginning. All the code is available in GitHub and Colab." }, { "code": null, "e": 12239, "s": 12225, "text": "Deep Learning" }, { "code": null, "e": 12576, "s": 12239, "text": "I haven’t found a function like cross_validate for deep learning, only posts about using k-fold cross-validation for neural networks. Here I will share a custom cross_validate function for deep learning with the same input and output as the report function. It will permit us to have the same metrics and to compare all models together." }, { "code": null, "e": 12626, "s": 12576, "text": "The goal is to take a neural network function as:" }, { "code": null, "e": 12833, "s": 12626, "text": "And call this function inside the cross_validate_NN function. All the Deep Learning received the same implementation and will compare. For the full implementation of the different models go to the notebook." }, { "code": null, "e": 12994, "s": 12833, "text": "When all the models computed the different folds and metrics we can easily compare them with the dataframe. On the IMDB data set the model performing better is:" }, { "code": null, "e": 13091, "s": 12994, "text": "Here I just show the results for accuracy > 80% and for accuracy, precision, and recall metrics." }, { "code": null, "e": 13186, "s": 13091, "text": "Build a function within argument a dictionary of models and concatenate all the work in a loop" }, { "code": null, "e": 13216, "s": 13186, "text": "Use distributed Deep Learning" }, { "code": null, "e": 13264, "s": 13216, "text": "Use TensorNetwork to accelerate Neural Networks" }, { "code": null, "e": 13296, "s": 13264, "text": "Use GridSearch for Hyper-tuning" }, { "code": null, "e": 13442, "s": 13296, "text": "You have now an import pipeline to made model selection for text classification with lots of parameters. All of the models are automatics. Enjoy." } ]
Haskell - Functions
Functions play a major role in Haskell, as it is a functional programming language. Like other languages, Haskell does have its own functional definition and declaration. Function declaration consists of the function name and its argument list along with its output. Function declaration consists of the function name and its argument list along with its output. Function definition is where you actually define a function. Function definition is where you actually define a function. Let us take small example of add function to understand this concept in detail. add :: Integer -> Integer -> Integer --function declaration add x y = x + y --function definition main = do putStrLn "The addition of the two numbers is:" print(add 2 5) --calling a function Here, we have declared our function in the first line and in the second line, we have written our actual function that will take two arguments and produce one integer type output. Like most other languages, Haskell starts compiling the code from the main method. Our code will generate the following output − The addition of the two numbers is: 7 Pattern Matching is process of matching specific type of expressions. It is nothing but a technique to simplify your code. This technique can be implemented into any type of Type class. If-Else can be used as an alternate option of pattern matching. Pattern Matching can be considered as a variant of dynamic polymorphism where at runtime, different methods can be executed depending on their argument list. Take a look at the following code block. Here we have used the technique of Pattern Matching to calculate the factorial of a number. fact :: Int -> Int fact 0 = 1 fact n = n * fact ( n - 1 ) main = do putStrLn "The factorial of 5 is:" print (fact 5) We all know how to calculate the factorial of a number. The compiler will start searching for a function called "fact" with an argument. If the argument is not equal to 0, then the number will keep on calling the same function with 1 less than that of the actual argument. When the pattern of the argument exactly matches with 0, it will call our pattern which is "fact 0 = 1". Our code will produce the following output − The factorial of 5 is: 120 Guards is a concept that is very similar to pattern matching. In pattern matching, we usually match one or more expressions, but we use guards to test some property of an expression. Although it is advisable to use pattern matching over guards, but from a developer’s perspective, guards is more readable and simple. For first-time users, guards can look very similar to If-Else statements, but they are functionally different. In the following code, we have modified our factorial program by using the concept of guards. fact :: Integer -> Integer fact n | n == 0 = 1 | n /= 0 = n * fact (n-1) main = do putStrLn "The factorial of 5 is:" print (fact 5) Here, we have declared two guards, separated by "|" and calling the fact function from main. Internally, the compiler will work in the same manner as in the case of pattern matching to yield the following output − The factorial of 5 is: 120 Where is a keyword or inbuilt function that can be used at runtime to generate a desired output. It can be very helpful when function calculation becomes complex. Consider a scenario where your input is a complex expression with multiple parameters. In such cases, you can break the entire expression into small parts using the "where" clause. In the following example, we are taking a complex mathematical expression. We will show how you can find the roots of a polynomial equation [x^2 - 8x + 6] using Haskell. roots :: (Float, Float, Float) -> (Float, Float) roots (a,b,c) = (x1, x2) where x1 = e + sqrt d / (2 * a) x2 = e - sqrt d / (2 * a) d = b * b - 4 * a * c e = - b / (2 * a) main = do putStrLn "The roots of our Polynomial equation are:" print (roots(1,-8,6)) Notice the complexity of our expression to calculate the roots of the given polynomial function. It is quite complex. Hence, we are breaking the expression using the where clause. The above piece of code will generate the following output − The roots of our Polynomial equation are: (7.1622777,0.8377223) Recursion is a situation where a function calls itself repeatedly. Haskell does not provide any facility of looping any expression for more than once. Instead, Haskell wants you to break your entire functionality into a collection of different functions and use recursion technique to implement your functionality. Let us consider our pattern matching example again, where we have calculated the factorial of a number. Finding the factorial of a number is a classic case of using Recursion. Here, you might, "How is pattern matching any different from recursion?” The difference between these two lie in the way they are used. Pattern matching works on setting up the terminal constrain, whereas recursion is a function call. In the following example, we have used both pattern matching and recursion to calculate the factorial of 5. fact :: Int -> Int fact 0 = 1 fact n = n * fact ( n - 1 ) main = do putStrLn "The factorial of 5 is:" print (fact 5) It will produce the following output − The factorial of 5 is: 120 Till now, what we have seen is that Haskell functions take one type as input and produce another type as output, which is pretty much similar in other imperative languages. Higher Order Functions are a unique feature of Haskell where you can use a function as an input or output argument. Although it is a virtual concept, but in real-world programs, every function that we define in Haskell use higher-order mechanism to provide output. If you get a chance to look into the library function of Haskell, then you will find that most of the library functions have been written in higher order manner. Let us take an example where we will import an inbuilt higher order function map and use the same to implement another higher order function according to our choice. import Data.Char import Prelude hiding (map) map :: (a -> b) -> [a] -> [b] map _ [] = [] map func (x : abc) = func x : map func abc main = print $ map toUpper "tutorialspoint.com" In the above example, we have used the toUpper function of the Type Class Char to convert our input into uppercase. Here, the method "map" is taking a function as an argument and returning the required output. Here is its output − sh-4.3$ ghc -O2 --make *.hs -o main -threaded -rtsopts sh-4.3$ main "TUTORIALSPOINT.COM" We sometimes have to write a function that is going to be used only once, throughout the entire lifespan of an application. To deal with this kind of situations, Haskell developers use another anonymous block known as lambda expression or lambda function. A function without having a definition is called a lambda function. A lambda function is denoted by "\" character. Let us take the following example where we will increase the input value by 1 without creating any function. main = do putStrLn "The successor of 4 is:" print ((\x -> x + 1) 4) Here, we have created an anonymous function which does not have a name. It takes the integer 4 as an argument and prints the output value. We are basically operating one function without even declaring it properly. That's the beauty of lambda expressions. Our lambda expression will produce the following output − sh-4.3$ main The successor of 4 is: 5 Print Add Notes Bookmark this page
[ { "code": null, "e": 2086, "s": 1915, "text": "Functions play a major role in Haskell, as it is a functional programming language. Like other languages, Haskell does have its own functional definition and declaration." }, { "code": null, "e": 2182, "s": 2086, "text": "Function declaration consists of the function name and its argument list along with its output." }, { "code": null, "e": 2278, "s": 2182, "text": "Function declaration consists of the function name and its argument list along with its output." }, { "code": null, "e": 2339, "s": 2278, "text": "Function definition is where you actually define a function." }, { "code": null, "e": 2400, "s": 2339, "text": "Function definition is where you actually define a function." }, { "code": null, "e": 2480, "s": 2400, "text": "Let us take small example of add function to understand this concept in detail." }, { "code": null, "e": 2712, "s": 2480, "text": "add :: Integer -> Integer -> Integer --function declaration \nadd x y = x + y --function definition \n\nmain = do \n putStrLn \"The addition of the two numbers is:\" \n print(add 2 5) --calling a function " }, { "code": null, "e": 2892, "s": 2712, "text": "Here, we have declared our function in the first line and in the second line, we have written our actual function that will take two arguments and produce one integer type output." }, { "code": null, "e": 3021, "s": 2892, "text": "Like most other languages, Haskell starts compiling the code from the main method. Our code will generate the following output −" }, { "code": null, "e": 3060, "s": 3021, "text": "The addition of the two numbers is:\n7\n" }, { "code": null, "e": 3310, "s": 3060, "text": "Pattern Matching is process of matching specific type of expressions. It is nothing but a technique to simplify your code. This technique can be implemented into any type of Type class. If-Else can be used as an alternate option of pattern matching." }, { "code": null, "e": 3468, "s": 3310, "text": "Pattern Matching can be considered as a variant of dynamic polymorphism where at runtime, different methods can be executed depending on their argument list." }, { "code": null, "e": 3601, "s": 3468, "text": "Take a look at the following code block. Here we have used the technique of Pattern Matching to calculate the factorial of a number." }, { "code": null, "e": 3730, "s": 3601, "text": "fact :: Int -> Int \nfact 0 = 1 \nfact n = n * fact ( n - 1 ) \n\nmain = do \n putStrLn \"The factorial of 5 is:\" \n print (fact 5)" }, { "code": null, "e": 4003, "s": 3730, "text": "We all know how to calculate the factorial of a number. The compiler will start searching for a function called \"fact\" with an argument. If the argument is not equal to 0, then the number will keep on calling the same function with 1 less than that of the actual argument." }, { "code": null, "e": 4153, "s": 4003, "text": "When the pattern of the argument exactly matches with 0, it will call our pattern which is \"fact 0 = 1\". Our code will produce the following output −" }, { "code": null, "e": 4181, "s": 4153, "text": "The factorial of 5 is:\n120\n" }, { "code": null, "e": 4364, "s": 4181, "text": "Guards is a concept that is very similar to pattern matching. In pattern matching, we usually match one or more expressions, but we use guards to test some property of an expression." }, { "code": null, "e": 4609, "s": 4364, "text": "Although it is advisable to use pattern matching over guards, but from a developer’s perspective, guards is more readable and simple. For first-time users, guards can look very similar to If-Else statements, but they are functionally different." }, { "code": null, "e": 4703, "s": 4609, "text": "In the following code, we have modified our factorial program by using the concept of guards." }, { "code": null, "e": 4855, "s": 4703, "text": "fact :: Integer -> Integer \nfact n | n == 0 = 1 \n | n /= 0 = n * fact (n-1) \nmain = do \n putStrLn \"The factorial of 5 is:\" \n print (fact 5) " }, { "code": null, "e": 5069, "s": 4855, "text": "Here, we have declared two guards, separated by \"|\" and calling the fact function from main. Internally, the compiler will work in the same manner as in the case of pattern matching to yield the following output −" }, { "code": null, "e": 5097, "s": 5069, "text": "The factorial of 5 is:\n120\n" }, { "code": null, "e": 5260, "s": 5097, "text": "Where is a keyword or inbuilt function that can be used at runtime to generate a desired output. It can be very helpful when function calculation becomes complex." }, { "code": null, "e": 5441, "s": 5260, "text": "Consider a scenario where your input is a complex expression with multiple parameters. In such cases, you can break the entire expression into small parts using the \"where\" clause." }, { "code": null, "e": 5611, "s": 5441, "text": "In the following example, we are taking a complex mathematical expression. We will show how you can find the roots of a polynomial equation [x^2 - 8x + 6] using Haskell." }, { "code": null, "e": 5897, "s": 5611, "text": "roots :: (Float, Float, Float) -> (Float, Float) \nroots (a,b,c) = (x1, x2) where \n x1 = e + sqrt d / (2 * a) \n x2 = e - sqrt d / (2 * a) \n d = b * b - 4 * a * c \n e = - b / (2 * a) \nmain = do \n putStrLn \"The roots of our Polynomial equation are:\" \n print (roots(1,-8,6))" }, { "code": null, "e": 6138, "s": 5897, "text": "Notice the complexity of our expression to calculate the roots of the given polynomial function. It is quite complex. Hence, we are breaking the expression using the where clause. The above piece of code will generate the following output −" }, { "code": null, "e": 6203, "s": 6138, "text": "The roots of our Polynomial equation are:\n(7.1622777,0.8377223)\n" }, { "code": null, "e": 6518, "s": 6203, "text": "Recursion is a situation where a function calls itself repeatedly. Haskell does not provide any facility of looping any expression for more than once. Instead, Haskell wants you to break your entire functionality into a collection of different functions and use recursion technique to implement your functionality." }, { "code": null, "e": 6929, "s": 6518, "text": "Let us consider our pattern matching example again, where we have calculated the factorial of a number. Finding the factorial of a number is a classic case of using Recursion. Here, you might, \"How is pattern matching any different from recursion?” The difference between these two lie in the way they are used. Pattern matching works on setting up the terminal constrain, whereas recursion is a function call." }, { "code": null, "e": 7037, "s": 6929, "text": "In the following example, we have used both pattern matching and recursion to calculate the factorial of 5." }, { "code": null, "e": 7167, "s": 7037, "text": "fact :: Int -> Int \nfact 0 = 1 \nfact n = n * fact ( n - 1 ) \n\nmain = do \n putStrLn \"The factorial of 5 is:\" \n print (fact 5) " }, { "code": null, "e": 7206, "s": 7167, "text": "It will produce the following output −" }, { "code": null, "e": 7234, "s": 7206, "text": "The factorial of 5 is:\n120\n" }, { "code": null, "e": 7523, "s": 7234, "text": "Till now, what we have seen is that Haskell functions take one type as input and produce another type as output, which is pretty much similar in other imperative languages. Higher Order Functions are a unique feature of Haskell where you can use a function as an input or output argument." }, { "code": null, "e": 7834, "s": 7523, "text": "Although it is a virtual concept, but in real-world programs, every function that we define in Haskell use higher-order mechanism to provide output. If you get a chance to look into the library function of Haskell, then you will find that most of the library functions have been written in higher order manner." }, { "code": null, "e": 8000, "s": 7834, "text": "Let us take an example where we will import an inbuilt higher order function map and use the same to implement another higher order function according to our choice." }, { "code": null, "e": 8189, "s": 8000, "text": "import Data.Char \nimport Prelude hiding (map) \n\nmap :: (a -> b) -> [a] -> [b] \nmap _ [] = [] \nmap func (x : abc) = func x : map func abc \nmain = print $ map toUpper \"tutorialspoint.com\" " }, { "code": null, "e": 8420, "s": 8189, "text": "In the above example, we have used the toUpper function of the Type Class Char to convert our input into uppercase. Here, the method \"map\" is taking a function as an argument and returning the required output. Here is its output −" }, { "code": null, "e": 8511, "s": 8420, "text": "sh-4.3$ ghc -O2 --make *.hs -o main -threaded -rtsopts\nsh-4.3$ main\n\"TUTORIALSPOINT.COM\" \n" }, { "code": null, "e": 8767, "s": 8511, "text": "We sometimes have to write a function that is going to be used only once, throughout the entire lifespan of an application. To deal with this kind of situations, Haskell developers use another anonymous block known as lambda expression or lambda function." }, { "code": null, "e": 8991, "s": 8767, "text": "A function without having a definition is called a lambda function. A lambda function is denoted by \"\\\" character. Let us take the following example where we will increase the input value by 1 without creating any function." }, { "code": null, "e": 9068, "s": 8991, "text": "main = do \n putStrLn \"The successor of 4 is:\" \n print ((\\x -> x + 1) 4)" }, { "code": null, "e": 9324, "s": 9068, "text": "Here, we have created an anonymous function which does not have a name. It takes the integer 4 as an argument and prints the output value. We are basically operating one function without even declaring it properly. That's the beauty of lambda expressions." }, { "code": null, "e": 9382, "s": 9324, "text": "Our lambda expression will produce the following output −" }, { "code": null, "e": 9421, "s": 9382, "text": "sh-4.3$ main\nThe successor of 4 is:\n5\n" }, { "code": null, "e": 9428, "s": 9421, "text": " Print" }, { "code": null, "e": 9439, "s": 9428, "text": " Add Notes" } ]
Group array by equal values JavaScript
Let’s say, we have an array of string / number literals that contains some duplicate values like this − const array = ['day', 'night', 'afternoon', 'night', 'noon', 'night', 'noon', 'day', 'afternoon', 'day', 'night']; We are required to write a function groupSimilar() that takes in this array and returns a new array where all the repeating entries are group together in a subarray as the first element and their total count in the original array as the second element. So, for this example, the output should be − [ [ 'day', 3 ], [ 'night', 4 ], [ 'afternoon', 2 ], [ 'noon', 2 ] ] Let’s write the code for this function. We will use the Array.prototype.map() function to construct a new, required, array, and we will use a Map to keep track of the repeating entries in the array − const array = ['day', 'night', 'afternoon', 'night', 'noon', 'night', 'noon', 'day', 'afternoon', 'day', 'night']; const groupSimilar = arr => { return arr.reduce((acc, val) => { const { data, map } = acc; const ind = map.get(val); if(map.has(val)){ data[ind][1]++; } else { map.set(val, data.push([val, 1])-1); } return { data, map }; }, { data: [], map: new Map() }).data; }; console.log(groupSimilar(array)); The output in the console will be − [ [ 'day', 3 ], [ 'night', 4 ], [ 'afternoon', 2 ], [ 'noon', 2 ] ]
[ { "code": null, "e": 1166, "s": 1062, "text": "Let’s say, we have an array of string / number literals that contains some duplicate values like\nthis −" }, { "code": null, "e": 1281, "s": 1166, "text": "const array = ['day', 'night', 'afternoon', 'night', 'noon', 'night', 'noon', 'day', 'afternoon', 'day', 'night'];" }, { "code": null, "e": 1534, "s": 1281, "text": "We are required to write a function groupSimilar() that takes in this array and returns a new\narray where all the repeating entries are group together in a subarray as the first element and\ntheir total count in the original array as the second element." }, { "code": null, "e": 1579, "s": 1534, "text": "So, for this example, the output should be −" }, { "code": null, "e": 1659, "s": 1579, "text": "[\n [ 'day', 3 ],\n [ 'night', 4 ],\n [ 'afternoon', 2 ],\n [ 'noon', 2 ]\n]" }, { "code": null, "e": 1859, "s": 1659, "text": "Let’s write the code for this function. We will use the Array.prototype.map() function to construct\na new, required, array, and we will use a Map to keep track of the repeating entries in the\narray −" }, { "code": null, "e": 2346, "s": 1859, "text": "const array = ['day', 'night', 'afternoon', 'night', 'noon', 'night',\n'noon', 'day', 'afternoon', 'day', 'night'];\nconst groupSimilar = arr => {\n return arr.reduce((acc, val) => {\n const { data, map } = acc;\n const ind = map.get(val);\n if(map.has(val)){\n data[ind][1]++;\n } else {\n map.set(val, data.push([val, 1])-1);\n }\n return { data, map };\n }, {\n data: [],\n map: new Map()\n }).data;\n};\nconsole.log(groupSimilar(array));" }, { "code": null, "e": 2382, "s": 2346, "text": "The output in the console will be −" }, { "code": null, "e": 2450, "s": 2382, "text": "[ [ 'day', 3 ], [ 'night', 4 ], [ 'afternoon', 2 ], [ 'noon', 2 ] ]" } ]
Check for Symmetric Binary Tree (Iterative Approach) - GeeksforGeeks
11 Mar, 2022 Given a binary tree, check whether it is a mirror of itself without recursion. Examples: Input : 1 / \ 2 2 / \ / \ 3 4 4 3 Output : Symmetric Input : 1 / \ 2 2 \ \ 3 3 Output : Not Symmetric We have discussed recursive approach to solve this problem in below post :Symmetric Tree (Mirror Image of itself)In this post, iterative approach is discussed. We use Queue here. Note that for a symmetric that elements at every level are palindromic. In example 2, at the leaf level- the elements are which is not palindromic. In other words, 1. The left child of left subtree = right child of right subtree. 2. The right child of left subtree = left child of right subtree. If we insert the left child of left subtree first followed by right child of the right subtree in the queue, we only need to ensure that these are equal. Similarly, If we insert the right child of left subtree followed by left child of the right subtree in the queue, we again need to ensure that these are equal. Below is the implementation based on above idea. C++ Java Python3 C# Javascript // C++ program to check if a given Binary// Tree is symmetric or not#include<bits/stdc++.h>using namespace std; // A Binary Tree Nodestruct Node{ int key; struct Node* left, *right;}; // Utility function to create new NodeNode *newNode(int key){ Node *temp = new Node; temp->key = key; temp->left = temp->right = NULL; return (temp);} // Returns true if a tree is symmetric// i.e. mirror image of itselfbool isSymmetric(struct Node* root){ if(root == NULL) return true; // If it is a single tree node, then // it is a symmetric tree. if(!root->left && !root->right) return true; queue <Node*> q; // Add root to queue two times so that // it can be checked if either one child // alone is NULL or not. q.push(root); q.push(root); // To store two nodes for checking their // symmetry. Node* leftNode, *rightNode; while(!q.empty()){ // Remove first two nodes to check // their symmetry. leftNode = q.front(); q.pop(); rightNode = q.front(); q.pop(); // if both left and right nodes // exist, but have different // values--> inequality, return false if(leftNode->key != rightNode->key){ return false; } // Push left child of left subtree node // and right child of right subtree // node in queue. if(leftNode->left && rightNode->right){ q.push(leftNode->left); q.push(rightNode->right); } // If only one child is present alone // and other is NULL, then tree // is not symmetric. else if (leftNode->left || rightNode->right) return false; // Push right child of left subtree node // and left child of right subtree node // in queue. if(leftNode->right && rightNode->left){ q.push(leftNode->right); q.push(rightNode->left); } // If only one child is present alone // and other is NULL, then tree // is not symmetric. else if(leftNode->right || rightNode->left) return false; } return true;} // Driver programint main(){ // Let us construct the Tree shown in // the above figure Node *root = newNode(1); root->left = newNode(2); root->right = newNode(2); root->left->left = newNode(3); root->left->right = newNode(4); root->right->left = newNode(4); root->right->right = newNode(3); if(isSymmetric(root)) cout << "The given tree is Symmetric"; else cout << "The given tree is not Symmetric"; return 0;} // This code is contributed by Nikhil jindal. // Iterative Java program to check if// given binary tree symmetricimport java.util.* ; public class BinaryTree{ Node root; static class Node { int val; Node left, right; Node(int v) { val = v; left = null; right = null; } } /* constructor to initialise the root */ BinaryTree(Node r) { root = r; } /* empty constructor */ BinaryTree() { } /* function to check if the tree is Symmetric */ public boolean isSymmetric(Node root) { /* This allows adding null elements to the queue */ Queue<Node> q = new LinkedList<Node>(); /* Initially, add left and right nodes of root */ q.add(root.left); q.add(root.right); while (!q.isEmpty()) { /* remove the front 2 nodes to check for equality */ Node tempLeft = q.remove(); Node tempRight = q.remove(); /* if both are null, continue and check for further elements */ if (tempLeft==null && tempRight==null) continue; /* if only one is null---inequality, return false */ if ((tempLeft==null && tempRight!=null) || (tempLeft!=null && tempRight==null)) return false; /* if both left and right nodes exist, but have different values-- inequality, return false*/ if (tempLeft.val != tempRight.val) return false; /* Note the order of insertion of elements to the queue : 1) left child of left subtree 2) right child of right subtree 3) right child of left subtree 4) left child of right subtree */ q.add(tempLeft.left); q.add(tempRight.right); q.add(tempLeft.right); q.add(tempRight.left); } /* if the flow reaches here, return true*/ return true; } /* driver function to test other functions */ public static void main(String[] args) { Node n = new Node(1); BinaryTree bt = new BinaryTree(n); bt.root.left = new Node(2); bt.root.right = new Node(2); bt.root.left.left = new Node(3); bt.root.left.right = new Node(4); bt.root.right.left = new Node(4); bt.root.right.right = new Node(3); if (bt.isSymmetric(bt.root)) System.out.println("The given tree is Symmetric"); else System.out.println("The given tree is not Symmetric"); }} # Python3 program to program to check if a# given Binary Tree is symmetric or not # Helper function that allocates a new# node with the given data and None# left and right pairs. class newNode: # Constructor to create a new node def __init__(self, key): self.key = key self.left = None self.right = None # function to check if a given# Binary Tree is symmetric or notdef isSymmetric( root) : # if tree is empty if (root == None) : return True # If it is a single tree node, # then it is a symmetric tree. if(not root.left and not root.right): return True q = [] # Add root to queue two times so that # it can be checked if either one # child alone is NULL or not. q.append(root) q.append(root) # To store two nodes for checking # their symmetry. leftNode = 0 rightNode = 0 while(not len(q)): # Remove first two nodes to # check their symmetry. leftNode = q[0] q.pop(0) rightNode = q[0] q.pop(0) # if both left and right nodes # exist, but have different # values-. inequality, return False if(leftNode.key != rightNode.key): return False # append left child of left subtree # node and right child of right # subtree node in queue. if(leftNode.left and rightNode.right) : q.append(leftNode.left) q.append(rightNode.right) # If only one child is present # alone and other is NULL, then # tree is not symmetric. else if (leftNode.left or rightNode.right) : return False # append right child of left subtree # node and left child of right subtree # node in queue. if(leftNode.right and rightNode.left): q.append(leftNode.right) q.append(rightNode.left) # If only one child is present # alone and other is NULL, then # tree is not symmetric. else if(leftNode.right or rightNode.left): return False return True # Driver Codeif __name__ == '__main__': # Let us construct the Tree # shown in the above figure root = newNode(1) root.left = newNode(2) root.right = newNode(2) root.left.left = newNode(3) root.left.right = newNode(4) root.right.left = newNode(4) root.right.right = newNode(3) if (isSymmetric(root)) : print("The given tree is Symmetric") else: print("The given tree is not Symmetric") # This code is contributed by# Shubham Singh(SHUBHAMSINGH10) // Iterative C# program to check if// given binary tree symmetricusing System;using System.Collections.Generic; public class BinaryTree{ public Node root; public class Node { public int val; public Node left, right; public Node(int v) { val = v; left = null; right = null; } } /* constructor to initialise the root */ BinaryTree(Node r) { root = r; } /* empty constructor */ BinaryTree() { } /* function to check if the tree is Symmetric */ public bool isSymmetric(Node root) { /* This allows adding null elements to the queue */ Queue<Node> q = new Queue<Node>(); /* Initially, add left and right nodes of root */ q.Enqueue(root.left); q.Enqueue(root.right); while (q.Count!=0) { /* remove the front 2 nodes to check for equality */ Node tempLeft = q.Dequeue(); Node tempRight = q.Dequeue(); /* if both are null, continue and check for further elements */ if (tempLeft==null && tempRight==null) continue; /* if only one is null---inequality, return false */ if ((tempLeft==null && tempRight!=null) || (tempLeft!=null && tempRight==null)) return false; /* if both left and right nodes exist, but have different values-- inequality, return false*/ if (tempLeft.val != tempRight.val) return false; /* Note the order of insertion of elements to the queue : 1) left child of left subtree 2) right child of right subtree 3) right child of left subtree 4) left child of right subtree */ q.Enqueue(tempLeft.left); q.Enqueue(tempRight.right); q.Enqueue(tempLeft.right); q.Enqueue(tempRight.left); } /* if the flow reaches here, return true*/ return true; } /* driver code */ public static void Main(String[] args) { Node n = new Node(1); BinaryTree bt = new BinaryTree(n); bt.root.left = new Node(2); bt.root.right = new Node(2); bt.root.left.left = new Node(3); bt.root.left.right = new Node(4); bt.root.right.left = new Node(4); bt.root.right.right = new Node(3); if (bt.isSymmetric(bt.root)) Console.WriteLine("The given tree is Symmetric"); else Console.WriteLine("The given tree is not Symmetric"); }} // This code is contributed by PrinciRaj1992 <script> // Iterative Javascript program to check if// given binary tree symmetricvar root = null; class Node{ constructor(v) { this.val = v; this.left = null; this.right = null; }} /* Function to check if the tree is Symmetric */function isSymmetric(root){ /* This allows adding null elements to the queue */ var q = []; /* Initially, add left and right nodes of root */ q.push(root.left); q.push(root.right); while (q.length != 0) { /* Remove the front 2 nodes to check for equality */ var tempLeft = q[0]; q.shift(); var tempRight = q[0]; q.shift(); /* If both are null, continue and check for further elements */ if (tempLeft == null && tempRight == null) continue; /* If only one is null---inequality, return false */ if ((tempLeft == null && tempRight != null) || (tempLeft != null && tempRight == null)) return false; /* If both left and right nodes exist, but have different values-- inequality, return false*/ if (tempLeft.val != tempRight.val) return false; /* Note the order of insertion of elements to the queue : 1) left child of left subtree 2) right child of right subtree 3) right child of left subtree 4) left child of right subtree */ q.push(tempLeft.left); q.push(tempRight.right); q.push(tempLeft.right); q.push(tempRight.left); } /* If the flow reaches here, return true*/ return true;} // Driver codevar n = new Node(1);root = n;root.left = new Node(2);root.right = new Node(2);root.left.left = new Node(3);root.left.right = new Node(4);root.right.left = new Node(4);root.right.right = new Node(3); if (isSymmetric(root)) document.write("The given tree is Symmetric");else document.write("The given tree is not Symmetric"); // This code is contributed by noob2000 </script> Output: The given tree is Symmetric YouTubeGeeksforGeeks500K subscribersCheck for Symmetric Binary Tree (Iterative Approach) | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:57•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=7yXBnlHZ0tY" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> This article is contributed by Saloni Baweja. 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. nik1996 SHUBHAMSINGH10 princiraj1992 bhanuchand noob2000 simranarora5sos sooda367 simmytarika5 Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Inorder Tree Traversal without Recursion Binary Tree | Set 3 (Types of Binary Tree) Binary Tree | Set 2 (Properties) Decision Tree Inorder Tree Traversal without recursion and without stack! Construct Tree from given Inorder and Preorder traversals Complexity of different operations in Binary tree, Binary Search Tree and AVL tree Introduction to Tree Data Structure Lowest Common Ancestor in a Binary Tree | Set 1 Binary Tree (Array implementation)
[ { "code": null, "e": 24945, "s": 24917, "text": "\n11 Mar, 2022" }, { "code": null, "e": 25024, "s": 24945, "text": "Given a binary tree, check whether it is a mirror of itself without recursion." }, { "code": null, "e": 25035, "s": 25024, "text": "Examples: " }, { "code": null, "e": 25201, "s": 25035, "text": "Input : \n \n 1\n / \\\n 2 2\n / \\ / \\\n3 4 4 3\n\nOutput : Symmetric\n\nInput : \n \n 1\n / \\\n 2 2\n \\ \\\n 3 3\n\nOutput : Not Symmetric" }, { "code": null, "e": 25990, "s": 25201, "text": "We have discussed recursive approach to solve this problem in below post :Symmetric Tree (Mirror Image of itself)In this post, iterative approach is discussed. We use Queue here. Note that for a symmetric that elements at every level are palindromic. In example 2, at the leaf level- the elements are which is not palindromic. In other words, 1. The left child of left subtree = right child of right subtree. 2. The right child of left subtree = left child of right subtree. If we insert the left child of left subtree first followed by right child of the right subtree in the queue, we only need to ensure that these are equal. Similarly, If we insert the right child of left subtree followed by left child of the right subtree in the queue, we again need to ensure that these are equal." }, { "code": null, "e": 26040, "s": 25990, "text": "Below is the implementation based on above idea. " }, { "code": null, "e": 26044, "s": 26040, "text": "C++" }, { "code": null, "e": 26049, "s": 26044, "text": "Java" }, { "code": null, "e": 26057, "s": 26049, "text": "Python3" }, { "code": null, "e": 26060, "s": 26057, "text": "C#" }, { "code": null, "e": 26071, "s": 26060, "text": "Javascript" }, { "code": "// C++ program to check if a given Binary// Tree is symmetric or not#include<bits/stdc++.h>using namespace std; // A Binary Tree Nodestruct Node{ int key; struct Node* left, *right;}; // Utility function to create new NodeNode *newNode(int key){ Node *temp = new Node; temp->key = key; temp->left = temp->right = NULL; return (temp);} // Returns true if a tree is symmetric// i.e. mirror image of itselfbool isSymmetric(struct Node* root){ if(root == NULL) return true; // If it is a single tree node, then // it is a symmetric tree. if(!root->left && !root->right) return true; queue <Node*> q; // Add root to queue two times so that // it can be checked if either one child // alone is NULL or not. q.push(root); q.push(root); // To store two nodes for checking their // symmetry. Node* leftNode, *rightNode; while(!q.empty()){ // Remove first two nodes to check // their symmetry. leftNode = q.front(); q.pop(); rightNode = q.front(); q.pop(); // if both left and right nodes // exist, but have different // values--> inequality, return false if(leftNode->key != rightNode->key){ return false; } // Push left child of left subtree node // and right child of right subtree // node in queue. if(leftNode->left && rightNode->right){ q.push(leftNode->left); q.push(rightNode->right); } // If only one child is present alone // and other is NULL, then tree // is not symmetric. else if (leftNode->left || rightNode->right) return false; // Push right child of left subtree node // and left child of right subtree node // in queue. if(leftNode->right && rightNode->left){ q.push(leftNode->right); q.push(rightNode->left); } // If only one child is present alone // and other is NULL, then tree // is not symmetric. else if(leftNode->right || rightNode->left) return false; } return true;} // Driver programint main(){ // Let us construct the Tree shown in // the above figure Node *root = newNode(1); root->left = newNode(2); root->right = newNode(2); root->left->left = newNode(3); root->left->right = newNode(4); root->right->left = newNode(4); root->right->right = newNode(3); if(isSymmetric(root)) cout << \"The given tree is Symmetric\"; else cout << \"The given tree is not Symmetric\"; return 0;} // This code is contributed by Nikhil jindal.", "e": 28806, "s": 26071, "text": null }, { "code": "// Iterative Java program to check if// given binary tree symmetricimport java.util.* ; public class BinaryTree{ Node root; static class Node { int val; Node left, right; Node(int v) { val = v; left = null; right = null; } } /* constructor to initialise the root */ BinaryTree(Node r) { root = r; } /* empty constructor */ BinaryTree() { } /* function to check if the tree is Symmetric */ public boolean isSymmetric(Node root) { /* This allows adding null elements to the queue */ Queue<Node> q = new LinkedList<Node>(); /* Initially, add left and right nodes of root */ q.add(root.left); q.add(root.right); while (!q.isEmpty()) { /* remove the front 2 nodes to check for equality */ Node tempLeft = q.remove(); Node tempRight = q.remove(); /* if both are null, continue and check for further elements */ if (tempLeft==null && tempRight==null) continue; /* if only one is null---inequality, return false */ if ((tempLeft==null && tempRight!=null) || (tempLeft!=null && tempRight==null)) return false; /* if both left and right nodes exist, but have different values-- inequality, return false*/ if (tempLeft.val != tempRight.val) return false; /* Note the order of insertion of elements to the queue : 1) left child of left subtree 2) right child of right subtree 3) right child of left subtree 4) left child of right subtree */ q.add(tempLeft.left); q.add(tempRight.right); q.add(tempLeft.right); q.add(tempRight.left); } /* if the flow reaches here, return true*/ return true; } /* driver function to test other functions */ public static void main(String[] args) { Node n = new Node(1); BinaryTree bt = new BinaryTree(n); bt.root.left = new Node(2); bt.root.right = new Node(2); bt.root.left.left = new Node(3); bt.root.left.right = new Node(4); bt.root.right.left = new Node(4); bt.root.right.right = new Node(3); if (bt.isSymmetric(bt.root)) System.out.println(\"The given tree is Symmetric\"); else System.out.println(\"The given tree is not Symmetric\"); }}", "e": 31399, "s": 28806, "text": null }, { "code": "# Python3 program to program to check if a# given Binary Tree is symmetric or not # Helper function that allocates a new# node with the given data and None# left and right pairs. class newNode: # Constructor to create a new node def __init__(self, key): self.key = key self.left = None self.right = None # function to check if a given# Binary Tree is symmetric or notdef isSymmetric( root) : # if tree is empty if (root == None) : return True # If it is a single tree node, # then it is a symmetric tree. if(not root.left and not root.right): return True q = [] # Add root to queue two times so that # it can be checked if either one # child alone is NULL or not. q.append(root) q.append(root) # To store two nodes for checking # their symmetry. leftNode = 0 rightNode = 0 while(not len(q)): # Remove first two nodes to # check their symmetry. leftNode = q[0] q.pop(0) rightNode = q[0] q.pop(0) # if both left and right nodes # exist, but have different # values-. inequality, return False if(leftNode.key != rightNode.key): return False # append left child of left subtree # node and right child of right # subtree node in queue. if(leftNode.left and rightNode.right) : q.append(leftNode.left) q.append(rightNode.right) # If only one child is present # alone and other is NULL, then # tree is not symmetric. else if (leftNode.left or rightNode.right) : return False # append right child of left subtree # node and left child of right subtree # node in queue. if(leftNode.right and rightNode.left): q.append(leftNode.right) q.append(rightNode.left) # If only one child is present # alone and other is NULL, then # tree is not symmetric. else if(leftNode.right or rightNode.left): return False return True # Driver Codeif __name__ == '__main__': # Let us construct the Tree # shown in the above figure root = newNode(1) root.left = newNode(2) root.right = newNode(2) root.left.left = newNode(3) root.left.right = newNode(4) root.right.left = newNode(4) root.right.right = newNode(3) if (isSymmetric(root)) : print(\"The given tree is Symmetric\") else: print(\"The given tree is not Symmetric\") # This code is contributed by# Shubham Singh(SHUBHAMSINGH10)", "e": 34097, "s": 31399, "text": null }, { "code": "// Iterative C# program to check if// given binary tree symmetricusing System;using System.Collections.Generic; public class BinaryTree{ public Node root; public class Node { public int val; public Node left, right; public Node(int v) { val = v; left = null; right = null; } } /* constructor to initialise the root */ BinaryTree(Node r) { root = r; } /* empty constructor */ BinaryTree() { } /* function to check if the tree is Symmetric */ public bool isSymmetric(Node root) { /* This allows adding null elements to the queue */ Queue<Node> q = new Queue<Node>(); /* Initially, add left and right nodes of root */ q.Enqueue(root.left); q.Enqueue(root.right); while (q.Count!=0) { /* remove the front 2 nodes to check for equality */ Node tempLeft = q.Dequeue(); Node tempRight = q.Dequeue(); /* if both are null, continue and check for further elements */ if (tempLeft==null && tempRight==null) continue; /* if only one is null---inequality, return false */ if ((tempLeft==null && tempRight!=null) || (tempLeft!=null && tempRight==null)) return false; /* if both left and right nodes exist, but have different values-- inequality, return false*/ if (tempLeft.val != tempRight.val) return false; /* Note the order of insertion of elements to the queue : 1) left child of left subtree 2) right child of right subtree 3) right child of left subtree 4) left child of right subtree */ q.Enqueue(tempLeft.left); q.Enqueue(tempRight.right); q.Enqueue(tempLeft.right); q.Enqueue(tempRight.left); } /* if the flow reaches here, return true*/ return true; } /* driver code */ public static void Main(String[] args) { Node n = new Node(1); BinaryTree bt = new BinaryTree(n); bt.root.left = new Node(2); bt.root.right = new Node(2); bt.root.left.left = new Node(3); bt.root.left.right = new Node(4); bt.root.right.left = new Node(4); bt.root.right.right = new Node(3); if (bt.isSymmetric(bt.root)) Console.WriteLine(\"The given tree is Symmetric\"); else Console.WriteLine(\"The given tree is not Symmetric\"); }} // This code is contributed by PrinciRaj1992", "e": 36745, "s": 34097, "text": null }, { "code": "<script> // Iterative Javascript program to check if// given binary tree symmetricvar root = null; class Node{ constructor(v) { this.val = v; this.left = null; this.right = null; }} /* Function to check if the tree is Symmetric */function isSymmetric(root){ /* This allows adding null elements to the queue */ var q = []; /* Initially, add left and right nodes of root */ q.push(root.left); q.push(root.right); while (q.length != 0) { /* Remove the front 2 nodes to check for equality */ var tempLeft = q[0]; q.shift(); var tempRight = q[0]; q.shift(); /* If both are null, continue and check for further elements */ if (tempLeft == null && tempRight == null) continue; /* If only one is null---inequality, return false */ if ((tempLeft == null && tempRight != null) || (tempLeft != null && tempRight == null)) return false; /* If both left and right nodes exist, but have different values-- inequality, return false*/ if (tempLeft.val != tempRight.val) return false; /* Note the order of insertion of elements to the queue : 1) left child of left subtree 2) right child of right subtree 3) right child of left subtree 4) left child of right subtree */ q.push(tempLeft.left); q.push(tempRight.right); q.push(tempLeft.right); q.push(tempRight.left); } /* If the flow reaches here, return true*/ return true;} // Driver codevar n = new Node(1);root = n;root.left = new Node(2);root.right = new Node(2);root.left.left = new Node(3);root.left.right = new Node(4);root.right.left = new Node(4);root.right.right = new Node(3); if (isSymmetric(root)) document.write(\"The given tree is Symmetric\");else document.write(\"The given tree is not Symmetric\"); // This code is contributed by noob2000 </script>", "e": 38810, "s": 36745, "text": null }, { "code": null, "e": 38819, "s": 38810, "text": "Output: " }, { "code": null, "e": 38847, "s": 38819, "text": "The given tree is Symmetric" }, { "code": null, "e": 39698, "s": 38847, "text": "YouTubeGeeksforGeeks500K subscribersCheck for Symmetric Binary Tree (Iterative Approach) | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:57•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=7yXBnlHZ0tY\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 40119, "s": 39698, "text": "This article is contributed by Saloni Baweja. 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": 40127, "s": 40119, "text": "nik1996" }, { "code": null, "e": 40142, "s": 40127, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 40156, "s": 40142, "text": "princiraj1992" }, { "code": null, "e": 40167, "s": 40156, "text": "bhanuchand" }, { "code": null, "e": 40176, "s": 40167, "text": "noob2000" }, { "code": null, "e": 40192, "s": 40176, "text": "simranarora5sos" }, { "code": null, "e": 40201, "s": 40192, "text": "sooda367" }, { "code": null, "e": 40214, "s": 40201, "text": "simmytarika5" }, { "code": null, "e": 40219, "s": 40214, "text": "Tree" }, { "code": null, "e": 40224, "s": 40219, "text": "Tree" }, { "code": null, "e": 40322, "s": 40224, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40331, "s": 40322, "text": "Comments" }, { "code": null, "e": 40344, "s": 40331, "text": "Old Comments" }, { "code": null, "e": 40385, "s": 40344, "text": "Inorder Tree Traversal without Recursion" }, { "code": null, "e": 40428, "s": 40385, "text": "Binary Tree | Set 3 (Types of Binary Tree)" }, { "code": null, "e": 40461, "s": 40428, "text": "Binary Tree | Set 2 (Properties)" }, { "code": null, "e": 40475, "s": 40461, "text": "Decision Tree" }, { "code": null, "e": 40535, "s": 40475, "text": "Inorder Tree Traversal without recursion and without stack!" }, { "code": null, "e": 40593, "s": 40535, "text": "Construct Tree from given Inorder and Preorder traversals" }, { "code": null, "e": 40676, "s": 40593, "text": "Complexity of different operations in Binary tree, Binary Search Tree and AVL tree" }, { "code": null, "e": 40712, "s": 40676, "text": "Introduction to Tree Data Structure" }, { "code": null, "e": 40760, "s": 40712, "text": "Lowest Common Ancestor in a Binary Tree | Set 1" } ]
Detecting Spam in Emails. Applying NLP and Deep Learning for Spam... | by Ramya Vidiyala | Towards Data Science
Have you ever wondered how a machine translates language? Or how voice assistants respond to questions? Or how mail gets automatically classified into spam or not spam? All these tasks are done through Natural Language Processing (NLP), which processes text into useful insights that can be applied to future data. In the field of artificial intelligence, NLP is one of the most complex areas of research due to the fact that text data is contextual. It needs modification to make it machine-interpretable and requires multiple stages of processing for feature extraction. Classification problems can be broadly split into two categories: binary classification problems, and multi-class classification problems. Binary classification means there are only two possible label classes, e.g. a patient’s condition is cancerous or it isn’t, or a financial transaction is fraudulent or it is not. Multi-class classification refers to cases where there are more than two label classes. An example of this is classifying the sentiment of a movie review into positive, negative, or neutral. There are many types of NLP problems, and one of the most common types is the classification of strings. Examples of this include the classification of movies/news articles into different genres and the automated classification of emails into a spam or not spam. I’ll be looking into this last example in more detail for this article. Understanding the problem is a crucial first step in solving any machine learning problem. In this article, we will explore and understand the process of classifying emails as spam or not spam. This is called Spam Detection, and it is a binary classification problem. The reason to do this is simple: by detecting unsolicited and unwanted emails, we can prevent spam messages from creeping into the user’s inbox, thereby improving user experience. Let’s start with our spam detection data. We’ll be using the open-source Spambase dataset from the UCI machine learning repository, a dataset that contains 5569 emails, of which 745 are spam. The target variable for this dataset is ‘spam’ in which a spam email is mapped to 1 and anything else is mapped to 0. The target variable can be thought of as what you are trying to predict. In machine learning problems, the value of this variable will be modeled and predicted by other variables. A snapshot of the data is presented in figure 1. Task: To classify an email into the spam or not spam. To get to our solution we need to understand the four processing concepts below. Please note that the concepts discussed here can also be applied to other text classification problems. Text ProcessingText SequencingModel SelectionImplementation Text Processing Text Sequencing Model Selection Implementation Data usually comes from a variety of sources and often in different formats. For this reason, transforming your raw data is essential. However, this transformation is not a simple process, as text data often contain redundant and repetitive words. This means that processing the text data is the first step in our solution. The fundamental steps involved in text preprocessing are A. Cleaning the raw dataB. Tokenizing the cleaned data This phase involves the deletion of words or characters that do not add value to the meaning of the text. Some of the standard cleaning steps are listed below: Lowering case Removal of special characters Removal of stopwords Removal of hyperlinks Removal of numbers Removal of whitespaces Lowering the case of text is essential for the following reasons: The words, ‘TEXT’, ‘Text’, ‘text’ all add the same value to a sentence Lowering the case of all the words is very helpful for reducing the dimensions by decreasing the size of the vocabulary def to_lower(word): result = word.lower() return result This is another text processing technique that will help to treat words like ‘hurray’ and ‘hurray!’ in the same way. def remove_special_characters(word): result=word.translate(str.maketrans(dict.fromkeys(string.punctuation))) return result Stopwords are commonly occurring words in a language like ‘the’, ‘a’, and so on. Most of the time they can be removed from the text because they don’t provide valuable information. def remove_stop_words(words): result = [i for i in words if i not in ENGLISH_STOP_WORDS] return result Next, we remove any URLs in the data. There is a good chance that email will have some URLs in it. We don’t need them for our further analysis as they do not add any value to the results. def remove_hyperlink(word): return re.sub(r"http\S+", "", word) For more details on text preprocessing techniques, check out the article below. towardsdatascience.com Tokenization is the process of splitting text into smaller chunks, called tokens. Each token is an input to the machine learning algorithm as a feature. keras.preprocessing.text.Tokenizer is a utility function that tokenizes a text into tokens while keeping only the words that occur the most in the text corpus. When we tokenize the text, we end up with a massive dictionary of words, and they won’t all be essential. We can set ‘max_features’ to select the top frequent words that we want to consider. max_feature = 50000 #number of unique words to considerfrom keras.preprocessing.text import Tokenizertokenizer = Tokenizer(num_words=max_feature)tokenizer.fit_on_texts(x_train)x_train_features = np.array(tokenizer.texts_to_sequences(x_train))x_test_features = np.array(tokenizer.texts_to_sequences(x_test)) Making the tokens for all emails an equal size is called padding. We send input in batches of data points. Information might be lost when inputs are of different sizes. So, we make them the same size using padding, and that eases batch updates. The length of all tokenized emails post-padding is set using ‘max_len’. Code snippet for padding : from keras.preprocessing.sequence import pad_sequencesx_train_features = pad_sequences(x_train_features,maxlen=max_len)x_test_features = pad_sequences(x_test_features,maxlen=max_len) The model will expect the target variable as a number and not a string. We can use a Label encoder from sklearn, to convert our target variable as below. from sklearn.preprocessing import LabelEncoderle = LabelEncoder()train_y = le.fit_transform(target_train.values)test_y = le.transform(target_test.values) A movie consists of a sequence of scenes. When we watch a particular scene, we don’t try to understand it in isolation, but rather in connection with previous scenes. In a similar fashion, a machine learning model has to understand the text by utilizing already-learned text, just like in a human neural network. In traditional machine learning models, we cannot store a model’s previous stages. However, Recurrent Neural Networks (commonly called RNN) can do this for us. Let’s take a closer look at RNNs below. An RNN has a repeating module that takes input from the previous stage and gives its output as input to the next stage. However, in RNNs we can only retain information from the most recent stage. To learn long-term dependencies, our network needs memorization power. Here’s where Long Short Term Memory Networks (LSTMs) come to the rescue. LSTMs are a special case of RNNs, They have the same chain-like structure as RNNs, but with a different repeating module structure. To perform LSTM even in reverse order, we’ll use a Bi-directional LSTM. Text data can be easily interpreted by humans. But for machines, reading and analyzing is a very complex task. To accomplish this task, we need to convert our text into a machine-understandable format. Embedding is the process of converting formatted text data into numerical values/vectors which a machine can interpret. import tensorflow as tffrom keras.layers import Dense,LSTM, Embedding, Dropout, Activation, Bidirectional#size of the output vector from each layerembedding_vector_length = 32#Creating a sequential modelmodel = tf.keras.Sequential()#Creating an embedding layer to vectorizemodel.add(Embedding(max_feature, embedding_vector_length, input_length=max_len))#Addding Bi-directional LSTMmodel.add(Bidirectional(tf.keras.layers.LSTM(64)))#Relu allows converging quickly and allows backpropagationmodel.add(Dense(16, activation='relu'))#Deep Learninng models can be overfit easily, to avoid this, we add randomization using drop outmodel.add(Dropout(0.1))#Adding sigmoid activation function to normalize the outputmodel.add(Dense(1, activation='sigmoid'))model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])print(model.summary()) history = model.fit(x_train_features, train_y, batch_size=512, epochs=20, validation_data=(x_test_features, test_y))y_predict = [1 if o>0.5 else 0 for o in model.predict(x_test_features)] Through the above, we have successfully fit a bi-directional LSTM model on our email data and detected 125 of 1114 emails as spam. Since the percentage of spam in data is often low, Measuring the model’s performance by accuracy alone is not recommended. We need to evaluate it using other performance metrics as well, which we’ll look at below. Precision and recall are the two most widely used performance metrics for a classification problem to get a better understanding of the problem. Precision is the fraction of the relevant instances from all the retrieved instances. Precision helps us to understand how useful the results are. The recall is the fraction of relevant instances from all the relevant instances. Recall helps us understand how complete the results are. The F1 Score is the harmonic mean of precision and recall. For example, consider that a search query results in 30 pages, of which 20 are relevant, but the results fail to display 40 other relevant results. In this case, the precision is 20/30, and recall is 20/60. Therefore, our F1 Score is 4/9. Using F1-score as a performance metric for spam detection problems is a good choice. from sklearn.metrics import confusion_matrix,f1_score, precision_score,recall_scorecf_matrix =confusion_matrix(test_y,y_predict)tn, fp, fn, tp = confusion_matrix(test_y,y_predict).ravel()print("Precision: {:.2f}%".format(100 * precision_score(test_y, y_predict)))print("Recall: {:.2f}%".format(100 * recall_score(test_y, y_predict)))print("F1 Score: {:.2f}%".format(100 * f1_score(test_y,y_predict))) import seaborn as snsimport matplotlib.pyplot as pltax= plt.subplot()#annot=True to annotate cellssns.heatmap(cf_matrix, annot=True, ax = ax,cmap='Blues',fmt='');# labels, title and ticksax.set_xlabel('Predicted labels');ax.set_ylabel('True labels');ax.set_title('Confusion Matrix');ax.xaxis.set_ticklabels(['Not Spam', 'Spam']); ax.yaxis.set_ticklabels(['Not Spam', 'Spam']); A model with an F1 score of 95% is a good-to-go model. Keep in mind, however, that these results are based on the training data we used. When applying a model like this to real-world data, we still need to actively monitor the model’s performance over time. We can also continue to improve the model by responding to results and feedback by doing things like adding features and removing misspelled words. In this article, we created a spam detection model by converting text data into vectors, creating a BiLSTM model, and fitting the model with the vectors. We also explored a variety of text processing techniques, text sequencing techniques, and deep learning models, namely RNN, LSTM, BiLSTM. The concepts and techniques learned in this article can be applied to a variety of natural language processing problems like building chatbots, text summarization, language translation models. If you would like to experiment with the custom dataset yourself, you can download the annotated data on UCI machine learning repository and the code at Github. This article is originally published on Lionbridge.ai. Thanks for the read. I am going to write more beginner-friendly posts in the future too. Follow me up on Medium to be informed about them. I welcome feedback and can be reached out on Twitter ramya_vidiyala and LinkedIn RamyaVidiyala. Happy learning!
[ { "code": null, "e": 340, "s": 171, "text": "Have you ever wondered how a machine translates language? Or how voice assistants respond to questions? Or how mail gets automatically classified into spam or not spam?" }, { "code": null, "e": 744, "s": 340, "text": "All these tasks are done through Natural Language Processing (NLP), which processes text into useful insights that can be applied to future data. In the field of artificial intelligence, NLP is one of the most complex areas of research due to the fact that text data is contextual. It needs modification to make it machine-interpretable and requires multiple stages of processing for feature extraction." }, { "code": null, "e": 1253, "s": 744, "text": "Classification problems can be broadly split into two categories: binary classification problems, and multi-class classification problems. Binary classification means there are only two possible label classes, e.g. a patient’s condition is cancerous or it isn’t, or a financial transaction is fraudulent or it is not. Multi-class classification refers to cases where there are more than two label classes. An example of this is classifying the sentiment of a movie review into positive, negative, or neutral." }, { "code": null, "e": 1588, "s": 1253, "text": "There are many types of NLP problems, and one of the most common types is the classification of strings. Examples of this include the classification of movies/news articles into different genres and the automated classification of emails into a spam or not spam. I’ll be looking into this last example in more detail for this article." }, { "code": null, "e": 1856, "s": 1588, "text": "Understanding the problem is a crucial first step in solving any machine learning problem. In this article, we will explore and understand the process of classifying emails as spam or not spam. This is called Spam Detection, and it is a binary classification problem." }, { "code": null, "e": 2036, "s": 1856, "text": "The reason to do this is simple: by detecting unsolicited and unwanted emails, we can prevent spam messages from creeping into the user’s inbox, thereby improving user experience." }, { "code": null, "e": 2228, "s": 2036, "text": "Let’s start with our spam detection data. We’ll be using the open-source Spambase dataset from the UCI machine learning repository, a dataset that contains 5569 emails, of which 745 are spam." }, { "code": null, "e": 2526, "s": 2228, "text": "The target variable for this dataset is ‘spam’ in which a spam email is mapped to 1 and anything else is mapped to 0. The target variable can be thought of as what you are trying to predict. In machine learning problems, the value of this variable will be modeled and predicted by other variables." }, { "code": null, "e": 2575, "s": 2526, "text": "A snapshot of the data is presented in figure 1." }, { "code": null, "e": 2629, "s": 2575, "text": "Task: To classify an email into the spam or not spam." }, { "code": null, "e": 2814, "s": 2629, "text": "To get to our solution we need to understand the four processing concepts below. Please note that the concepts discussed here can also be applied to other text classification problems." }, { "code": null, "e": 2874, "s": 2814, "text": "Text ProcessingText SequencingModel SelectionImplementation" }, { "code": null, "e": 2890, "s": 2874, "text": "Text Processing" }, { "code": null, "e": 2906, "s": 2890, "text": "Text Sequencing" }, { "code": null, "e": 2922, "s": 2906, "text": "Model Selection" }, { "code": null, "e": 2937, "s": 2922, "text": "Implementation" }, { "code": null, "e": 3261, "s": 2937, "text": "Data usually comes from a variety of sources and often in different formats. For this reason, transforming your raw data is essential. However, this transformation is not a simple process, as text data often contain redundant and repetitive words. This means that processing the text data is the first step in our solution." }, { "code": null, "e": 3318, "s": 3261, "text": "The fundamental steps involved in text preprocessing are" }, { "code": null, "e": 3373, "s": 3318, "text": "A. Cleaning the raw dataB. Tokenizing the cleaned data" }, { "code": null, "e": 3533, "s": 3373, "text": "This phase involves the deletion of words or characters that do not add value to the meaning of the text. Some of the standard cleaning steps are listed below:" }, { "code": null, "e": 3547, "s": 3533, "text": "Lowering case" }, { "code": null, "e": 3577, "s": 3547, "text": "Removal of special characters" }, { "code": null, "e": 3598, "s": 3577, "text": "Removal of stopwords" }, { "code": null, "e": 3620, "s": 3598, "text": "Removal of hyperlinks" }, { "code": null, "e": 3639, "s": 3620, "text": "Removal of numbers" }, { "code": null, "e": 3662, "s": 3639, "text": "Removal of whitespaces" }, { "code": null, "e": 3728, "s": 3662, "text": "Lowering the case of text is essential for the following reasons:" }, { "code": null, "e": 3799, "s": 3728, "text": "The words, ‘TEXT’, ‘Text’, ‘text’ all add the same value to a sentence" }, { "code": null, "e": 3919, "s": 3799, "text": "Lowering the case of all the words is very helpful for reducing the dimensions by decreasing the size of the vocabulary" }, { "code": null, "e": 3981, "s": 3919, "text": "def to_lower(word): result = word.lower() return result" }, { "code": null, "e": 4098, "s": 3981, "text": "This is another text processing technique that will help to treat words like ‘hurray’ and ‘hurray!’ in the same way." }, { "code": null, "e": 4227, "s": 4098, "text": "def remove_special_characters(word): result=word.translate(str.maketrans(dict.fromkeys(string.punctuation))) return result" }, { "code": null, "e": 4408, "s": 4227, "text": "Stopwords are commonly occurring words in a language like ‘the’, ‘a’, and so on. Most of the time they can be removed from the text because they don’t provide valuable information." }, { "code": null, "e": 4517, "s": 4408, "text": "def remove_stop_words(words): result = [i for i in words if i not in ENGLISH_STOP_WORDS] return result" }, { "code": null, "e": 4705, "s": 4517, "text": "Next, we remove any URLs in the data. There is a good chance that email will have some URLs in it. We don’t need them for our further analysis as they do not add any value to the results." }, { "code": null, "e": 4772, "s": 4705, "text": "def remove_hyperlink(word): return re.sub(r\"http\\S+\", \"\", word)" }, { "code": null, "e": 4852, "s": 4772, "text": "For more details on text preprocessing techniques, check out the article below." }, { "code": null, "e": 4875, "s": 4852, "text": "towardsdatascience.com" }, { "code": null, "e": 5028, "s": 4875, "text": "Tokenization is the process of splitting text into smaller chunks, called tokens. Each token is an input to the machine learning algorithm as a feature." }, { "code": null, "e": 5379, "s": 5028, "text": "keras.preprocessing.text.Tokenizer is a utility function that tokenizes a text into tokens while keeping only the words that occur the most in the text corpus. When we tokenize the text, we end up with a massive dictionary of words, and they won’t all be essential. We can set ‘max_features’ to select the top frequent words that we want to consider." }, { "code": null, "e": 5686, "s": 5379, "text": "max_feature = 50000 #number of unique words to considerfrom keras.preprocessing.text import Tokenizertokenizer = Tokenizer(num_words=max_feature)tokenizer.fit_on_texts(x_train)x_train_features = np.array(tokenizer.texts_to_sequences(x_train))x_test_features = np.array(tokenizer.texts_to_sequences(x_test))" }, { "code": null, "e": 5752, "s": 5686, "text": "Making the tokens for all emails an equal size is called padding." }, { "code": null, "e": 5931, "s": 5752, "text": "We send input in batches of data points. Information might be lost when inputs are of different sizes. So, we make them the same size using padding, and that eases batch updates." }, { "code": null, "e": 6003, "s": 5931, "text": "The length of all tokenized emails post-padding is set using ‘max_len’." }, { "code": null, "e": 6030, "s": 6003, "text": "Code snippet for padding :" }, { "code": null, "e": 6213, "s": 6030, "text": "from keras.preprocessing.sequence import pad_sequencesx_train_features = pad_sequences(x_train_features,maxlen=max_len)x_test_features = pad_sequences(x_test_features,maxlen=max_len)" }, { "code": null, "e": 6367, "s": 6213, "text": "The model will expect the target variable as a number and not a string. We can use a Label encoder from sklearn, to convert our target variable as below." }, { "code": null, "e": 6521, "s": 6367, "text": "from sklearn.preprocessing import LabelEncoderle = LabelEncoder()train_y = le.fit_transform(target_train.values)test_y = le.transform(target_test.values)" }, { "code": null, "e": 6834, "s": 6521, "text": "A movie consists of a sequence of scenes. When we watch a particular scene, we don’t try to understand it in isolation, but rather in connection with previous scenes. In a similar fashion, a machine learning model has to understand the text by utilizing already-learned text, just like in a human neural network." }, { "code": null, "e": 7034, "s": 6834, "text": "In traditional machine learning models, we cannot store a model’s previous stages. However, Recurrent Neural Networks (commonly called RNN) can do this for us. Let’s take a closer look at RNNs below." }, { "code": null, "e": 7374, "s": 7034, "text": "An RNN has a repeating module that takes input from the previous stage and gives its output as input to the next stage. However, in RNNs we can only retain information from the most recent stage. To learn long-term dependencies, our network needs memorization power. Here’s where Long Short Term Memory Networks (LSTMs) come to the rescue." }, { "code": null, "e": 7506, "s": 7374, "text": "LSTMs are a special case of RNNs, They have the same chain-like structure as RNNs, but with a different repeating module structure." }, { "code": null, "e": 7578, "s": 7506, "text": "To perform LSTM even in reverse order, we’ll use a Bi-directional LSTM." }, { "code": null, "e": 7780, "s": 7578, "text": "Text data can be easily interpreted by humans. But for machines, reading and analyzing is a very complex task. To accomplish this task, we need to convert our text into a machine-understandable format." }, { "code": null, "e": 7900, "s": 7780, "text": "Embedding is the process of converting formatted text data into numerical values/vectors which a machine can interpret." }, { "code": null, "e": 8751, "s": 7900, "text": "import tensorflow as tffrom keras.layers import Dense,LSTM, Embedding, Dropout, Activation, Bidirectional#size of the output vector from each layerembedding_vector_length = 32#Creating a sequential modelmodel = tf.keras.Sequential()#Creating an embedding layer to vectorizemodel.add(Embedding(max_feature, embedding_vector_length, input_length=max_len))#Addding Bi-directional LSTMmodel.add(Bidirectional(tf.keras.layers.LSTM(64)))#Relu allows converging quickly and allows backpropagationmodel.add(Dense(16, activation='relu'))#Deep Learninng models can be overfit easily, to avoid this, we add randomization using drop outmodel.add(Dropout(0.1))#Adding sigmoid activation function to normalize the outputmodel.add(Dense(1, activation='sigmoid'))model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])print(model.summary())" }, { "code": null, "e": 8939, "s": 8751, "text": "history = model.fit(x_train_features, train_y, batch_size=512, epochs=20, validation_data=(x_test_features, test_y))y_predict = [1 if o>0.5 else 0 for o in model.predict(x_test_features)]" }, { "code": null, "e": 9070, "s": 8939, "text": "Through the above, we have successfully fit a bi-directional LSTM model on our email data and detected 125 of 1114 emails as spam." }, { "code": null, "e": 9284, "s": 9070, "text": "Since the percentage of spam in data is often low, Measuring the model’s performance by accuracy alone is not recommended. We need to evaluate it using other performance metrics as well, which we’ll look at below." }, { "code": null, "e": 9715, "s": 9284, "text": "Precision and recall are the two most widely used performance metrics for a classification problem to get a better understanding of the problem. Precision is the fraction of the relevant instances from all the retrieved instances. Precision helps us to understand how useful the results are. The recall is the fraction of relevant instances from all the relevant instances. Recall helps us understand how complete the results are." }, { "code": null, "e": 9774, "s": 9715, "text": "The F1 Score is the harmonic mean of precision and recall." }, { "code": null, "e": 10013, "s": 9774, "text": "For example, consider that a search query results in 30 pages, of which 20 are relevant, but the results fail to display 40 other relevant results. In this case, the precision is 20/30, and recall is 20/60. Therefore, our F1 Score is 4/9." }, { "code": null, "e": 10098, "s": 10013, "text": "Using F1-score as a performance metric for spam detection problems is a good choice." }, { "code": null, "e": 10499, "s": 10098, "text": "from sklearn.metrics import confusion_matrix,f1_score, precision_score,recall_scorecf_matrix =confusion_matrix(test_y,y_predict)tn, fp, fn, tp = confusion_matrix(test_y,y_predict).ravel()print(\"Precision: {:.2f}%\".format(100 * precision_score(test_y, y_predict)))print(\"Recall: {:.2f}%\".format(100 * recall_score(test_y, y_predict)))print(\"F1 Score: {:.2f}%\".format(100 * f1_score(test_y,y_predict)))" }, { "code": null, "e": 10876, "s": 10499, "text": "import seaborn as snsimport matplotlib.pyplot as pltax= plt.subplot()#annot=True to annotate cellssns.heatmap(cf_matrix, annot=True, ax = ax,cmap='Blues',fmt='');# labels, title and ticksax.set_xlabel('Predicted labels');ax.set_ylabel('True labels');ax.set_title('Confusion Matrix');ax.xaxis.set_ticklabels(['Not Spam', 'Spam']); ax.yaxis.set_ticklabels(['Not Spam', 'Spam']);" }, { "code": null, "e": 11282, "s": 10876, "text": "A model with an F1 score of 95% is a good-to-go model. Keep in mind, however, that these results are based on the training data we used. When applying a model like this to real-world data, we still need to actively monitor the model’s performance over time. We can also continue to improve the model by responding to results and feedback by doing things like adding features and removing misspelled words." }, { "code": null, "e": 11574, "s": 11282, "text": "In this article, we created a spam detection model by converting text data into vectors, creating a BiLSTM model, and fitting the model with the vectors. We also explored a variety of text processing techniques, text sequencing techniques, and deep learning models, namely RNN, LSTM, BiLSTM." }, { "code": null, "e": 11767, "s": 11574, "text": "The concepts and techniques learned in this article can be applied to a variety of natural language processing problems like building chatbots, text summarization, language translation models." }, { "code": null, "e": 11983, "s": 11767, "text": "If you would like to experiment with the custom dataset yourself, you can download the annotated data on UCI machine learning repository and the code at Github. This article is originally published on Lionbridge.ai." } ]
Anonymous classes in C++ - GeeksforGeeks
09 Mar, 2018 Anonymous class is a class which has no name given to it. C++ supports this feature. These classes cannot have a constructor but can have a destructor. These classes can neither be passed as arguments to functions nor can be used as return values from functions. Examples to illustrate Anonymous Classes Creating single object of Anonymous Class : In the first Example, Anonymous class is created with object name obj1. The scope of the obj1 is throughout the program. So, we can access this into the main function. In main, using obj1, a call is given to member functions of the anonymous class.// CPP program to illustrate // concept of Anonymous Class#include <iostream>using namespace std; // Anonymous Class : Class is not having any nameclass{ // data member int i; public: void setData(int i) { // this pointer is used to differentiate // between data member and formal argument. this->i = i; } void print() { cout << "Value for i : " << this->i << endl; } } obj1; // object for anonymous class // Driver functionint main(){ obj1.setData(10); obj1.print(); return 0;}Output :Value for i : 10 Creating two objects of Anonymous Class : In the Second example, we have created two objects obj1 and obj2 for Anonymous class and given a call to member functions of the class. The scope of the obj1 and obj2 is through out the program. Likewise, we can create multiple objects for an anonymous class.// CPP program to illustrate // concept of Anonymous Class#include <iostream>using namespace std; // Anonymous Class : Class is not having any nameclass{ // data member int i; public: void setData(int i) { // this pointer is used to differentiate // between data member and formal argument. this->i = i; } void print() { cout << "Value for i : " << this->i << endl; } } obj1, obj2; // multiple objects for anonymous class // Driver functionint main(){ obj1.setData(10); obj1.print(); obj2.setData(20); obj2.print(); return 0;}Output :Value for i : 10 Value for i : 20 Restricting the scope of Anonymous class : To restrict the scope of the objects for the anonymous class, we can take a help of typedef. In the third example, by using typedef we can give a convenient name to class and use that name we have created multiple objects obje1 and obj2 for the anonymous class. Here we can control the scope of the obj1 and obj2 objects, which are inside the main function.// CPP program to illustrate // concept of Anonymous Class// by scope restriction#include<iostream>using namespace std; // Anonymous Class : Class is not having any nametypedef class{ // data member int i; public: void setData(int i) { // this pointer is used to differentiate // between data member and formal argument. this->i = i; } void print() { cout << "Value for i :" << this->i << endl; } } myClass; // using typedef give a proper name // Driver functionint main(){ // multiple objects myClass obj1, obj2; obj1.setData(10); obj1.print(); obj2.setData(20); obj2.print(); return 0;}Output :Value for i : 10 Value for i : 20 Creating single object of Anonymous Class : In the first Example, Anonymous class is created with object name obj1. The scope of the obj1 is throughout the program. So, we can access this into the main function. In main, using obj1, a call is given to member functions of the anonymous class.// CPP program to illustrate // concept of Anonymous Class#include <iostream>using namespace std; // Anonymous Class : Class is not having any nameclass{ // data member int i; public: void setData(int i) { // this pointer is used to differentiate // between data member and formal argument. this->i = i; } void print() { cout << "Value for i : " << this->i << endl; } } obj1; // object for anonymous class // Driver functionint main(){ obj1.setData(10); obj1.print(); return 0;}Output :Value for i : 10 // CPP program to illustrate // concept of Anonymous Class#include <iostream>using namespace std; // Anonymous Class : Class is not having any nameclass{ // data member int i; public: void setData(int i) { // this pointer is used to differentiate // between data member and formal argument. this->i = i; } void print() { cout << "Value for i : " << this->i << endl; } } obj1; // object for anonymous class // Driver functionint main(){ obj1.setData(10); obj1.print(); return 0;} Output : Value for i : 10 Creating two objects of Anonymous Class : In the Second example, we have created two objects obj1 and obj2 for Anonymous class and given a call to member functions of the class. The scope of the obj1 and obj2 is through out the program. Likewise, we can create multiple objects for an anonymous class.// CPP program to illustrate // concept of Anonymous Class#include <iostream>using namespace std; // Anonymous Class : Class is not having any nameclass{ // data member int i; public: void setData(int i) { // this pointer is used to differentiate // between data member and formal argument. this->i = i; } void print() { cout << "Value for i : " << this->i << endl; } } obj1, obj2; // multiple objects for anonymous class // Driver functionint main(){ obj1.setData(10); obj1.print(); obj2.setData(20); obj2.print(); return 0;}Output :Value for i : 10 Value for i : 20 // CPP program to illustrate // concept of Anonymous Class#include <iostream>using namespace std; // Anonymous Class : Class is not having any nameclass{ // data member int i; public: void setData(int i) { // this pointer is used to differentiate // between data member and formal argument. this->i = i; } void print() { cout << "Value for i : " << this->i << endl; } } obj1, obj2; // multiple objects for anonymous class // Driver functionint main(){ obj1.setData(10); obj1.print(); obj2.setData(20); obj2.print(); return 0;} Output : Value for i : 10 Value for i : 20 Restricting the scope of Anonymous class : To restrict the scope of the objects for the anonymous class, we can take a help of typedef. In the third example, by using typedef we can give a convenient name to class and use that name we have created multiple objects obje1 and obj2 for the anonymous class. Here we can control the scope of the obj1 and obj2 objects, which are inside the main function.// CPP program to illustrate // concept of Anonymous Class// by scope restriction#include<iostream>using namespace std; // Anonymous Class : Class is not having any nametypedef class{ // data member int i; public: void setData(int i) { // this pointer is used to differentiate // between data member and formal argument. this->i = i; } void print() { cout << "Value for i :" << this->i << endl; } } myClass; // using typedef give a proper name // Driver functionint main(){ // multiple objects myClass obj1, obj2; obj1.setData(10); obj1.print(); obj2.setData(20); obj2.print(); return 0;}Output :Value for i : 10 Value for i : 20 // CPP program to illustrate // concept of Anonymous Class// by scope restriction#include<iostream>using namespace std; // Anonymous Class : Class is not having any nametypedef class{ // data member int i; public: void setData(int i) { // this pointer is used to differentiate // between data member and formal argument. this->i = i; } void print() { cout << "Value for i :" << this->i << endl; } } myClass; // using typedef give a proper name // Driver functionint main(){ // multiple objects myClass obj1, obj2; obj1.setData(10); obj1.print(); obj2.setData(20); obj2.print(); return 0;} Output : Value for i : 10 Value for i : 20 C++-Class and Object C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Operator Overloading in C++ Polymorphism in C++ Friend class and function in C++ Sorting a vector in C++ std::string class in C++ Inline Functions in C++ Pair in C++ Standard Template Library (STL) Array of Strings in C++ (5 Different Ways to Create) Convert string to char array in C++ Destructors in C++
[ { "code": null, "e": 25477, "s": 25449, "text": "\n09 Mar, 2018" }, { "code": null, "e": 25562, "s": 25477, "text": "Anonymous class is a class which has no name given to it. C++ supports this feature." }, { "code": null, "e": 25629, "s": 25562, "text": "These classes cannot have a constructor but can have a destructor." }, { "code": null, "e": 25740, "s": 25629, "text": "These classes can neither be passed as arguments to functions nor can be used as return values from functions." }, { "code": null, "e": 25781, "s": 25740, "text": "Examples to illustrate Anonymous Classes" }, { "code": null, "e": 28716, "s": 25781, "text": "Creating single object of Anonymous Class : In the first Example, Anonymous class is created with object name obj1. The scope of the obj1 is throughout the program. So, we can access this into the main function. In main, using obj1, a call is given to member functions of the anonymous class.// CPP program to illustrate // concept of Anonymous Class#include <iostream>using namespace std; // Anonymous Class : Class is not having any nameclass{ // data member int i; public: void setData(int i) { // this pointer is used to differentiate // between data member and formal argument. this->i = i; } void print() { cout << \"Value for i : \" << this->i << endl; } } obj1; // object for anonymous class // Driver functionint main(){ obj1.setData(10); obj1.print(); return 0;}Output :Value for i : 10\nCreating two objects of Anonymous Class : In the Second example, we have created two objects obj1 and obj2 for Anonymous class and given a call to member functions of the class. The scope of the obj1 and obj2 is through out the program. Likewise, we can create multiple objects for an anonymous class.// CPP program to illustrate // concept of Anonymous Class#include <iostream>using namespace std; // Anonymous Class : Class is not having any nameclass{ // data member int i; public: void setData(int i) { // this pointer is used to differentiate // between data member and formal argument. this->i = i; } void print() { cout << \"Value for i : \" << this->i << endl; } } obj1, obj2; // multiple objects for anonymous class // Driver functionint main(){ obj1.setData(10); obj1.print(); obj2.setData(20); obj2.print(); return 0;}Output :Value for i : 10\nValue for i : 20\nRestricting the scope of Anonymous class : To restrict the scope of the objects for the anonymous class, we can take a help of typedef. In the third example, by using typedef we can give a convenient name to class and use that name we have created multiple objects obje1 and obj2 for the anonymous class. Here we can control the scope of the obj1 and obj2 objects, which are inside the main function.// CPP program to illustrate // concept of Anonymous Class// by scope restriction#include<iostream>using namespace std; // Anonymous Class : Class is not having any nametypedef class{ // data member int i; public: void setData(int i) { // this pointer is used to differentiate // between data member and formal argument. this->i = i; } void print() { cout << \"Value for i :\" << this->i << endl; } } myClass; // using typedef give a proper name // Driver functionint main(){ // multiple objects myClass obj1, obj2; obj1.setData(10); obj1.print(); obj2.setData(20); obj2.print(); return 0;}Output :Value for i : 10\nValue for i : 20\n" }, { "code": null, "e": 29584, "s": 28716, "text": "Creating single object of Anonymous Class : In the first Example, Anonymous class is created with object name obj1. The scope of the obj1 is throughout the program. So, we can access this into the main function. In main, using obj1, a call is given to member functions of the anonymous class.// CPP program to illustrate // concept of Anonymous Class#include <iostream>using namespace std; // Anonymous Class : Class is not having any nameclass{ // data member int i; public: void setData(int i) { // this pointer is used to differentiate // between data member and formal argument. this->i = i; } void print() { cout << \"Value for i : \" << this->i << endl; } } obj1; // object for anonymous class // Driver functionint main(){ obj1.setData(10); obj1.print(); return 0;}Output :Value for i : 10\n" }, { "code": "// CPP program to illustrate // concept of Anonymous Class#include <iostream>using namespace std; // Anonymous Class : Class is not having any nameclass{ // data member int i; public: void setData(int i) { // this pointer is used to differentiate // between data member and formal argument. this->i = i; } void print() { cout << \"Value for i : \" << this->i << endl; } } obj1; // object for anonymous class // Driver functionint main(){ obj1.setData(10); obj1.print(); return 0;}", "e": 30135, "s": 29584, "text": null }, { "code": null, "e": 30144, "s": 30135, "text": "Output :" }, { "code": null, "e": 30162, "s": 30144, "text": "Value for i : 10\n" }, { "code": null, "e": 31111, "s": 30162, "text": "Creating two objects of Anonymous Class : In the Second example, we have created two objects obj1 and obj2 for Anonymous class and given a call to member functions of the class. The scope of the obj1 and obj2 is through out the program. Likewise, we can create multiple objects for an anonymous class.// CPP program to illustrate // concept of Anonymous Class#include <iostream>using namespace std; // Anonymous Class : Class is not having any nameclass{ // data member int i; public: void setData(int i) { // this pointer is used to differentiate // between data member and formal argument. this->i = i; } void print() { cout << \"Value for i : \" << this->i << endl; } } obj1, obj2; // multiple objects for anonymous class // Driver functionint main(){ obj1.setData(10); obj1.print(); obj2.setData(20); obj2.print(); return 0;}Output :Value for i : 10\nValue for i : 20\n" }, { "code": "// CPP program to illustrate // concept of Anonymous Class#include <iostream>using namespace std; // Anonymous Class : Class is not having any nameclass{ // data member int i; public: void setData(int i) { // this pointer is used to differentiate // between data member and formal argument. this->i = i; } void print() { cout << \"Value for i : \" << this->i << endl; } } obj1, obj2; // multiple objects for anonymous class // Driver functionint main(){ obj1.setData(10); obj1.print(); obj2.setData(20); obj2.print(); return 0;}", "e": 31717, "s": 31111, "text": null }, { "code": null, "e": 31726, "s": 31717, "text": "Output :" }, { "code": null, "e": 31761, "s": 31726, "text": "Value for i : 10\nValue for i : 20\n" }, { "code": null, "e": 32881, "s": 31761, "text": "Restricting the scope of Anonymous class : To restrict the scope of the objects for the anonymous class, we can take a help of typedef. In the third example, by using typedef we can give a convenient name to class and use that name we have created multiple objects obje1 and obj2 for the anonymous class. Here we can control the scope of the obj1 and obj2 objects, which are inside the main function.// CPP program to illustrate // concept of Anonymous Class// by scope restriction#include<iostream>using namespace std; // Anonymous Class : Class is not having any nametypedef class{ // data member int i; public: void setData(int i) { // this pointer is used to differentiate // between data member and formal argument. this->i = i; } void print() { cout << \"Value for i :\" << this->i << endl; } } myClass; // using typedef give a proper name // Driver functionint main(){ // multiple objects myClass obj1, obj2; obj1.setData(10); obj1.print(); obj2.setData(20); obj2.print(); return 0;}Output :Value for i : 10\nValue for i : 20\n" }, { "code": "// CPP program to illustrate // concept of Anonymous Class// by scope restriction#include<iostream>using namespace std; // Anonymous Class : Class is not having any nametypedef class{ // data member int i; public: void setData(int i) { // this pointer is used to differentiate // between data member and formal argument. this->i = i; } void print() { cout << \"Value for i :\" << this->i << endl; } } myClass; // using typedef give a proper name // Driver functionint main(){ // multiple objects myClass obj1, obj2; obj1.setData(10); obj1.print(); obj2.setData(20); obj2.print(); return 0;}", "e": 33559, "s": 32881, "text": null }, { "code": null, "e": 33568, "s": 33559, "text": "Output :" }, { "code": null, "e": 33603, "s": 33568, "text": "Value for i : 10\nValue for i : 20\n" }, { "code": null, "e": 33624, "s": 33603, "text": "C++-Class and Object" }, { "code": null, "e": 33628, "s": 33624, "text": "C++" }, { "code": null, "e": 33632, "s": 33628, "text": "CPP" }, { "code": null, "e": 33730, "s": 33632, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33758, "s": 33730, "text": "Operator Overloading in C++" }, { "code": null, "e": 33778, "s": 33758, "text": "Polymorphism in C++" }, { "code": null, "e": 33811, "s": 33778, "text": "Friend class and function in C++" }, { "code": null, "e": 33835, "s": 33811, "text": "Sorting a vector in C++" }, { "code": null, "e": 33860, "s": 33835, "text": "std::string class in C++" }, { "code": null, "e": 33884, "s": 33860, "text": "Inline Functions in C++" }, { "code": null, "e": 33928, "s": 33884, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 33981, "s": 33928, "text": "Array of Strings in C++ (5 Different Ways to Create)" }, { "code": null, "e": 34017, "s": 33981, "text": "Convert string to char array in C++" } ]
Minimum LCM of all pairs in a given array - GeeksforGeeks
01 Jun, 2021 Given an array arr[] of size N, the task is to find the minimum LCM (Least Common Multiple) of all unique pairs in the given array, where 1 <= N <= 105, 1 <= arr[i] <= 105. Examples: Input: arr[] = {2, 4, 3} Output: 4 Explanation LCM (2, 4) = 4 LCM (2, 3) = 6 LCM (4, 3) = 12 Minimum possible LCM is 4. Input: arr [] ={1, 5, 2, 2, 6} Output: 2 Naive Approach Generate all possible pairs and compute LCM for every unique pair.Find the minimum LCM from all unique pairs. Generate all possible pairs and compute LCM for every unique pair. Find the minimum LCM from all unique pairs. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to find// minimum possible lcm// from any pair #include <bits/stdc++.h>using namespace std; // function to compute// GCD of two numbersint gcd(int a, int b){ if (b == 0) return a; return gcd(b, a % b);} // function that return// minimum possible lcm// from any pairint minLCM(int arr[], int n){ int ans = INT_MAX; for (int i = 0; i < n; i++) { // fix the ith element and // iterate over all the array // to find minimum LCM for (int j = i + 1; j < n; j++) { int g = gcd(arr[i], arr[j]); int lcm = arr[i] / g * arr[j]; ans = min(ans, lcm); } } return ans;} // Driver codeint main(){ int arr[] = { 2, 4, 3, 6, 5 }; int n = sizeof(arr) / sizeof(arr[0]); cout << minLCM(arr, n) << endl; return 0;} // Java program to find minimum// possible lcm from any pairimport java.io.*;import java.util.*; class GFG { // Function to compute// GCD of two numbersstatic int gcd(int a, int b){ if (b == 0) return a; return gcd(b, a % b);} // Function that return minimum// possible lcm from any pairstatic int minLCM(int arr[], int n){ int ans = Integer.MAX_VALUE; for(int i = 0; i < n; i++) { // Fix the ith element and // iterate over all the array // to find minimum LCM for(int j = i + 1; j < n; j++) { int g = gcd(arr[i], arr[j]); int lcm = arr[i] / g * arr[j]; ans = Math.min(ans, lcm); } } return ans;} // Driver codepublic static void main(String[] args){ int arr[] = { 2, 4, 3, 6, 5 }; int n = arr.length; System.out.println(minLCM(arr,n));}} // This code is contributed by coder001 # Python3 program to find minimum# possible lcm from any pairimport sys # Function to compute# GCD of two numbersdef gcd(a, b): if (b == 0): return a; return gcd(b, a % b); # Function that return minimum# possible lcm from any pairdef minLCM(arr, n): ans = 1000000000; for i in range(n): # Fix the ith element and # iterate over all the # array to find minimum LCM for j in range(i + 1, n): g = gcd(arr[i], arr[j]); lcm = arr[i] / g * arr[j]; ans = min(ans, lcm); return ans; # Driver codearr = [ 2, 4, 3, 6, 5 ]; print(minLCM(arr, 5)) # This code is contributed by grand_master // C# program to find minimum// possible lcm from any pairusing System;class GFG{ // Function to compute// GCD of two numbersstatic int gcd(int a, int b){ if (b == 0) return a; return gcd(b, a % b);} // Function that return minimum// possible lcm from any pairstatic int minLCM(int []arr, int n){ int ans = Int32.MaxValue; for(int i = 0; i < n; i++) { // Fix the ith element and // iterate over all the array // to find minimum LCM for(int j = i + 1; j < n; j++) { int g = gcd(arr[i], arr[j]); int lcm = arr[i] / g * arr[j]; ans = Math.Min(ans, lcm); } } return ans;} // Driver codepublic static void Main(){ int []arr = { 2, 4, 3, 6, 5 }; int n = arr.Length; Console.Write(minLCM(arr,n));}} // This code is contributed by Akanksha_Rai <script> // Javascript program to find // minimum possible lcm // from any pair // function to compute // GCD of two numbers function gcd(a, b) { if (b == 0) return a; return gcd(b, a % b); } // function that return // minimum possible lcm // from any pair function minLCM(arr, n) { let ans = Number.MAX_VALUE; for (let i = 0; i < n; i++) { // fix the ith element and // iterate over all the array // to find minimum LCM for (let j = i + 1; j < n; j++) { let g = gcd(arr[i], arr[j]); let lcm = arr[i] / g * arr[j]; ans = Math.min(ans, lcm); } } return ans; } let arr = [ 2, 4, 3, 6, 5 ]; let n = arr.length; document.write(minLCM(arr, n)); </script> 4 Time Complexity: O(N2) Efficient Approach: This approach depends upon the formula: Product of two number = LCM of two number * GCD of two number In the formula of LCM, the denominator is the GCD of two numbers, and the GCD of two numbers will never be greater than the number itself.So for a fixed GCD, find the smallest two multiples of that fixed GCD that is present in the given array.Store only the smallest two multiples of each GCD because choosing a bigger multiple of GCD that is present in the array, no matter what, it will never give the minimum answer.Finally, use a sieve to find the minimum two number that is the multiple of the chosen GCD. In the formula of LCM, the denominator is the GCD of two numbers, and the GCD of two numbers will never be greater than the number itself. So for a fixed GCD, find the smallest two multiples of that fixed GCD that is present in the given array. Store only the smallest two multiples of each GCD because choosing a bigger multiple of GCD that is present in the array, no matter what, it will never give the minimum answer. Finally, use a sieve to find the minimum two number that is the multiple of the chosen GCD. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to find the// pair having minimum LCM #include <bits/stdc++.h>using namespace std; // function that return// pair having minimum LCMint minLCM(int arr[], int n){ int mx = 0; for (int i = 0; i < n; i++) { // find max element in the array as // the gcd of two elements from the // array can't greater than max element. mx = max(mx, arr[i]); } // created a 2D array to store minimum // two multiple of any particular i. vector<vector<int> > mul(mx + 1); for (int i = 0; i < n; i++) { if (mul[arr[i]].size() > 1) { // we already found two // smallest multiple continue; } mul[arr[i]].push_back(arr[i]); } // iterating over all gcd for (int i = 1; i <= mx; i++) { // iterating over its multiple for (int j = i + i; j <= mx; j += i) { if (mul[i].size() > 1) { // if we already found the // two smallest multiple of i break; } for (int k : mul[j]) { if (mul[i].size() > 1) break; mul[i].push_back(k); } } } int ans = INT_MAX; for (int i = 1; i <= mx; i++) { if (mul[i].size() <= 1) continue; // choosing smallest two multiple int a = mul[i][0], b = mul[i][1]; // calculating lcm int lcm = (a * b) / i; ans = min(ans, lcm); } // return final answer return ans;} // Driver codeint main(){ int arr[] = { 2, 4, 3, 6, 5 }; int n = sizeof(arr) / sizeof(arr[0]); cout << minLCM(arr, n) << endl; return 0;} // Java program to find the// pair having minimum LCMimport java.util.Vector;class GFG{ // Function that return// pair having minimum LCMstatic int minLCM(int arr[], int n){ int mx = 0; for (int i = 0; i < n; i++) { // Find max element in the // array as the gcd of two // elements from the array // can't greater than max element. mx = Math.max(mx, arr[i]); } // Created a 2D array to store minimum // two multiple of any particular i. Vector<Integer> []mul = new Vector[mx + 1]; for (int i = 0; i < mul.length; i++) mul[i] = new Vector<Integer>(); for (int i = 0; i < n; i++) { if (mul[arr[i]].size() > 1) { // We already found two // smallest multiple continue; } mul[arr[i]].add(arr[i]); } // Iterating over all gcd for (int i = 1; i <= mx; i++) { // Iterating over its multiple for (int j = i + i; j <= mx; j += i) { if (mul[i].size() > 1) { // If we already found the // two smallest multiple of i break; } for (int k : mul[j]) { if (mul[i].size() > 1) break; mul[i].add(k); } } } int ans = Integer.MAX_VALUE; for (int i = 1; i <= mx; i++) { if (mul[i].size() <= 1) continue; // Choosing smallest // two multiple int a = mul[i].get(0), b = mul[i].get(1); // Calculating lcm int lcm = (a * b) / i; ans = Math.min(ans, lcm); } // Return final answer return ans;} // Driver codepublic static void main(String[] args){ int arr[] = {2, 4, 3, 6, 5}; int n = arr.length; System.out.print(minLCM(arr, n) + "\n");}} // This code is contributed by shikhasingrajput # Python3 program to find the# pair having minimum LCMimport sys # function that return# pair having minimum LCMdef minLCM(arr, n) : mx = 0 for i in range(n) : # find max element in the array as # the gcd of two elements from the # array can't greater than max element. mx = max(mx, arr[i]) # created a 2D array to store minimum # two multiple of any particular i. mul = [[] for i in range(mx + 1)] for i in range(n) : if (len(mul[arr[i]]) > 1) : # we already found two # smallest multiple continue mul[arr[i]].append(arr[i]) # iterating over all gcd for i in range(1, mx + 1) : # iterating over its multiple for j in range(i + i, mx + 1, i) : if (len(mul[i]) > 1) : # if we already found the # two smallest multiple of i break for k in mul[j] : if (len(mul[i]) > 1) : break mul[i].append(k) ans = sys.maxsize for i in range(1, mx + 1) : if (len(mul[i]) <= 1) : continue # choosing smallest two multiple a, b = mul[i][0], mul[i][1] # calculating lcm lcm = (a * b) // i ans = min(ans, lcm) # return final answer return ans # Driver codearr = [ 2, 4, 3, 6, 5 ]n = len(arr)print(minLCM(arr, n)) # This code is contributed by divyesh072019 // C# program to find the// pair having minimum LCMusing System;using System.Collections.Generic;class GFG{ // Function that return// pair having minimum LCMstatic int minLCM(int []arr, int n){ int mx = 0; for (int i = 0; i < n; i++) { // Find max element in the // array as the gcd of two // elements from the array // can't greater than max element. mx = Math.Max(mx, arr[i]); } // Created a 2D array to store minimum // two multiple of any particular i. List<int> []mul = new List<int>[mx + 1]; for (int i = 0; i < mul.Length; i++) mul[i] = new List<int>(); for (int i = 0; i < n; i++) { if (mul[arr[i]].Count > 1) { // We already found two // smallest multiple continue; } mul[arr[i]].Add(arr[i]); } // Iterating over all gcd for (int i = 1; i <= mx; i++) { // Iterating over its multiple for (int j = i + i; j <= mx; j += i) { if (mul[i].Count > 1) { // If we already found the // two smallest multiple of i break; } foreach (int k in mul[j]) { if (mul[i].Count > 1) break; mul[i].Add(k); } } } int ans = int.MaxValue; for (int i = 1; i <= mx; i++) { if (mul[i].Count <= 1) continue; // Choosing smallest // two multiple int a = mul[i][0], b = mul[i][1]; // Calculating lcm int lcm = (a * b) / i; ans = Math.Min(ans, lcm); } // Return readonly answer return ans;} // Driver codepublic static void Main(String[] args){ int []arr = {2, 4, 3, 6, 5}; int n = arr.Length; Console.Write(minLCM(arr, n) + "\n");}} // This code is contributed by Princi Singh <script> // Javascript program to find the// pair having minimum LCM // function that return// pair having minimum LCMfunction minLCM(arr, n){ var mx = 0; for(var i = 0; i < n; i++) { // Find max element in the array as // the gcd of two elements from the // array can't greater than max element. mx = Math.max(mx, arr[i]); } // Created a 2D array to store minimum // two multiple of any particular i. var mul = Array.from(Array(mx + 1), () => Array()); for(var i = 0; i < n; i++) { if (mul[arr[i]].length > 1) { // We already found two // smallest multiple continue; } mul[arr[i]].push(arr[i]); } // Iterating over all gcd for(var i = 1; i <= mx; i++) { // Iterating over its multiple for(var j = i + i; j <= mx; j += i) { if (mul[i].length > 1) { // If we already found the // two smallest multiple of i break; } mul[j].forEach(k => { if (mul[i].length <= 1) { mul[i].push(k); } }); } } var ans = 1000000000; for(var i = 1; i <= mx; i++) { if (mul[i].length <= 1) continue; // Choosing smallest two multiple var a = mul[i][0], b = mul[i][1]; // Calculating lcm var lcm = (a * b) / i; ans = Math.min(ans, lcm); } // Return final answer return ans;} // Driver codevar arr = [ 2, 4, 3, 6, 5 ];var n = arr.length; document.write( minLCM(arr, n) + "<br>"); // This code is contributed by itsok </script> 4 Time Complexity: O((N + M) * log(M)) Auxiliary Space: O(M) where M is the maximum element in the array. coder001 Akanksha_Rai grand_master nidhi_biet shikhasingrajput princi singh divyesh072019 divyeshrabadiya07 itsok GCD-LCM Arrays Mathematical Arrays Mathematical 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 Program for Fibonacci numbers Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 24796, "s": 24768, "text": "\n01 Jun, 2021" }, { "code": null, "e": 24969, "s": 24796, "text": "Given an array arr[] of size N, the task is to find the minimum LCM (Least Common Multiple) of all unique pairs in the given array, where 1 <= N <= 105, 1 <= arr[i] <= 105." }, { "code": null, "e": 24980, "s": 24969, "text": "Examples: " }, { "code": null, "e": 25100, "s": 24980, "text": "Input: arr[] = {2, 4, 3} Output: 4 Explanation LCM (2, 4) = 4 LCM (2, 3) = 6 LCM (4, 3) = 12 Minimum possible LCM is 4." }, { "code": null, "e": 25142, "s": 25100, "text": "Input: arr [] ={1, 5, 2, 2, 6} Output: 2 " }, { "code": null, "e": 25159, "s": 25142, "text": "Naive Approach " }, { "code": null, "e": 25269, "s": 25159, "text": "Generate all possible pairs and compute LCM for every unique pair.Find the minimum LCM from all unique pairs." }, { "code": null, "e": 25336, "s": 25269, "text": "Generate all possible pairs and compute LCM for every unique pair." }, { "code": null, "e": 25380, "s": 25336, "text": "Find the minimum LCM from all unique pairs." }, { "code": null, "e": 25431, "s": 25380, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 25435, "s": 25431, "text": "C++" }, { "code": null, "e": 25440, "s": 25435, "text": "Java" }, { "code": null, "e": 25448, "s": 25440, "text": "Python3" }, { "code": null, "e": 25451, "s": 25448, "text": "C#" }, { "code": null, "e": 25462, "s": 25451, "text": "Javascript" }, { "code": "// C++ program to find// minimum possible lcm// from any pair #include <bits/stdc++.h>using namespace std; // function to compute// GCD of two numbersint gcd(int a, int b){ if (b == 0) return a; return gcd(b, a % b);} // function that return// minimum possible lcm// from any pairint minLCM(int arr[], int n){ int ans = INT_MAX; for (int i = 0; i < n; i++) { // fix the ith element and // iterate over all the array // to find minimum LCM for (int j = i + 1; j < n; j++) { int g = gcd(arr[i], arr[j]); int lcm = arr[i] / g * arr[j]; ans = min(ans, lcm); } } return ans;} // Driver codeint main(){ int arr[] = { 2, 4, 3, 6, 5 }; int n = sizeof(arr) / sizeof(arr[0]); cout << minLCM(arr, n) << endl; return 0;}", "e": 26279, "s": 25462, "text": null }, { "code": "// Java program to find minimum// possible lcm from any pairimport java.io.*;import java.util.*; class GFG { // Function to compute// GCD of two numbersstatic int gcd(int a, int b){ if (b == 0) return a; return gcd(b, a % b);} // Function that return minimum// possible lcm from any pairstatic int minLCM(int arr[], int n){ int ans = Integer.MAX_VALUE; for(int i = 0; i < n; i++) { // Fix the ith element and // iterate over all the array // to find minimum LCM for(int j = i + 1; j < n; j++) { int g = gcd(arr[i], arr[j]); int lcm = arr[i] / g * arr[j]; ans = Math.min(ans, lcm); } } return ans;} // Driver codepublic static void main(String[] args){ int arr[] = { 2, 4, 3, 6, 5 }; int n = arr.length; System.out.println(minLCM(arr,n));}} // This code is contributed by coder001", "e": 27186, "s": 26279, "text": null }, { "code": "# Python3 program to find minimum# possible lcm from any pairimport sys # Function to compute# GCD of two numbersdef gcd(a, b): if (b == 0): return a; return gcd(b, a % b); # Function that return minimum# possible lcm from any pairdef minLCM(arr, n): ans = 1000000000; for i in range(n): # Fix the ith element and # iterate over all the # array to find minimum LCM for j in range(i + 1, n): g = gcd(arr[i], arr[j]); lcm = arr[i] / g * arr[j]; ans = min(ans, lcm); return ans; # Driver codearr = [ 2, 4, 3, 6, 5 ]; print(minLCM(arr, 5)) # This code is contributed by grand_master", "e": 27885, "s": 27186, "text": null }, { "code": "// C# program to find minimum// possible lcm from any pairusing System;class GFG{ // Function to compute// GCD of two numbersstatic int gcd(int a, int b){ if (b == 0) return a; return gcd(b, a % b);} // Function that return minimum// possible lcm from any pairstatic int minLCM(int []arr, int n){ int ans = Int32.MaxValue; for(int i = 0; i < n; i++) { // Fix the ith element and // iterate over all the array // to find minimum LCM for(int j = i + 1; j < n; j++) { int g = gcd(arr[i], arr[j]); int lcm = arr[i] / g * arr[j]; ans = Math.Min(ans, lcm); } } return ans;} // Driver codepublic static void Main(){ int []arr = { 2, 4, 3, 6, 5 }; int n = arr.Length; Console.Write(minLCM(arr,n));}} // This code is contributed by Akanksha_Rai", "e": 28724, "s": 27885, "text": null }, { "code": "<script> // Javascript program to find // minimum possible lcm // from any pair // function to compute // GCD of two numbers function gcd(a, b) { if (b == 0) return a; return gcd(b, a % b); } // function that return // minimum possible lcm // from any pair function minLCM(arr, n) { let ans = Number.MAX_VALUE; for (let i = 0; i < n; i++) { // fix the ith element and // iterate over all the array // to find minimum LCM for (let j = i + 1; j < n; j++) { let g = gcd(arr[i], arr[j]); let lcm = arr[i] / g * arr[j]; ans = Math.min(ans, lcm); } } return ans; } let arr = [ 2, 4, 3, 6, 5 ]; let n = arr.length; document.write(minLCM(arr, n)); </script>", "e": 29594, "s": 28724, "text": null }, { "code": null, "e": 29596, "s": 29594, "text": "4" }, { "code": null, "e": 29621, "s": 29598, "text": "Time Complexity: O(N2)" }, { "code": null, "e": 29683, "s": 29621, "text": "Efficient Approach: This approach depends upon the formula: " }, { "code": null, "e": 29746, "s": 29683, "text": "Product of two number = LCM of two number * GCD of two number " }, { "code": null, "e": 30257, "s": 29746, "text": "In the formula of LCM, the denominator is the GCD of two numbers, and the GCD of two numbers will never be greater than the number itself.So for a fixed GCD, find the smallest two multiples of that fixed GCD that is present in the given array.Store only the smallest two multiples of each GCD because choosing a bigger multiple of GCD that is present in the array, no matter what, it will never give the minimum answer.Finally, use a sieve to find the minimum two number that is the multiple of the chosen GCD." }, { "code": null, "e": 30396, "s": 30257, "text": "In the formula of LCM, the denominator is the GCD of two numbers, and the GCD of two numbers will never be greater than the number itself." }, { "code": null, "e": 30502, "s": 30396, "text": "So for a fixed GCD, find the smallest two multiples of that fixed GCD that is present in the given array." }, { "code": null, "e": 30679, "s": 30502, "text": "Store only the smallest two multiples of each GCD because choosing a bigger multiple of GCD that is present in the array, no matter what, it will never give the minimum answer." }, { "code": null, "e": 30771, "s": 30679, "text": "Finally, use a sieve to find the minimum two number that is the multiple of the chosen GCD." }, { "code": null, "e": 30822, "s": 30771, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 30826, "s": 30822, "text": "C++" }, { "code": null, "e": 30831, "s": 30826, "text": "Java" }, { "code": null, "e": 30839, "s": 30831, "text": "Python3" }, { "code": null, "e": 30842, "s": 30839, "text": "C#" }, { "code": null, "e": 30853, "s": 30842, "text": "Javascript" }, { "code": "// C++ program to find the// pair having minimum LCM #include <bits/stdc++.h>using namespace std; // function that return// pair having minimum LCMint minLCM(int arr[], int n){ int mx = 0; for (int i = 0; i < n; i++) { // find max element in the array as // the gcd of two elements from the // array can't greater than max element. mx = max(mx, arr[i]); } // created a 2D array to store minimum // two multiple of any particular i. vector<vector<int> > mul(mx + 1); for (int i = 0; i < n; i++) { if (mul[arr[i]].size() > 1) { // we already found two // smallest multiple continue; } mul[arr[i]].push_back(arr[i]); } // iterating over all gcd for (int i = 1; i <= mx; i++) { // iterating over its multiple for (int j = i + i; j <= mx; j += i) { if (mul[i].size() > 1) { // if we already found the // two smallest multiple of i break; } for (int k : mul[j]) { if (mul[i].size() > 1) break; mul[i].push_back(k); } } } int ans = INT_MAX; for (int i = 1; i <= mx; i++) { if (mul[i].size() <= 1) continue; // choosing smallest two multiple int a = mul[i][0], b = mul[i][1]; // calculating lcm int lcm = (a * b) / i; ans = min(ans, lcm); } // return final answer return ans;} // Driver codeint main(){ int arr[] = { 2, 4, 3, 6, 5 }; int n = sizeof(arr) / sizeof(arr[0]); cout << minLCM(arr, n) << endl; return 0;}", "e": 32527, "s": 30853, "text": null }, { "code": "// Java program to find the// pair having minimum LCMimport java.util.Vector;class GFG{ // Function that return// pair having minimum LCMstatic int minLCM(int arr[], int n){ int mx = 0; for (int i = 0; i < n; i++) { // Find max element in the // array as the gcd of two // elements from the array // can't greater than max element. mx = Math.max(mx, arr[i]); } // Created a 2D array to store minimum // two multiple of any particular i. Vector<Integer> []mul = new Vector[mx + 1]; for (int i = 0; i < mul.length; i++) mul[i] = new Vector<Integer>(); for (int i = 0; i < n; i++) { if (mul[arr[i]].size() > 1) { // We already found two // smallest multiple continue; } mul[arr[i]].add(arr[i]); } // Iterating over all gcd for (int i = 1; i <= mx; i++) { // Iterating over its multiple for (int j = i + i; j <= mx; j += i) { if (mul[i].size() > 1) { // If we already found the // two smallest multiple of i break; } for (int k : mul[j]) { if (mul[i].size() > 1) break; mul[i].add(k); } } } int ans = Integer.MAX_VALUE; for (int i = 1; i <= mx; i++) { if (mul[i].size() <= 1) continue; // Choosing smallest // two multiple int a = mul[i].get(0), b = mul[i].get(1); // Calculating lcm int lcm = (a * b) / i; ans = Math.min(ans, lcm); } // Return final answer return ans;} // Driver codepublic static void main(String[] args){ int arr[] = {2, 4, 3, 6, 5}; int n = arr.length; System.out.print(minLCM(arr, n) + \"\\n\");}} // This code is contributed by shikhasingrajput", "e": 34209, "s": 32527, "text": null }, { "code": "# Python3 program to find the# pair having minimum LCMimport sys # function that return# pair having minimum LCMdef minLCM(arr, n) : mx = 0 for i in range(n) : # find max element in the array as # the gcd of two elements from the # array can't greater than max element. mx = max(mx, arr[i]) # created a 2D array to store minimum # two multiple of any particular i. mul = [[] for i in range(mx + 1)] for i in range(n) : if (len(mul[arr[i]]) > 1) : # we already found two # smallest multiple continue mul[arr[i]].append(arr[i]) # iterating over all gcd for i in range(1, mx + 1) : # iterating over its multiple for j in range(i + i, mx + 1, i) : if (len(mul[i]) > 1) : # if we already found the # two smallest multiple of i break for k in mul[j] : if (len(mul[i]) > 1) : break mul[i].append(k) ans = sys.maxsize for i in range(1, mx + 1) : if (len(mul[i]) <= 1) : continue # choosing smallest two multiple a, b = mul[i][0], mul[i][1] # calculating lcm lcm = (a * b) // i ans = min(ans, lcm) # return final answer return ans # Driver codearr = [ 2, 4, 3, 6, 5 ]n = len(arr)print(minLCM(arr, n)) # This code is contributed by divyesh072019", "e": 35675, "s": 34209, "text": null }, { "code": "// C# program to find the// pair having minimum LCMusing System;using System.Collections.Generic;class GFG{ // Function that return// pair having minimum LCMstatic int minLCM(int []arr, int n){ int mx = 0; for (int i = 0; i < n; i++) { // Find max element in the // array as the gcd of two // elements from the array // can't greater than max element. mx = Math.Max(mx, arr[i]); } // Created a 2D array to store minimum // two multiple of any particular i. List<int> []mul = new List<int>[mx + 1]; for (int i = 0; i < mul.Length; i++) mul[i] = new List<int>(); for (int i = 0; i < n; i++) { if (mul[arr[i]].Count > 1) { // We already found two // smallest multiple continue; } mul[arr[i]].Add(arr[i]); } // Iterating over all gcd for (int i = 1; i <= mx; i++) { // Iterating over its multiple for (int j = i + i; j <= mx; j += i) { if (mul[i].Count > 1) { // If we already found the // two smallest multiple of i break; } foreach (int k in mul[j]) { if (mul[i].Count > 1) break; mul[i].Add(k); } } } int ans = int.MaxValue; for (int i = 1; i <= mx; i++) { if (mul[i].Count <= 1) continue; // Choosing smallest // two multiple int a = mul[i][0], b = mul[i][1]; // Calculating lcm int lcm = (a * b) / i; ans = Math.Min(ans, lcm); } // Return readonly answer return ans;} // Driver codepublic static void Main(String[] args){ int []arr = {2, 4, 3, 6, 5}; int n = arr.Length; Console.Write(minLCM(arr, n) + \"\\n\");}} // This code is contributed by Princi Singh", "e": 37358, "s": 35675, "text": null }, { "code": "<script> // Javascript program to find the// pair having minimum LCM // function that return// pair having minimum LCMfunction minLCM(arr, n){ var mx = 0; for(var i = 0; i < n; i++) { // Find max element in the array as // the gcd of two elements from the // array can't greater than max element. mx = Math.max(mx, arr[i]); } // Created a 2D array to store minimum // two multiple of any particular i. var mul = Array.from(Array(mx + 1), () => Array()); for(var i = 0; i < n; i++) { if (mul[arr[i]].length > 1) { // We already found two // smallest multiple continue; } mul[arr[i]].push(arr[i]); } // Iterating over all gcd for(var i = 1; i <= mx; i++) { // Iterating over its multiple for(var j = i + i; j <= mx; j += i) { if (mul[i].length > 1) { // If we already found the // two smallest multiple of i break; } mul[j].forEach(k => { if (mul[i].length <= 1) { mul[i].push(k); } }); } } var ans = 1000000000; for(var i = 1; i <= mx; i++) { if (mul[i].length <= 1) continue; // Choosing smallest two multiple var a = mul[i][0], b = mul[i][1]; // Calculating lcm var lcm = (a * b) / i; ans = Math.min(ans, lcm); } // Return final answer return ans;} // Driver codevar arr = [ 2, 4, 3, 6, 5 ];var n = arr.length; document.write( minLCM(arr, n) + \"<br>\"); // This code is contributed by itsok </script>", "e": 39126, "s": 37358, "text": null }, { "code": null, "e": 39128, "s": 39126, "text": "4" }, { "code": null, "e": 39234, "s": 39130, "text": "Time Complexity: O((N + M) * log(M)) Auxiliary Space: O(M) where M is the maximum element in the array." }, { "code": null, "e": 39245, "s": 39236, "text": "coder001" }, { "code": null, "e": 39258, "s": 39245, "text": "Akanksha_Rai" }, { "code": null, "e": 39271, "s": 39258, "text": "grand_master" }, { "code": null, "e": 39282, "s": 39271, "text": "nidhi_biet" }, { "code": null, "e": 39299, "s": 39282, "text": "shikhasingrajput" }, { "code": null, "e": 39312, "s": 39299, "text": "princi singh" }, { "code": null, "e": 39326, "s": 39312, "text": "divyesh072019" }, { "code": null, "e": 39344, "s": 39326, "text": "divyeshrabadiya07" }, { "code": null, "e": 39350, "s": 39344, "text": "itsok" }, { "code": null, "e": 39358, "s": 39350, "text": "GCD-LCM" }, { "code": null, "e": 39365, "s": 39358, "text": "Arrays" }, { "code": null, "e": 39378, "s": 39365, "text": "Mathematical" }, { "code": null, "e": 39385, "s": 39378, "text": "Arrays" }, { "code": null, "e": 39398, "s": 39385, "text": "Mathematical" }, { "code": null, "e": 39496, "s": 39398, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39521, "s": 39496, "text": "Window Sliding Technique" }, { "code": null, "e": 39541, "s": 39521, "text": "Trapping Rain Water" }, { "code": null, "e": 39579, "s": 39541, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 39664, "s": 39579, "text": "Move all negative numbers to beginning and positive to end with constant extra space" }, { "code": null, "e": 39713, "s": 39664, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 39743, "s": 39713, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 39803, "s": 39743, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 39818, "s": 39803, "text": "C++ Data Types" }, { "code": null, "e": 39861, "s": 39818, "text": "Set in C++ Standard Template Library (STL)" } ]
File Objects in Python?
In python, whenever we try read or write files we don’t need to import any library as it’s handled natively. The very first thing we’ll do is to use the built-in open function to get a file object. The open function opens a file and returns a file object. The file objects contains methods and attributes which latter can be used to retrieve information or manipulate the file you opened. Before we do any operation on file, let’s first understand what is file? File is a named location on disk to store related information, as the file is having some name and location, it is stored in hard disk. In python, file operation is performed in following order: Opening a file. Read or Write operation. Closing a file. In order to open a file for reading or writing purposes, we must use the built-in open() function. The open() function uses two arguments. First is the name of the file and second is for what purpose we want to open it .i.e. for reading or writing? The syntax to open a file object in python is: File_obj = open(“filename”, “mode”) File_obj also called handle is the variable to add the file object. File_obj also called handle is the variable to add the file object. filename: Name of the file. filename: Name of the file. mode: To tell the interpreter which way the file will be used. mode: To tell the interpreter which way the file will be used. >>> f = open("pytube1.py") # open file in current directory >>> f = open(r"c:\users\rajesh\Documents\readme.txt") # Open file from the given path As we can see from above, giving second argument to the open() function is optional which is mode. We can specify the mode while opening a file .i.e. whether we want to read ‘r’, write ‘w’ or append ‘a’ to the file. We can also specify if we want to open the file in text mode or binary mode. The default mode is text mode where we get strings when reading from the file. Below are the different modes supported in open() function: >>> f = open("pytube1.py") #equivalent to 'r' or 'rt' >>> f = open("pytube1.py", "w")# write in text mode >>> f = open("color3.jpg", "r+b")# read and write in binary mode The default encoding is platform dependent. In windows, it is ‘cp1252’ but ‘utf-g’ in linux. It is recommended to specify the encoding type: >>> f = open("pytube1.py", mode = "r", encoding = 'utf-8') Let’s create a simple text file in python using any text editor or your choice, though I’m using python shell ☺. >>> # Create a text file named "textfile.txt" in your current working directory >>> f = open("textfile.txt", "w") >>> #above will create a file named textfile.txt in your default directory >>> f.write("Hello, Python") 13 >>> f.write("\nThis is our first line") 23 >>> f.write("\nThis is our second line") 24 >>> f.write("\nWhy writing more?, Because we can :)") 37 >>> f.close() We can see a new file is created, named textfile.txt in our current working directory and on opening the newly created file, we see something like: To read a text file in python, we can use multiple ways. In case you want to extract a string that contains all characters in the file. We can use the following method: file.read() Below is program to implement above syntax: >>> f = open("textfile.txt", "r") >>> f.read() 'Hello, Python\nThis is our first line\nThis is our second line\nWhy writing more?, Because we can :)' In case you want to read certain numbers of character from a file, we can do it very easily. >>> f = open("textfile.txt", "r") >>> print(f.read(13)) Hello, Python However, if you wanted to read a file line by line then you can use the readline() function. >>> f = open("textfile.txt", "r") >>> print(f.read(13)) Hello, Python >>> print(f.readline()) >>> f = open("textfile.txt", "r") >>> print(f.readline()) Hello, Python >>> print(f.readline()) This is our first line >>> print(f.readline()) This is our second line >>> print(f.readline()) Why writing more?, Because we can :) Or you want to return every line in the file, properly separated, we could use the readlines() function. >>> f = open("textfile.txt", "r") >>> print(f.readlines()) ['Hello, Python\n', 'This is our first line\n', 'This is our second line\n', 'Why writing more?, Because we can :)'] Above each line is comma separated. In case you want to read or return all the lines from the file in a most structured and efficient way, we can use the loop over method. >>> f = open("textfile.txt", "r") >>> for line in f: print(line) Hello, Python This is our first line This is our second line Why writing more?, Because we can :) Writing to a file is simple, you just need to open the file and pass on the text you want to write to a file. This method we can use to append data to an existing file. Use EOL character to start a new line after you write data to the file. >>> f = open("textfile.txt", "w") >>> f.write("There are tons to reason to 'fall in love with PYTHON'") 54 >>> f.write("\nSee, i have added one more line :).") 36 >>> f.close() >>> f = open("textfile.txt", "r") >>> for line in f: print(line) There are tons to reason to 'fall in love with PYTHON' See, i have added one more line :). Once you’re done with working on file, you have to use the f.close() command to end things. With this, we’ve close the file completely, terminating all the resources in use and freeing them up for the system to use elsewhere. >>> f = open("textfile.txt", "r") >>> f.close() >>> f.readlines() Traceback (most recent call last): File "<pyshell#95>", line 1, in <module> f.readlines() ValueError: I/O operation on closed file. Once the file is closed, any attempt to use the file object will through an error. The with statement can be used with file objects. Using the two (with statement & file objects) we get, much cleaner syntax and exceptions handling in our program. Another advantage is that any files opened will be closed automatically once we are done with file operations with open(“filename”) as file: >>> with open("textfile.txt") as f: for line in f: print(line) There are tons to reason to 'fall in love with PYTHON' See, i have added one more line :). Writing to a file using with statement is also easy (as you’ve guessed by now). >>> with open("textfile.txt", "a") as f: f.write("\nHello, Python-Here i come once again!") 38 >>> with open("textfile.txt") as f: for line in f: print(line) There are tons to reason to 'fall in love with PYTHON' See, i have added one more line :). Hello, Python-Here i come once again! We can split the lines taken from a text file using python split() function. We can split our text using any character of your choice it can either be a space character or colon or something else. >>> with open("textfile.txt", "r") as f: data = f.readlines() for line in data: words = line.split() print(words) ['There', 'are', 'tons', 'to', 'reason', 'to', "'fall", 'in', 'love', 'with', "PYTHON'"] ['See,', 'i', 'have', 'added', 'one', 'more', 'line', ':).'] ['Hello,', 'Python-Here', 'i', 'come', 'once', 'again!'] And we are going to split the text using a colon instead of a space(like above), we just need to change line.split() to line.split(“:”) and our output will be something like: ["There are tons to reason to 'fall in love with PYTHON'\n"] ['See, i have added one more line ', ').\n'] ['Hello, Python-Here i come once again!']
[ { "code": null, "e": 1171, "s": 1062, "text": "In python, whenever we try read or write files we don’t need to import any library as it’s handled natively." }, { "code": null, "e": 1260, "s": 1171, "text": "The very first thing we’ll do is to use the built-in open function to get a file object." }, { "code": null, "e": 1451, "s": 1260, "text": "The open function opens a file and returns a file object. The file objects contains methods and attributes which latter can be used to retrieve information or manipulate the file you opened." }, { "code": null, "e": 1660, "s": 1451, "text": "Before we do any operation on file, let’s first understand what is file? File is a named location on disk to store related information, as the file is having some name and location, it is stored in hard disk." }, { "code": null, "e": 1719, "s": 1660, "text": "In python, file operation is performed in following order:" }, { "code": null, "e": 1735, "s": 1719, "text": "Opening a file." }, { "code": null, "e": 1760, "s": 1735, "text": "Read or Write operation." }, { "code": null, "e": 1776, "s": 1760, "text": "Closing a file." }, { "code": null, "e": 1875, "s": 1776, "text": "In order to open a file for reading or writing purposes, we must use the built-in open() function." }, { "code": null, "e": 2025, "s": 1875, "text": "The open() function uses two arguments. First is the name of the file and second is for what purpose we want to open it .i.e. for reading or writing?" }, { "code": null, "e": 2072, "s": 2025, "text": "The syntax to open a file object in python is:" }, { "code": null, "e": 2108, "s": 2072, "text": "File_obj = open(“filename”, “mode”)" }, { "code": null, "e": 2176, "s": 2108, "text": "File_obj also called handle is the variable to add the file object." }, { "code": null, "e": 2244, "s": 2176, "text": "File_obj also called handle is the variable to add the file object." }, { "code": null, "e": 2272, "s": 2244, "text": "filename: Name of the file." }, { "code": null, "e": 2300, "s": 2272, "text": "filename: Name of the file." }, { "code": null, "e": 2363, "s": 2300, "text": "mode: To tell the interpreter which way the file will be used." }, { "code": null, "e": 2426, "s": 2363, "text": "mode: To tell the interpreter which way the file will be used." }, { "code": null, "e": 2572, "s": 2426, "text": ">>> f = open(\"pytube1.py\") # open file in current directory\n>>> f = open(r\"c:\\users\\rajesh\\Documents\\readme.txt\") # Open file from the given path" }, { "code": null, "e": 2865, "s": 2572, "text": "As we can see from above, giving second argument to the open() function is optional which is mode. We can specify the mode while opening a file .i.e. whether we want to read ‘r’, write ‘w’ or append ‘a’ to the file. We can also specify if we want to open the file in text mode or binary mode." }, { "code": null, "e": 2944, "s": 2865, "text": "The default mode is text mode where we get strings when reading from the file." }, { "code": null, "e": 3004, "s": 2944, "text": "Below are the different modes supported in open() function:" }, { "code": null, "e": 3175, "s": 3004, "text": ">>> f = open(\"pytube1.py\") #equivalent to 'r' or 'rt'\n>>> f = open(\"pytube1.py\", \"w\")# write in text mode\n>>> f = open(\"color3.jpg\", \"r+b\")# read and write in binary mode" }, { "code": null, "e": 3268, "s": 3175, "text": "The default encoding is platform dependent. In windows, it is ‘cp1252’ but ‘utf-g’ in linux." }, { "code": null, "e": 3316, "s": 3268, "text": "It is recommended to specify the encoding type:" }, { "code": null, "e": 3375, "s": 3316, "text": ">>> f = open(\"pytube1.py\", mode = \"r\", encoding = 'utf-8')" }, { "code": null, "e": 3488, "s": 3375, "text": "Let’s create a simple text file in python using any text editor or your choice, though I’m using python shell ☺." }, { "code": null, "e": 3867, "s": 3488, "text": ">>> # Create a text file named \"textfile.txt\" in your current working directory\n>>> f = open(\"textfile.txt\", \"w\")\n>>> #above will create a file named textfile.txt in your default directory\n>>> f.write(\"Hello, Python\")\n13\n>>> f.write(\"\\nThis is our first line\")\n23\n>>> f.write(\"\\nThis is our second line\")\n24\n>>> f.write(\"\\nWhy writing more?, Because we can :)\")\n37\n>>> f.close()" }, { "code": null, "e": 4015, "s": 3867, "text": "We can see a new file is created, named textfile.txt in our current working directory and on opening the newly created file, we see something like:" }, { "code": null, "e": 4072, "s": 4015, "text": "To read a text file in python, we can use multiple ways." }, { "code": null, "e": 4184, "s": 4072, "text": "In case you want to extract a string that contains all characters in the file. We can use the following method:" }, { "code": null, "e": 4196, "s": 4184, "text": "file.read()" }, { "code": null, "e": 4240, "s": 4196, "text": "Below is program to implement above syntax:" }, { "code": null, "e": 4390, "s": 4240, "text": ">>> f = open(\"textfile.txt\", \"r\")\n>>> f.read()\n'Hello, Python\\nThis is our first line\\nThis is our second line\\nWhy writing more?, Because we can :)'" }, { "code": null, "e": 4483, "s": 4390, "text": "In case you want to read certain numbers of character from a file, we can do it very easily." }, { "code": null, "e": 4553, "s": 4483, "text": ">>> f = open(\"textfile.txt\", \"r\")\n>>> print(f.read(13))\nHello, Python" }, { "code": null, "e": 4646, "s": 4553, "text": "However, if you wanted to read a file line by line then you can use the readline() function." }, { "code": null, "e": 4972, "s": 4646, "text": ">>> f = open(\"textfile.txt\", \"r\")\n>>> print(f.read(13))\nHello, Python\n>>> print(f.readline())\n\n>>> f = open(\"textfile.txt\", \"r\")\n>>> print(f.readline())\nHello, Python\n\n>>> print(f.readline())\nThis is our first line\n\n>>> print(f.readline())\nThis is our second line\n\n>>> print(f.readline())\nWhy writing more?, Because we can :)" }, { "code": null, "e": 5077, "s": 4972, "text": "Or you want to return every line in the file, properly separated, we could use the readlines() function." }, { "code": null, "e": 5253, "s": 5077, "text": ">>> f = open(\"textfile.txt\", \"r\")\n>>> print(f.readlines())\n['Hello, Python\\n', 'This is our first line\\n', 'This is our second line\\n', 'Why writing more?, Because we can :)']" }, { "code": null, "e": 5289, "s": 5253, "text": "Above each line is comma separated." }, { "code": null, "e": 5425, "s": 5289, "text": "In case you want to read or return all the lines from the file in a most structured and efficient way, we can use the loop over method." }, { "code": null, "e": 5592, "s": 5425, "text": ">>> f = open(\"textfile.txt\", \"r\")\n>>> for line in f:\nprint(line)\n\nHello, Python\n\nThis is our first line\n\nThis is our second line\n\nWhy writing more?, Because we can :)" }, { "code": null, "e": 5702, "s": 5592, "text": "Writing to a file is simple, you just need to open the file and pass on the text you want to write to a file." }, { "code": null, "e": 5833, "s": 5702, "text": "This method we can use to append data to an existing file. Use EOL character to start a new line after you write data to the file." }, { "code": null, "e": 6167, "s": 5833, "text": ">>> f = open(\"textfile.txt\", \"w\")\n>>> f.write(\"There are tons to reason to 'fall in love with PYTHON'\")\n54\n>>> f.write(\"\\nSee, i have added one more line :).\")\n36\n>>> f.close()\n>>> f = open(\"textfile.txt\", \"r\")\n>>> for line in f:\nprint(line)\n\nThere are tons to reason to 'fall in love with PYTHON'\nSee, i have added one more line :)." }, { "code": null, "e": 6393, "s": 6167, "text": "Once you’re done with working on file, you have to use the f.close() command to end things. With this, we’ve close the file completely, terminating all the resources in use and freeing them up for the system to use elsewhere." }, { "code": null, "e": 6591, "s": 6393, "text": ">>> f = open(\"textfile.txt\", \"r\")\n>>> f.close()\n>>> f.readlines()\nTraceback (most recent call last):\nFile \"<pyshell#95>\", line 1, in <module>\nf.readlines()\nValueError: I/O operation on closed file." }, { "code": null, "e": 6674, "s": 6591, "text": "Once the file is closed, any attempt to use the file object will through an error." }, { "code": null, "e": 6838, "s": 6674, "text": "The with statement can be used with file objects. Using the two (with statement & file objects) we get, much cleaner syntax and exceptions handling in our program." }, { "code": null, "e": 6948, "s": 6838, "text": "Another advantage is that any files opened will be closed automatically once we are done with file operations" }, { "code": null, "e": 6979, "s": 6948, "text": "with open(“filename”) as file:" }, { "code": null, "e": 7045, "s": 6979, "text": ">>> with open(\"textfile.txt\") as f:\nfor line in f:\n print(line)" }, { "code": null, "e": 7137, "s": 7045, "text": "There are tons to reason to 'fall in love with PYTHON'\n\nSee, i have added one more line :)." }, { "code": null, "e": 7217, "s": 7137, "text": "Writing to a file using with statement is also easy (as you’ve guessed by now)." }, { "code": null, "e": 7509, "s": 7217, "text": ">>> with open(\"textfile.txt\", \"a\") as f:\nf.write(\"\\nHello, Python-Here i come once again!\")\n\n38\n>>> with open(\"textfile.txt\") as f:\nfor line in f:\nprint(line)\n\n\nThere are tons to reason to 'fall in love with PYTHON'\n\nSee, i have added one more line :).\n\nHello, Python-Here i come once again!" }, { "code": null, "e": 7706, "s": 7509, "text": "We can split the lines taken from a text file using python split() function. We can split our text using any character of your choice it can either be a space character or colon or something else." }, { "code": null, "e": 7835, "s": 7706, "text": ">>> with open(\"textfile.txt\", \"r\") as f:\ndata = f.readlines()\n for line in data:\n words = line.split()\n print(words)" }, { "code": null, "e": 8367, "s": 7835, "text": "['There', 'are', 'tons', 'to', 'reason', 'to', \"'fall\", 'in', 'love', 'with', \"PYTHON'\"]\n['See,', 'i', 'have', 'added', 'one', 'more', 'line', ':).']\n['Hello,', 'Python-Here', 'i', 'come', 'once', 'again!']\n\nAnd we are going to split the text using a colon instead of a space(like above), we just need to change line.split() to line.split(“:”) and our output will be something like:\n\n[\"There are tons to reason to 'fall in love with PYTHON'\\n\"]\n['See, i have added one more line ', ').\\n']\n['Hello, Python-Here i come once again!']" } ]
Perform min/max with MongoDB aggregation
For min/max in MongoDB, use minandmax. Let us create a collection with documents − > db.demo251.insertOne({"Marks":78}); { "acknowledged" : true, "insertedId" : ObjectId("5e46c0001627c0c63e7dba74") } > db.demo251.insertOne({"Marks":87}); { "acknowledged" : true, "insertedId" : ObjectId("5e46c0031627c0c63e7dba75") } > db.demo251.insertOne({"Marks":56}); { "acknowledged" : true, "insertedId" : ObjectId("5e46c0061627c0c63e7dba76") } > db.demo251.insertOne({"Marks":76}); { "acknowledged" : true, "insertedId" : ObjectId("5e46c00c1627c0c63e7dba77") } Display all documents from a collection with the help of find() method − > db.demo251.find(); This will produce the following output − { "_id" : ObjectId("5e46c0001627c0c63e7dba74"), "Marks" : 78 } { "_id" : ObjectId("5e46c0031627c0c63e7dba75"), "Marks" : 87 } { "_id" : ObjectId("5e46c0061627c0c63e7dba76"), "Marks" : 56 } { "_id" : ObjectId("5e46c00c1627c0c63e7dba77"), "Marks" : 76 } Following is the query to implement min/max aggregation in MongoDB − > db.demo251.aggregate([ ... { "$group": { ... "_id": null, ... "MaxMarks": { "$max": "$Marks" }, ... "MinMarks": { "$min": "$Marks" } ... }} ...]) This will produce the following output − { "_id" : null, "MaxMarks" : 87, "MinMarks" : 56 }
[ { "code": null, "e": 1145, "s": 1062, "text": "For min/max in MongoDB, use minandmax. Let us create a collection with documents −" }, { "code": null, "e": 1637, "s": 1145, "text": "> db.demo251.insertOne({\"Marks\":78});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e46c0001627c0c63e7dba74\")\n}\n> db.demo251.insertOne({\"Marks\":87});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e46c0031627c0c63e7dba75\")\n}\n> db.demo251.insertOne({\"Marks\":56});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e46c0061627c0c63e7dba76\")\n}\n> db.demo251.insertOne({\"Marks\":76});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e46c00c1627c0c63e7dba77\")\n}" }, { "code": null, "e": 1710, "s": 1637, "text": "Display all documents from a collection with the help of find() method −" }, { "code": null, "e": 1731, "s": 1710, "text": "> db.demo251.find();" }, { "code": null, "e": 1772, "s": 1731, "text": "This will produce the following output −" }, { "code": null, "e": 2024, "s": 1772, "text": "{ \"_id\" : ObjectId(\"5e46c0001627c0c63e7dba74\"), \"Marks\" : 78 }\n{ \"_id\" : ObjectId(\"5e46c0031627c0c63e7dba75\"), \"Marks\" : 87 }\n{ \"_id\" : ObjectId(\"5e46c0061627c0c63e7dba76\"), \"Marks\" : 56 }\n{ \"_id\" : ObjectId(\"5e46c00c1627c0c63e7dba77\"), \"Marks\" : 76 }" }, { "code": null, "e": 2093, "s": 2024, "text": "Following is the query to implement min/max aggregation in MongoDB −" }, { "code": null, "e": 2260, "s": 2093, "text": "> db.demo251.aggregate([\n... { \"$group\": {\n... \"_id\": null,\n... \"MaxMarks\": { \"$max\": \"$Marks\" },\n... \"MinMarks\": { \"$min\": \"$Marks\" }\n... }}\n...])" }, { "code": null, "e": 2301, "s": 2260, "text": "This will produce the following output −" }, { "code": null, "e": 2352, "s": 2301, "text": "{ \"_id\" : null, \"MaxMarks\" : 87, \"MinMarks\" : 56 }" } ]
How to skip empty dates (weekends) in a financial Matplotlib Python graph?
To skip weekends in a financial graph in matplotlib, we can iterate the time in dataframe and skip the plot if weekday is 5 or 6. Set the figure size and adjust the padding between and around the subplots. Set the figure size and adjust the padding between and around the subplots. Create a dataframe with keys time. Create a dataframe with keys time. Iterate zipped index and time of a date frame. Iterate zipped index and time of a date frame. If iterated timestamp is having weekday 5 or 6, don't plot them. If iterated timestamp is having weekday 5 or 6, don't plot them. Other than 5 or 6 weekday, plot the points. Other than 5 or 6 weekday, plot the points. Set the current tick locations of Y-axis. Set the current tick locations of Y-axis. Lay out a plot with grid lines. Lay out a plot with grid lines. To display the figure, use show() method. To display the figure, use show() method. import pandas as pd from matplotlib import pyplot as plt plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True df = pd.DataFrame(dict(time=list(pd.date_range(start="2021-01-01", end="2021-01-15")))) for i, t in zip(df.index, df.time): if t.weekday() in (5, 6): pass else: plt.plot(i, t, marker="*", ms=10) plt.yticks(df.time) plt.grid(True) plt.show()
[ { "code": null, "e": 1192, "s": 1062, "text": "To skip weekends in a financial graph in matplotlib, we can iterate the time in dataframe and skip the plot if weekday is 5 or 6." }, { "code": null, "e": 1268, "s": 1192, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1344, "s": 1268, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1379, "s": 1344, "text": "Create a dataframe with keys time." }, { "code": null, "e": 1414, "s": 1379, "text": "Create a dataframe with keys time." }, { "code": null, "e": 1461, "s": 1414, "text": "Iterate zipped index and time of a date frame." }, { "code": null, "e": 1508, "s": 1461, "text": "Iterate zipped index and time of a date frame." }, { "code": null, "e": 1573, "s": 1508, "text": "If iterated timestamp is having weekday 5 or 6, don't plot them." }, { "code": null, "e": 1638, "s": 1573, "text": "If iterated timestamp is having weekday 5 or 6, don't plot them." }, { "code": null, "e": 1682, "s": 1638, "text": "Other than 5 or 6 weekday, plot the points." }, { "code": null, "e": 1726, "s": 1682, "text": "Other than 5 or 6 weekday, plot the points." }, { "code": null, "e": 1768, "s": 1726, "text": "Set the current tick locations of Y-axis." }, { "code": null, "e": 1810, "s": 1768, "text": "Set the current tick locations of Y-axis." }, { "code": null, "e": 1842, "s": 1810, "text": "Lay out a plot with grid lines." }, { "code": null, "e": 1874, "s": 1842, "text": "Lay out a plot with grid lines." }, { "code": null, "e": 1916, "s": 1874, "text": "To display the figure, use show() method." }, { "code": null, "e": 1958, "s": 1916, "text": "To display the figure, use show() method." }, { "code": null, "e": 2361, "s": 1958, "text": "import pandas as pd\nfrom matplotlib import pyplot as plt\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\ndf = pd.DataFrame(dict(time=list(pd.date_range(start=\"2021-01-01\", end=\"2021-01-15\"))))\nfor i, t in zip(df.index, df.time):\n if t.weekday() in (5, 6):\n pass\n else:\n plt.plot(i, t, marker=\"*\", ms=10)\nplt.yticks(df.time)\nplt.grid(True)\nplt.show()" } ]
HTML5 fieldset Tag - GeeksforGeeks
17 Mar, 2022 The <fieldset> tag in HTML5 is used to make a group of related elements in the form, and it creates the box over the elements. The <fieldset> tag is new in HTML5. The <legend> tag is used to define the title for the child’s contents. The legend elements are the parent element. This tag is used to define the caption for the <fieldset> element. Syntax: <fieldset>Contents</fieldset> Attribute: disabled: It is used to specify that the group of related form elements is disabled. A disabled fieldset is un-clickable and unusable. form: It is used to specify the one or more forms that the <fieldset> element belongs to. name: It is used to specify the name for the Fieldset element. autocomplete: It is used to specify that the fieldset has autocompleted on or off value. Example: This simple example illustrates the use of the <fieldset> tag in order to make a group of related elements in the HTML Form. HTML <!DOCTYPE html><html><body> <h1>GeeksforGeeks</h1> <h2>HTML <fieldset> Tag</h2> <form> <div class="title"> Employee Personal Details: </div> <!--HTML fieldset tag starts here--> <fieldset> <legend>Details:</legend> Name:<input type="text"> Emp_Id:<input type="text"> Designation:<input type="text"> </fieldset> <!--HTML fieldset tag ends here--> </form></body></html> Output: HTML <fieldset> tag Example: In this example, we will know the use of <fieldset> tag to make the group of related elements. HTML <!DOCTYPE html><html><body> <h1>GeeksforGeeks</h1> <h2>HTML <fieldset> Tag</h2> <form> <div class="title"> Suggest article for video: </div> <!--HTML fieldset tag starts here--> <fieldset> <legend>JAVA:</legend> Title:<input type="text"><br> Link:<input type="text"><br> User ID:<input type="text"> </fieldset> <!--HTML fieldset tag ends here--> <br> <!--HTML fieldset tag starts here--> <fieldset> <legend>PHP:</legend> Title:<input type="text"><br> Link:<input type="text"><br> User ID:<input type="text"> </fieldset> <!--HTML fieldset tag ends here--> </form></body></html> Output: <fieldset> tag to group the related element Supported Browsers: Google Chrome 93.0 & above Internet Explorer 11.0 Microsoft Edge 93.0 Firefox 92.0 & above Safari 14.1 Opera 78.0 Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. shubhamyadav4 bhaskargeeksforgeeks HTML-Tags HTML5 HTML HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to update Node.js and NPM to next version ? How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? How to Insert Form Data into Database using PHP ? Hide or show elements in HTML using display property REST API (Introduction) CSS to put icon inside an input element in a form Form validation using HTML and JavaScript
[ { "code": null, "e": 23331, "s": 23303, "text": "\n17 Mar, 2022" }, { "code": null, "e": 23676, "s": 23331, "text": "The <fieldset> tag in HTML5 is used to make a group of related elements in the form, and it creates the box over the elements. The <fieldset> tag is new in HTML5. The <legend> tag is used to define the title for the child’s contents. The legend elements are the parent element. This tag is used to define the caption for the <fieldset> element." }, { "code": null, "e": 23684, "s": 23676, "text": "Syntax:" }, { "code": null, "e": 23714, "s": 23684, "text": "<fieldset>Contents</fieldset>" }, { "code": null, "e": 23725, "s": 23714, "text": "Attribute:" }, { "code": null, "e": 23860, "s": 23725, "text": "disabled: It is used to specify that the group of related form elements is disabled. A disabled fieldset is un-clickable and unusable." }, { "code": null, "e": 23950, "s": 23860, "text": "form: It is used to specify the one or more forms that the <fieldset> element belongs to." }, { "code": null, "e": 24013, "s": 23950, "text": "name: It is used to specify the name for the Fieldset element." }, { "code": null, "e": 24102, "s": 24013, "text": "autocomplete: It is used to specify that the fieldset has autocompleted on or off value." }, { "code": null, "e": 24236, "s": 24102, "text": "Example: This simple example illustrates the use of the <fieldset> tag in order to make a group of related elements in the HTML Form." }, { "code": null, "e": 24241, "s": 24236, "text": "HTML" }, { "code": "<!DOCTYPE html><html><body> <h1>GeeksforGeeks</h1> <h2>HTML <fieldset> Tag</h2> <form> <div class=\"title\"> Employee Personal Details: </div> <!--HTML fieldset tag starts here--> <fieldset> <legend>Details:</legend> Name:<input type=\"text\"> Emp_Id:<input type=\"text\"> Designation:<input type=\"text\"> </fieldset> <!--HTML fieldset tag ends here--> </form></body></html>", "e": 24734, "s": 24241, "text": null }, { "code": null, "e": 24742, "s": 24734, "text": "Output:" }, { "code": null, "e": 24762, "s": 24742, "text": "HTML <fieldset> tag" }, { "code": null, "e": 24866, "s": 24762, "text": "Example: In this example, we will know the use of <fieldset> tag to make the group of related elements." }, { "code": null, "e": 24871, "s": 24866, "text": "HTML" }, { "code": "<!DOCTYPE html><html><body> <h1>GeeksforGeeks</h1> <h2>HTML <fieldset> Tag</h2> <form> <div class=\"title\"> Suggest article for video: </div> <!--HTML fieldset tag starts here--> <fieldset> <legend>JAVA:</legend> Title:<input type=\"text\"><br> Link:<input type=\"text\"><br> User ID:<input type=\"text\"> </fieldset> <!--HTML fieldset tag ends here--> <br> <!--HTML fieldset tag starts here--> <fieldset> <legend>PHP:</legend> Title:<input type=\"text\"><br> Link:<input type=\"text\"><br> User ID:<input type=\"text\"> </fieldset> <!--HTML fieldset tag ends here--> </form></body></html>", "e": 25649, "s": 24871, "text": null }, { "code": null, "e": 25658, "s": 25649, "text": " Output:" }, { "code": null, "e": 25703, "s": 25658, "text": "<fieldset> tag to group the related element " }, { "code": null, "e": 25723, "s": 25703, "text": "Supported Browsers:" }, { "code": null, "e": 25750, "s": 25723, "text": "Google Chrome 93.0 & above" }, { "code": null, "e": 25773, "s": 25750, "text": "Internet Explorer 11.0" }, { "code": null, "e": 25793, "s": 25773, "text": "Microsoft Edge 93.0" }, { "code": null, "e": 25814, "s": 25793, "text": "Firefox 92.0 & above" }, { "code": null, "e": 25826, "s": 25814, "text": "Safari 14.1" }, { "code": null, "e": 25837, "s": 25826, "text": "Opera 78.0" }, { "code": null, "e": 25974, "s": 25837, "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": 25988, "s": 25974, "text": "shubhamyadav4" }, { "code": null, "e": 26009, "s": 25988, "text": "bhaskargeeksforgeeks" }, { "code": null, "e": 26019, "s": 26009, "text": "HTML-Tags" }, { "code": null, "e": 26025, "s": 26019, "text": "HTML5" }, { "code": null, "e": 26030, "s": 26025, "text": "HTML" }, { "code": null, "e": 26035, "s": 26030, "text": "HTML" }, { "code": null, "e": 26133, "s": 26035, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26142, "s": 26133, "text": "Comments" }, { "code": null, "e": 26155, "s": 26142, "text": "Old Comments" }, { "code": null, "e": 26217, "s": 26155, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 26267, "s": 26217, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 26315, "s": 26267, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 26375, "s": 26315, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 26436, "s": 26375, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 26486, "s": 26436, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 26539, "s": 26486, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 26563, "s": 26539, "text": "REST API (Introduction)" }, { "code": null, "e": 26613, "s": 26563, "text": "CSS to put icon inside an input element in a form" } ]
Java - tan() Method
The method returns the tangent of the specified double value. double tan(double d) Here is the detail of parameters − d − A double data type. d − A double data type. This method returns the tangent of the specified double value. public class Test { public static void main(String args[]) { double degrees = 45.0; double radians = Math.toRadians(degrees); System.out.format("The value of pi is %.4f%n", Math.PI); System.out.format("The tangent of %.1f degrees is %.4f%n", degrees, Math.tan(radians)); } } This will produce the following result − The value of pi is 3.1416 The tangent of 45.0 degrees is 1.0000 16 Lectures 2 hours Malhar Lathkar 19 Lectures 5 hours Malhar Lathkar 25 Lectures 2.5 hours Anadi Sharma 126 Lectures 7 hours Tushar Kale 119 Lectures 17.5 hours Monica Mittal 76 Lectures 7 hours Arnab Chakraborty Print Add Notes Bookmark this page
[ { "code": null, "e": 2439, "s": 2377, "text": "The method returns the tangent of the specified double value." }, { "code": null, "e": 2461, "s": 2439, "text": "double tan(double d)\n" }, { "code": null, "e": 2496, "s": 2461, "text": "Here is the detail of parameters −" }, { "code": null, "e": 2520, "s": 2496, "text": "d − A double data type." }, { "code": null, "e": 2544, "s": 2520, "text": "d − A double data type." }, { "code": null, "e": 2607, "s": 2544, "text": "This method returns the tangent of the specified double value." }, { "code": null, "e": 2915, "s": 2607, "text": "public class Test { \n\n public static void main(String args[]) {\n double degrees = 45.0;\n double radians = Math.toRadians(degrees);\n\n System.out.format(\"The value of pi is %.4f%n\", Math.PI);\n System.out.format(\"The tangent of %.1f degrees is %.4f%n\", degrees, Math.tan(radians));\n }\n}" }, { "code": null, "e": 2956, "s": 2915, "text": "This will produce the following result −" }, { "code": null, "e": 3021, "s": 2956, "text": "The value of pi is 3.1416\nThe tangent of 45.0 degrees is 1.0000\n" }, { "code": null, "e": 3054, "s": 3021, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 3070, "s": 3054, "text": " Malhar Lathkar" }, { "code": null, "e": 3103, "s": 3070, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 3119, "s": 3103, "text": " Malhar Lathkar" }, { "code": null, "e": 3154, "s": 3119, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3168, "s": 3154, "text": " Anadi Sharma" }, { "code": null, "e": 3202, "s": 3168, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 3216, "s": 3202, "text": " Tushar Kale" }, { "code": null, "e": 3253, "s": 3216, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 3268, "s": 3253, "text": " Monica Mittal" }, { "code": null, "e": 3301, "s": 3268, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 3320, "s": 3301, "text": " Arnab Chakraborty" }, { "code": null, "e": 3327, "s": 3320, "text": " Print" }, { "code": null, "e": 3338, "s": 3327, "text": " Add Notes" } ]
The curious case of Simpson’s Paradox | by Parul Pandey | Towards Data Science
Statistics rarely offers a single “right”way of doing anything — Charles Wheelan in Naked Statistics In 1996, Appleton, French, and Vanderpump conducted an experiment to study the effect of smoking on a sample of people. The study was conducted over twenty years and included 1314 English women. Contrary to the common belief, this study showed that Smokers tend to live longer than non-smokers. Even though I am not an expert on the effects of smoking on human health, this finding is disturbing. The graph below shows that smokers had a mortality rate of 23%, while for non-smokers, it was around 31%. Now, here’s where the things get interesting. On breaking the same data by age group, we get an entirely different picture. The results show that in most age groups, smokers have a high mortality rate compared to non-smokers. Well, the phenomenon that we just saw above is a classic case of Simpson’s paradox, which from time to makes way into a lot of data-driven analysis. In this article, we’ll look a little deeper into it and understand how to avoid fallacies like these in our analysis. As per Wikipedia, Simpson’s paradox, also called the Yule-Simpson effect, can be defined as follows: Simpson’s Paradox is a phenomenon in probability and statistics, in which a trend appears in several different groups of data but disappears or reverses when these groups are combined. In other words, the same data set can appear to show opposite trends depending on how it’s grouped. This is exactly what we saw in the smokers vs. non-smokers mortality rate example. When grouped age-wise, the data shows that non-smokers tend to live longer. But when we see an overall picture, smokers tend to live longer. So what is exactly happening here? Why are there different interpretations of the same data, and what is evading our eye in the first case? Well, The culprit, in this case, is called the Lurking variable — a conditional variable that can affect our conclusions about the relationship between two variables — smoking and mortality in our case. Lurking means to be present in a latent or barely discernible state, although still having an effect. In the same way, a lurking variable is a variable that isn’t included in the analysis but, if included, can considerably change the outcome of the analysis. The age groups are the lurking variable in the example discussed. When the data were grouped by age, we saw that the non-smokers were significantly older on average, and thus, more likely to die during the trial period, precisely because they were living longer in general. Here is another example where the effect of Simpson’s Paradox is easily visible. We all are aware of the Palmer Penguins 🐧 dataset — the drop-in replacement for the famous iris dataset. The dataset consists of details about three species of penguins, including their culmen length and depth, their flipper length, body mass, and sex. The culmen is essentially the upper ridge of a penguin’s beak, while their wings are called flippers. The dataset is available for download on Kaggle. import pandas as pdimport seaborn as snsfrom scipy import statsimport matplotlib.pyplot as plt%matplotlib inline#plt.rcParams['figure.figsize'] = 12, 10plt.style.use("fivethirtyeight")# for pretty graphsdf = pd.read_csv('penguins_size.csv')df.head()')df.info() There are few missing values in the dataset. Let’s get rid of those. df = df.dropna() Let’s now visualize the relationship between the culmen length of the penguins vs. their culmen depth. We’ll use seaborn’s lmplot method (where “lm” stands for “linear model”)for the same. Here we see a negative association between culmen length and culmen depth for the data set. The results above demonstrate that the longer the culmen or the beak, the less dense it is. We have also calculated the correlation coefficient between the two columns to view the negative association using the Pearson correlation coefficient(PCC), referred to as Pearson’s r. The PCC is a number between -1 and 1 and measures the linear correlation between two data sets. The Scipy library provides a method called pearsonr() for the same. When you drill down further and group the data species-wise, the findings reverse. The ‘hue’ parameter determines which column in the data frame should be used for color encoding. sns.lmplot(x = 'culmen_length_mm',y = 'culmen_depth_mm', data = df, hue = 'species') Voila! What we have is a classic example of Simpson’s effect. While the culmen's length and depth were negatively associated on a group level, the species level data exhibits an opposite association. Thus the type of species is a lurking variable here. We can also see the person's coefficient for each of the species using the code below: Here is the nbviewer link to the notebook incase you want to follow along. Detecting Simpson’s effect in a dataset can be tricky and requires some careful observation and analysis. However, since this issue pops up from time to time in the statistical world, few tools have been created to help us deal with it. A paper titled “Using Simpson’s Paradox to Discover Interesting Patterns in Behavioral Data.” was released in 2018, highlighting a data-driven discovery method that leverages Simpson’s paradox to uncover interesting patterns in behavioral data. The method systematically disaggregates data to identify subgroups within a population whose behavior deviates significantly from the rest of the population. It is a great read and also has a link to the code. Data comes with a lot of power and can be easily manipulated to suit our needs and objectives. There are multiple ways of aggregating and grouping data. Depending upon how it is grouped, the data may offer confounding results. It is up to us to carefully assess all the details using statistical tools and look for lurking variables that might affect our decisions and outcomes. 👉 Interested in reading other articles authored by me. This repo contains all the articles written by me category-wise.
[ { "code": null, "e": 272, "s": 171, "text": "Statistics rarely offers a single “right”way of doing anything — Charles Wheelan in Naked Statistics" }, { "code": null, "e": 775, "s": 272, "text": "In 1996, Appleton, French, and Vanderpump conducted an experiment to study the effect of smoking on a sample of people. The study was conducted over twenty years and included 1314 English women. Contrary to the common belief, this study showed that Smokers tend to live longer than non-smokers. Even though I am not an expert on the effects of smoking on human health, this finding is disturbing. The graph below shows that smokers had a mortality rate of 23%, while for non-smokers, it was around 31%." }, { "code": null, "e": 1001, "s": 775, "text": "Now, here’s where the things get interesting. On breaking the same data by age group, we get an entirely different picture. The results show that in most age groups, smokers have a high mortality rate compared to non-smokers." }, { "code": null, "e": 1268, "s": 1001, "text": "Well, the phenomenon that we just saw above is a classic case of Simpson’s paradox, which from time to makes way into a lot of data-driven analysis. In this article, we’ll look a little deeper into it and understand how to avoid fallacies like these in our analysis." }, { "code": null, "e": 1369, "s": 1268, "text": "As per Wikipedia, Simpson’s paradox, also called the Yule-Simpson effect, can be defined as follows:" }, { "code": null, "e": 1554, "s": 1369, "text": "Simpson’s Paradox is a phenomenon in probability and statistics, in which a trend appears in several different groups of data but disappears or reverses when these groups are combined." }, { "code": null, "e": 2221, "s": 1554, "text": "In other words, the same data set can appear to show opposite trends depending on how it’s grouped. This is exactly what we saw in the smokers vs. non-smokers mortality rate example. When grouped age-wise, the data shows that non-smokers tend to live longer. But when we see an overall picture, smokers tend to live longer. So what is exactly happening here? Why are there different interpretations of the same data, and what is evading our eye in the first case? Well, The culprit, in this case, is called the Lurking variable — a conditional variable that can affect our conclusions about the relationship between two variables — smoking and mortality in our case." }, { "code": null, "e": 2480, "s": 2221, "text": "Lurking means to be present in a latent or barely discernible state, although still having an effect. In the same way, a lurking variable is a variable that isn’t included in the analysis but, if included, can considerably change the outcome of the analysis." }, { "code": null, "e": 2754, "s": 2480, "text": "The age groups are the lurking variable in the example discussed. When the data were grouped by age, we saw that the non-smokers were significantly older on average, and thus, more likely to die during the trial period, precisely because they were living longer in general." }, { "code": null, "e": 3239, "s": 2754, "text": "Here is another example where the effect of Simpson’s Paradox is easily visible. We all are aware of the Palmer Penguins 🐧 dataset — the drop-in replacement for the famous iris dataset. The dataset consists of details about three species of penguins, including their culmen length and depth, their flipper length, body mass, and sex. The culmen is essentially the upper ridge of a penguin’s beak, while their wings are called flippers. The dataset is available for download on Kaggle." }, { "code": null, "e": 3501, "s": 3239, "text": "import pandas as pdimport seaborn as snsfrom scipy import statsimport matplotlib.pyplot as plt%matplotlib inline#plt.rcParams['figure.figsize'] = 12, 10plt.style.use(\"fivethirtyeight\")# for pretty graphsdf = pd.read_csv('penguins_size.csv')df.head()')df.info()" }, { "code": null, "e": 3570, "s": 3501, "text": "There are few missing values in the dataset. Let’s get rid of those." }, { "code": null, "e": 3587, "s": 3570, "text": "df = df.dropna()" }, { "code": null, "e": 3776, "s": 3587, "text": "Let’s now visualize the relationship between the culmen length of the penguins vs. their culmen depth. We’ll use seaborn’s lmplot method (where “lm” stands for “linear model”)for the same." }, { "code": null, "e": 4309, "s": 3776, "text": "Here we see a negative association between culmen length and culmen depth for the data set. The results above demonstrate that the longer the culmen or the beak, the less dense it is. We have also calculated the correlation coefficient between the two columns to view the negative association using the Pearson correlation coefficient(PCC), referred to as Pearson’s r. The PCC is a number between -1 and 1 and measures the linear correlation between two data sets. The Scipy library provides a method called pearsonr() for the same." }, { "code": null, "e": 4489, "s": 4309, "text": "When you drill down further and group the data species-wise, the findings reverse. The ‘hue’ parameter determines which column in the data frame should be used for color encoding." }, { "code": null, "e": 4574, "s": 4489, "text": "sns.lmplot(x = 'culmen_length_mm',y = 'culmen_depth_mm', data = df, hue = 'species')" }, { "code": null, "e": 4914, "s": 4574, "text": "Voila! What we have is a classic example of Simpson’s effect. While the culmen's length and depth were negatively associated on a group level, the species level data exhibits an opposite association. Thus the type of species is a lurking variable here. We can also see the person's coefficient for each of the species using the code below:" }, { "code": null, "e": 4989, "s": 4914, "text": "Here is the nbviewer link to the notebook incase you want to follow along." }, { "code": null, "e": 5681, "s": 4989, "text": "Detecting Simpson’s effect in a dataset can be tricky and requires some careful observation and analysis. However, since this issue pops up from time to time in the statistical world, few tools have been created to help us deal with it. A paper titled “Using Simpson’s Paradox to Discover Interesting Patterns in Behavioral Data.” was released in 2018, highlighting a data-driven discovery method that leverages Simpson’s paradox to uncover interesting patterns in behavioral data. The method systematically disaggregates data to identify subgroups within a population whose behavior deviates significantly from the rest of the population. It is a great read and also has a link to the code." }, { "code": null, "e": 6060, "s": 5681, "text": "Data comes with a lot of power and can be easily manipulated to suit our needs and objectives. There are multiple ways of aggregating and grouping data. Depending upon how it is grouped, the data may offer confounding results. It is up to us to carefully assess all the details using statistical tools and look for lurking variables that might affect our decisions and outcomes." } ]
How to use Boto3 to get the details of a single crawler?
Problem Statement − Use boto3 library in Python to get the details of a crawler. Example − Get the details of a crawler, crawler_for_s3_file_job. Step 1 − Import boto3 and botocore exceptions to handle exceptions. Step 2 − crawler_name is the mandatory parameter. It is a string so user can send only one crawler name at a time to fetch details. Step 3 − Create an AWS session using boto3 library. Make sure region_name is mentioned in default profile. If it is not mentioned, then explicitly pass the region_name while creating the session. Step 4 − Create an AWS client for glue. Step 5 − Now use get_crawler function and pass the crawler_name. Step 6 − It returns the metadata of the crawler. Step 7 − Handle the generic exception if something went wrong while checking the job. Use the following code to fetch the details of a crawler − import boto3 from botocore.exceptions import ClientError def get_one_crawler_details(crawler_name:str) session = boto3.session.Session() glue_client = session.client('glue') try: crawler_details = glue_client.get_crawler(Name= crawler_name) return crawler_details except ClientError as e: raise Exception("boto3 client error in get_one_crawler_details: " + e.__str__()) except Exception as e: raise Exception("Unexpected error in get_one_crawler_details: " + e.__str__()) print(get_one_crawler_details("crawler_for_s3_file_job")) {'Crawler': {'Name': 'crawler_for_s3_file_job', 'Role': 'glue-role', 'Targets': {'S3Targets': [{'Path': 's3://test/', 'Exclusions': []}], 'JdbcTargets': [], 'DynamoDBTargets': [], 'CatalogTargets': []}, 'DatabaseName': 'default', 'Classifiers': [], 'SchemaChangePolicy': {'UpdateBehavior': 'UPDATE_IN_DATABASE', 'DeleteBehavior': 'DEPRECATE_IN_DATABASE'}, 'State': 'READY', 'TablePrefix': 'prod_scdk_', 'CrawlElapsedTime': 0, 'CreationTime': datetime.datetime(2018, 9, 24, 20, 42, 7, tzinfo=tzlocal()), 'LastUpdated': datetime.datetime(2020, 4, 27, 14, 49, 12, tzinfo=tzlocal()), 'LastCrawl': {'Status': 'SUCCEEDED', 'LogGroup': '/aws-glue/crawlers', 'LogStream': 'crawler_for_s3_file_job', 'MessagePrefix': ************-90ad1', 'StartTime': datetime.datetime(2020, 4, 27, 14, 49, 19, tzinfo=tzlocal())}, 'Version': 15}, 'ResponseMetadata': {'RequestId': '8c7dcbde-***********************-774', 'HTTPStatusCode': 200, 'HTTPHeaders': {'date': 'Sun, 28 Feb 2021 11:34:32 GMT', 'content-type': 'application/x-amz-json-1.1', 'content-length': '805', 'connection': 'keep-alive', 'x-amzn-requestid': '8c7dcbde-**********************774'}, 'RetryAttempts': 0}}
[ { "code": null, "e": 1143, "s": 1062, "text": "Problem Statement − Use boto3 library in Python to get the details of a crawler." }, { "code": null, "e": 1208, "s": 1143, "text": "Example − Get the details of a crawler, crawler_for_s3_file_job." }, { "code": null, "e": 1276, "s": 1208, "text": "Step 1 − Import boto3 and botocore exceptions to handle exceptions." }, { "code": null, "e": 1408, "s": 1276, "text": "Step 2 − crawler_name is the mandatory parameter. It is a string so user can send only one crawler name at a time to fetch details." }, { "code": null, "e": 1604, "s": 1408, "text": "Step 3 − Create an AWS session using boto3 library. Make sure region_name is mentioned in default profile. If it is not mentioned, then explicitly pass the region_name while creating the session." }, { "code": null, "e": 1644, "s": 1604, "text": "Step 4 − Create an AWS client for glue." }, { "code": null, "e": 1709, "s": 1644, "text": "Step 5 − Now use get_crawler function and pass the crawler_name." }, { "code": null, "e": 1758, "s": 1709, "text": "Step 6 − It returns the metadata of the crawler." }, { "code": null, "e": 1844, "s": 1758, "text": "Step 7 − Handle the generic exception if something went wrong while checking the job." }, { "code": null, "e": 1903, "s": 1844, "text": "Use the following code to fetch the details of a crawler −" }, { "code": null, "e": 2473, "s": 1903, "text": "import boto3\nfrom botocore.exceptions import ClientError\n\ndef get_one_crawler_details(crawler_name:str)\n session = boto3.session.Session()\n glue_client = session.client('glue')\n try:\n crawler_details = glue_client.get_crawler(Name= crawler_name)\n return crawler_details\n except ClientError as e:\n raise Exception(\"boto3 client error in get_one_crawler_details: \" + e.__str__())\n except Exception as e:\n raise Exception(\"Unexpected error in get_one_crawler_details: \" + e.__str__())\nprint(get_one_crawler_details(\"crawler_for_s3_file_job\"))" }, { "code": null, "e": 3627, "s": 2473, "text": "{'Crawler': {'Name': 'crawler_for_s3_file_job', 'Role': 'glue-role',\n'Targets': {'S3Targets': [{'Path': 's3://test/', 'Exclusions': []}],\n'JdbcTargets': [], 'DynamoDBTargets': [], 'CatalogTargets': []},\n'DatabaseName': 'default', 'Classifiers': [], 'SchemaChangePolicy':\n{'UpdateBehavior': 'UPDATE_IN_DATABASE', 'DeleteBehavior':\n'DEPRECATE_IN_DATABASE'}, 'State': 'READY', 'TablePrefix': 'prod_scdk_',\n'CrawlElapsedTime': 0, 'CreationTime': datetime.datetime(2018, 9, 24,\n20, 42, 7, tzinfo=tzlocal()), 'LastUpdated': datetime.datetime(2020, 4,\n27, 14, 49, 12, tzinfo=tzlocal()), 'LastCrawl': {'Status': 'SUCCEEDED',\n'LogGroup': '/aws-glue/crawlers', 'LogStream':\n'crawler_for_s3_file_job', 'MessagePrefix': ************-90ad1',\n'StartTime': datetime.datetime(2020, 4, 27, 14, 49, 19,\ntzinfo=tzlocal())}, 'Version': 15}, 'ResponseMetadata': {'RequestId':\n'8c7dcbde-***********************-774', 'HTTPStatusCode': 200,\n'HTTPHeaders': {'date': 'Sun, 28 Feb 2021 11:34:32 GMT', 'content-type':\n'application/x-amz-json-1.1', 'content-length': '805', 'connection':\n'keep-alive', 'x-amzn-requestid': '8c7dcbde-**********************774'},\n'RetryAttempts': 0}}" } ]
How to change the value of an attribute using jQuery?
The jQuery attr() method is used to get the value of an attribute. It can also be used to change the value. In the example, we will change the attribute value tutorialspoint.com to tutorialspoint.com/java. You can try to run the following code to learn how to change the value of an attribute using jQuery − Live Demo <html> <head> <title>Selector Example</title> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ $("#tpoint").attr("href", "https://www.tutorialspoint.com/java"); }); }); </script> </head> <body> <p><a href="https://www.tutorialspoint.com" id="tpoint">tutorialspoint.com</a></p> <button>Change attribute value</button> <p>The value of above link will change on clicking the above button. Check before and after clicking the link.</p> </body> </html>
[ { "code": null, "e": 1268, "s": 1062, "text": "The jQuery attr() method is used to get the value of an attribute. It can also be used to change the value. In the example, we will change the attribute value tutorialspoint.com to tutorialspoint.com/java." }, { "code": null, "e": 1370, "s": 1268, "text": "You can try to run the following code to learn how to change the value of an attribute using jQuery −" }, { "code": null, "e": 1380, "s": 1370, "text": "Live Demo" }, { "code": null, "e": 2036, "s": 1380, "text": "<html>\n <head>\n <title>Selector Example</title>\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script>\n <script>\n $(document).ready(function(){\n $(\"button\").click(function(){\n $(\"#tpoint\").attr(\"href\", \"https://www.tutorialspoint.com/java\");\n });\n });\n </script>\n </head>\n <body>\n <p><a href=\"https://www.tutorialspoint.com\" id=\"tpoint\">tutorialspoint.com</a></p>\n <button>Change attribute value</button>\n <p>The value of above link will change on clicking the above button. Check before and after clicking the link.</p>\n </body>\n</html>" } ]
Ubuntu + Deep Learning Software Installation Guide | by Nick Condo | Towards Data Science
I recently built a deep learning machine after enrolling in Udacity’s Self-Driving Car Engineer Nanodegree. You can read about my build here: Build a Deep Learning Rig for $800. In this post, I will describe the necessary steps to go from a clean build to training deep neural networks. There are a number of good installation guides out there — particularly this one from floydhub that much of this is based on — but I found myself having to dig through many different resources to get everything installed properly. The goal of this article is to consolidate all the necessary resources into one place. Even before installing your OS, you should perform some basic checks to ensure your system is up and running properly. For this, I recommend following along with First 5 Things to Do with a New PC Build from Paul’s Hardware YouTube channel. He goes on to install Windows, but the first half of the video applies to any machine regardless of OS. First, download Ubuntu 16.04.2 LTS, the latest long-term support version of Ubuntu. Then, create a bootable USB stick with the Ubuntu ISO. You can follow the official Ubuntu instructions here if you are on macOS, or here if you are on Windows. Once you have the Ubuntu ISO loaded onto your USB stick, insert it into your new build and power on the machine. To install Ubuntu, you will need to access the boot menu, which is the F11 key for me, and choose to boot from the USB drive. From there, you can simply follow the installation instructions on the screen. You can also refer to Ubuntu’s community wiki Quick Guide: Installing Ubuntu from a USB memory stick for more details. From the terminal, run the following commands to update packages and install some essential software: sudo apt-get updatesudo apt-get upgradesudo apt-get install build-essential cmake g++ gfortran git vim pkg-config python-dev software-properties-common wgetsudo apt-get autoremovesudo rm -rf /var/lib/apt/lists/* You will need to download the correct driver based on your GPU model, which you can check with the following command: lspci | grep -i nvidia Check the Proprietary GPU Drivers PPA repository to find the current release for your GPU. As of the time of this writing the latest release for the GeForce 10 Series is 381.22, however I opted to go with the 375.66 — the current long-lived branch release. Install the driver with the following commands: sudo add-apt-repository ppa:graphics-drivers/ppasudo apt-get updatesudo apt-get install nvidia-375 Then restart your computer: sudo shutdown -r now To double check that the driver has installed correctly: cat /proc/driver/nvidia/version Download the CUDA 8.0 toolkit from Nvidia’s site. Go to the Downloads directory (or where ever you chose to save it) and install CUDA: sudo dpkg -i cuda-repo-ubuntu1604*amd64.debsudo apt-get updatesudo apt-get install cuda Add CUDA to the environment variables: echo 'export PATH=/usr/local/cuda/bin:$PATH' >> ~/.bashrcecho 'export LD_LIBRARY_PATH=/usr/local/cuda/lib64:$LD_LIBRARY_PATH' >> ~/.bashrcsource ~/.bashrc Check that the correct version of CUDA is installed: nvcc -V Restart your computer: sudo shutdown -r now Download the cuDNN library from Nvidia’s site. You will need to first sign up for Nvidia’s developer program before you can download cuDNN. They state that this could take up to a couple of days, but I received access almost instantly. At the time of this writing, cuDNN v5.1 is the version officially supported by TensorFlow, so hold off on v6.0 unless you know it is supported (they are currently working on it). After downloading, go to your Downloads directory to extract and copy the files: tar xvf cudnn*.tgzcd cudasudo cp -P */*.h /usr/local/cuda/include/sudo cp -P */libcudnn* /usr/local/cuda/lib64/sudo chmod a+r /usr/local/cuda/lib64/libcudnn* Download the Anaconda installer from the Continuum site. I chose the Python 2.7 version, but you can choose whichever version you want to be your default Python: bash Anaconda2-4.4.0-Linux-x86_64.sh Answer ‘yes’ when the installer asks if you’d like to add Anaconda to your path (unless you don’t want it as your default Python). Once you have Anaconda installed, you can create a new conda environment with all of the necessary deep learning libraries. I will use Udacity’s starter kit as an example, since that’s what I’ve used for many of my projects. Download (or copy and paste) the environment-gpu.yml file from the CarND-Term1-Starter-Kit. You can change the name of the environment to whatever you like at the top of the file. From the directory which you saved the environment-gpu.yml file: conda env create -f environment-gpu.yml And to activate your new environment: source activate carnd-term1 Now you can test to make sure everything is working properly by running TensorFlow’s builtin MNIST example model (no longer works for TensorFlow version ≥ 1.0). Note that the following command will automatically download the 12 MB MNIST dataset on the first run: python -m tensorflow.models.image.mnist.convolutional If everything is working for you at this point, congratulations — you are now ready to classify hotdogs!
[ { "code": null, "e": 776, "s": 171, "text": "I recently built a deep learning machine after enrolling in Udacity’s Self-Driving Car Engineer Nanodegree. You can read about my build here: Build a Deep Learning Rig for $800. In this post, I will describe the necessary steps to go from a clean build to training deep neural networks. There are a number of good installation guides out there — particularly this one from floydhub that much of this is based on — but I found myself having to dig through many different resources to get everything installed properly. The goal of this article is to consolidate all the necessary resources into one place." }, { "code": null, "e": 1121, "s": 776, "text": "Even before installing your OS, you should perform some basic checks to ensure your system is up and running properly. For this, I recommend following along with First 5 Things to Do with a New PC Build from Paul’s Hardware YouTube channel. He goes on to install Windows, but the first half of the video applies to any machine regardless of OS." }, { "code": null, "e": 1802, "s": 1121, "text": "First, download Ubuntu 16.04.2 LTS, the latest long-term support version of Ubuntu. Then, create a bootable USB stick with the Ubuntu ISO. You can follow the official Ubuntu instructions here if you are on macOS, or here if you are on Windows. Once you have the Ubuntu ISO loaded onto your USB stick, insert it into your new build and power on the machine. To install Ubuntu, you will need to access the boot menu, which is the F11 key for me, and choose to boot from the USB drive. From there, you can simply follow the installation instructions on the screen. You can also refer to Ubuntu’s community wiki Quick Guide: Installing Ubuntu from a USB memory stick for more details." }, { "code": null, "e": 1904, "s": 1802, "text": "From the terminal, run the following commands to update packages and install some essential software:" }, { "code": null, "e": 2116, "s": 1904, "text": "sudo apt-get updatesudo apt-get upgradesudo apt-get install build-essential cmake g++ gfortran git vim pkg-config python-dev software-properties-common wgetsudo apt-get autoremovesudo rm -rf /var/lib/apt/lists/*" }, { "code": null, "e": 2234, "s": 2116, "text": "You will need to download the correct driver based on your GPU model, which you can check with the following command:" }, { "code": null, "e": 2257, "s": 2234, "text": "lspci | grep -i nvidia" }, { "code": null, "e": 2562, "s": 2257, "text": "Check the Proprietary GPU Drivers PPA repository to find the current release for your GPU. As of the time of this writing the latest release for the GeForce 10 Series is 381.22, however I opted to go with the 375.66 — the current long-lived branch release. Install the driver with the following commands:" }, { "code": null, "e": 2661, "s": 2562, "text": "sudo add-apt-repository ppa:graphics-drivers/ppasudo apt-get updatesudo apt-get install nvidia-375" }, { "code": null, "e": 2689, "s": 2661, "text": "Then restart your computer:" }, { "code": null, "e": 2710, "s": 2689, "text": "sudo shutdown -r now" }, { "code": null, "e": 2767, "s": 2710, "text": "To double check that the driver has installed correctly:" }, { "code": null, "e": 2799, "s": 2767, "text": "cat /proc/driver/nvidia/version" }, { "code": null, "e": 2934, "s": 2799, "text": "Download the CUDA 8.0 toolkit from Nvidia’s site. Go to the Downloads directory (or where ever you chose to save it) and install CUDA:" }, { "code": null, "e": 3022, "s": 2934, "text": "sudo dpkg -i cuda-repo-ubuntu1604*amd64.debsudo apt-get updatesudo apt-get install cuda" }, { "code": null, "e": 3061, "s": 3022, "text": "Add CUDA to the environment variables:" }, { "code": null, "e": 3216, "s": 3061, "text": "echo 'export PATH=/usr/local/cuda/bin:$PATH' >> ~/.bashrcecho 'export LD_LIBRARY_PATH=/usr/local/cuda/lib64:$LD_LIBRARY_PATH' >> ~/.bashrcsource ~/.bashrc" }, { "code": null, "e": 3269, "s": 3216, "text": "Check that the correct version of CUDA is installed:" }, { "code": null, "e": 3277, "s": 3269, "text": "nvcc -V" }, { "code": null, "e": 3300, "s": 3277, "text": "Restart your computer:" }, { "code": null, "e": 3321, "s": 3300, "text": "sudo shutdown -r now" }, { "code": null, "e": 3817, "s": 3321, "text": "Download the cuDNN library from Nvidia’s site. You will need to first sign up for Nvidia’s developer program before you can download cuDNN. They state that this could take up to a couple of days, but I received access almost instantly. At the time of this writing, cuDNN v5.1 is the version officially supported by TensorFlow, so hold off on v6.0 unless you know it is supported (they are currently working on it). After downloading, go to your Downloads directory to extract and copy the files:" }, { "code": null, "e": 3975, "s": 3817, "text": "tar xvf cudnn*.tgzcd cudasudo cp -P */*.h /usr/local/cuda/include/sudo cp -P */libcudnn* /usr/local/cuda/lib64/sudo chmod a+r /usr/local/cuda/lib64/libcudnn*" }, { "code": null, "e": 4137, "s": 3975, "text": "Download the Anaconda installer from the Continuum site. I chose the Python 2.7 version, but you can choose whichever version you want to be your default Python:" }, { "code": null, "e": 4174, "s": 4137, "text": "bash Anaconda2-4.4.0-Linux-x86_64.sh" }, { "code": null, "e": 4775, "s": 4174, "text": "Answer ‘yes’ when the installer asks if you’d like to add Anaconda to your path (unless you don’t want it as your default Python). Once you have Anaconda installed, you can create a new conda environment with all of the necessary deep learning libraries. I will use Udacity’s starter kit as an example, since that’s what I’ve used for many of my projects. Download (or copy and paste) the environment-gpu.yml file from the CarND-Term1-Starter-Kit. You can change the name of the environment to whatever you like at the top of the file. From the directory which you saved the environment-gpu.yml file:" }, { "code": null, "e": 4815, "s": 4775, "text": "conda env create -f environment-gpu.yml" }, { "code": null, "e": 4853, "s": 4815, "text": "And to activate your new environment:" }, { "code": null, "e": 4881, "s": 4853, "text": "source activate carnd-term1" }, { "code": null, "e": 5144, "s": 4881, "text": "Now you can test to make sure everything is working properly by running TensorFlow’s builtin MNIST example model (no longer works for TensorFlow version ≥ 1.0). Note that the following command will automatically download the 12 MB MNIST dataset on the first run:" }, { "code": null, "e": 5198, "s": 5144, "text": "python -m tensorflow.models.image.mnist.convolutional" } ]
Perl | Scalars - GeeksforGeeks
12 Feb, 2021 A scalar is a variable that stores a single unit of data at a time. The data that will be stored by the scalar variable can be of the different type like string, character, floating point, a large group of strings or it can be a webpage and so on.Example : Perl # Perl program to demonstrate# scalars variables # a string scalar$name = "Alex"; # Integer Scalar$rollno = 13; # a floating point scalar$percentage = 87.65; # to display the resultprint "Name = $name\n";print "Roll number = $rollno\n";print "Percentage = $percentage\n"; Output : Name = Alex Roll number = 13 Percentage = 87.65 Numeric Scalars Numeric scalar variables hold values like whole numbers, integers(positive and negative), float(containing decimal point). The following example demonstrates different types of numerical scalar variables in perl.Example : Perl # Perl program to demonstrate various types# of numerical scalar variables # Positive integer numerical# scalar variables$intpositive = 25; # Negative integer numerical# scalar variables$intnegative = -73; # Floating point numerical# scalar variables$float = 23.5; # In hexadecimal form$hexadec = 0xcd; # to display the resultprint "Positive Integer = $intpositive\n";print "Negative Integer = $intnegative\n";print "Floating Point = $float\n";print "Hexadecimal Form = $hexadec\n"; Output : Positive Integer = 25 Negative Integer = -73 Floating Point = 23.5 Hexadecimal Form = 205 String Scalars String scalar variables hold values like a word(made of different characters), a group of words or a paragraph. The following example demonstrates different types of string scalar variables.Example : Perl # Perl program to demonstrate various types# of string scalar variables # String scalar$alphastring = "GeeksforGeeks";$numericstring = "17";$alphanumeric = "gfg21"; #special character in string scalar$specialstring = "^gfg"; # in single quotes$singlequt = 'Hello Geeks'; # To display the resultprint "String with alphabets = $alphastring\n";print "String with numeric values = $numericstring\n";print "String with alphanumeric values = $alphanumeric\n";print "String within Single quotes = $singlequt\n";print "String with special characters = $specialstring\n"; Output : String with alphabets = GeeksforGeeks String with numeric values = 17 String with alphanumeric values = gfg21 String within Single quotes = Hello Geeks String with special characters = ^gfg arorakashish0911 perl-basics Perl-Scalars Perl Perl Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Perl | split() Function Perl | push() Function Perl | exists() Function Perl | chomp() Function Perl | grep() Function Perl | substr() function Perl Tutorial - Learn Perl With Examples Use of print() and say() in Perl Perl | Subroutines or Functions Perl | Removing leading and trailing white spaces (trim)
[ { "code": null, "e": 24913, "s": 24885, "text": "\n12 Feb, 2021" }, { "code": null, "e": 25172, "s": 24913, "text": "A scalar is a variable that stores a single unit of data at a time. The data that will be stored by the scalar variable can be of the different type like string, character, floating point, a large group of strings or it can be a webpage and so on.Example : " }, { "code": null, "e": 25177, "s": 25172, "text": "Perl" }, { "code": "# Perl program to demonstrate# scalars variables # a string scalar$name = \"Alex\"; # Integer Scalar$rollno = 13; # a floating point scalar$percentage = 87.65; # to display the resultprint \"Name = $name\\n\";print \"Roll number = $rollno\\n\";print \"Percentage = $percentage\\n\";", "e": 25449, "s": 25177, "text": null }, { "code": null, "e": 25460, "s": 25449, "text": "Output : " }, { "code": null, "e": 25508, "s": 25460, "text": "Name = Alex\nRoll number = 13\nPercentage = 87.65" }, { "code": null, "e": 25526, "s": 25510, "text": "Numeric Scalars" }, { "code": null, "e": 25750, "s": 25526, "text": "Numeric scalar variables hold values like whole numbers, integers(positive and negative), float(containing decimal point). The following example demonstrates different types of numerical scalar variables in perl.Example : " }, { "code": null, "e": 25755, "s": 25750, "text": "Perl" }, { "code": "# Perl program to demonstrate various types# of numerical scalar variables # Positive integer numerical# scalar variables$intpositive = 25; # Negative integer numerical# scalar variables$intnegative = -73; # Floating point numerical# scalar variables$float = 23.5; # In hexadecimal form$hexadec = 0xcd; # to display the resultprint \"Positive Integer = $intpositive\\n\";print \"Negative Integer = $intnegative\\n\";print \"Floating Point = $float\\n\";print \"Hexadecimal Form = $hexadec\\n\";", "e": 26238, "s": 25755, "text": null }, { "code": null, "e": 26249, "s": 26238, "text": "Output : " }, { "code": null, "e": 26339, "s": 26249, "text": "Positive Integer = 25\nNegative Integer = -73\nFloating Point = 23.5\nHexadecimal Form = 205" }, { "code": null, "e": 26356, "s": 26341, "text": "String Scalars" }, { "code": null, "e": 26557, "s": 26356, "text": "String scalar variables hold values like a word(made of different characters), a group of words or a paragraph. The following example demonstrates different types of string scalar variables.Example : " }, { "code": null, "e": 26562, "s": 26557, "text": "Perl" }, { "code": "# Perl program to demonstrate various types# of string scalar variables # String scalar$alphastring = \"GeeksforGeeks\";$numericstring = \"17\";$alphanumeric = \"gfg21\"; #special character in string scalar$specialstring = \"^gfg\"; # in single quotes$singlequt = 'Hello Geeks'; # To display the resultprint \"String with alphabets = $alphastring\\n\";print \"String with numeric values = $numericstring\\n\";print \"String with alphanumeric values = $alphanumeric\\n\";print \"String within Single quotes = $singlequt\\n\";print \"String with special characters = $specialstring\\n\";", "e": 27126, "s": 26562, "text": null }, { "code": null, "e": 27137, "s": 27126, "text": "Output : " }, { "code": null, "e": 27327, "s": 27137, "text": "String with alphabets = GeeksforGeeks\nString with numeric values = 17\nString with alphanumeric values = gfg21\nString within Single quotes = Hello Geeks\nString with special characters = ^gfg" }, { "code": null, "e": 27346, "s": 27329, "text": "arorakashish0911" }, { "code": null, "e": 27358, "s": 27346, "text": "perl-basics" }, { "code": null, "e": 27371, "s": 27358, "text": "Perl-Scalars" }, { "code": null, "e": 27376, "s": 27371, "text": "Perl" }, { "code": null, "e": 27381, "s": 27376, "text": "Perl" }, { "code": null, "e": 27479, "s": 27381, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27488, "s": 27479, "text": "Comments" }, { "code": null, "e": 27501, "s": 27488, "text": "Old Comments" }, { "code": null, "e": 27525, "s": 27501, "text": "Perl | split() Function" }, { "code": null, "e": 27548, "s": 27525, "text": "Perl | push() Function" }, { "code": null, "e": 27573, "s": 27548, "text": "Perl | exists() Function" }, { "code": null, "e": 27597, "s": 27573, "text": "Perl | chomp() Function" }, { "code": null, "e": 27620, "s": 27597, "text": "Perl | grep() Function" }, { "code": null, "e": 27645, "s": 27620, "text": "Perl | substr() function" }, { "code": null, "e": 27686, "s": 27645, "text": "Perl Tutorial - Learn Perl With Examples" }, { "code": null, "e": 27719, "s": 27686, "text": "Use of print() and say() in Perl" }, { "code": null, "e": 27751, "s": 27719, "text": "Perl | Subroutines or Functions" } ]
Machine Learning with Python - AdaBoost
It is one the most successful boosting ensemble algorithm. The main key of this algorithm is in the way they give weights to the instances in dataset. Due to this the algorithm needs to pay less attention to the instances while constructing subsequent models. In the following Python recipe, we are going to build Ada Boost ensemble model for classification by using AdaBoostClassifier class of sklearn on Pima Indians diabetes dataset. First, import the required packages as follows − from pandas import read_csv from sklearn.model_selection import KFold from sklearn.model_selection import cross_val_score from sklearn.ensemble import AdaBoostClassifier Now, we need to load the Pima diabetes dataset as did in previous examples − path = r"C:\pima-indians-diabetes.csv" headernames = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class'] data = read_csv(path, names = headernames) array = data.values X = array[:,0:8] Y = array[:,8] Next, give the input for 10-fold cross validation as follows − seed = 5 kfold = KFold(n_splits = 10, random_state = seed) We need to provide the number of trees we are going to build. Here we are building 150 trees with split points chosen from 5 features − num_trees = 50 Next, build the model with the help of following script − model = AdaBoostClassifier(n_estimators = num_trees, random_state = seed) Calculate and print the result as follows − results = cross_val_score(model, X, Y, cv = kfold) print(results.mean()) Output 0.7539473684210527 The output above shows that we got around 75% accuracy of our AdaBoost classifier ensemble model. 168 Lectures 13.5 hours Er. Himanshu Vasishta 64 Lectures 10.5 hours Eduonix Learning Solutions 91 Lectures 10 hours Abhilash Nelson 54 Lectures 6 hours Abhishek And Pukhraj 49 Lectures 5 hours Abhishek And Pukhraj 35 Lectures 4 hours Abhishek And Pukhraj Print Add Notes Bookmark this page
[ { "code": null, "e": 2564, "s": 2304, "text": "It is one the most successful boosting ensemble algorithm. The main key of this algorithm is in the way they give weights to the instances in dataset. Due to this the algorithm needs to pay less attention to the instances while constructing subsequent models." }, { "code": null, "e": 2741, "s": 2564, "text": "In the following Python recipe, we are going to build Ada Boost ensemble model for classification by using AdaBoostClassifier class of sklearn on Pima Indians diabetes dataset." }, { "code": null, "e": 2790, "s": 2741, "text": "First, import the required packages as follows −" }, { "code": null, "e": 2960, "s": 2790, "text": "from pandas import read_csv\nfrom sklearn.model_selection import KFold\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.ensemble import AdaBoostClassifier" }, { "code": null, "e": 3037, "s": 2960, "text": "Now, we need to load the Pima diabetes dataset as did in previous examples −" }, { "code": null, "e": 3258, "s": 3037, "text": "path = r\"C:\\pima-indians-diabetes.csv\"\nheadernames = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class']\ndata = read_csv(path, names = headernames)\narray = data.values\nX = array[:,0:8]\nY = array[:,8]" }, { "code": null, "e": 3321, "s": 3258, "text": "Next, give the input for 10-fold cross validation as follows −" }, { "code": null, "e": 3381, "s": 3321, "text": "seed = 5\nkfold = KFold(n_splits = 10, random_state = seed)\n" }, { "code": null, "e": 3517, "s": 3381, "text": "We need to provide the number of trees we are going to build. Here we are building 150 trees with split points chosen from 5 features −" }, { "code": null, "e": 3533, "s": 3517, "text": "num_trees = 50\n" }, { "code": null, "e": 3591, "s": 3533, "text": "Next, build the model with the help of following script −" }, { "code": null, "e": 3666, "s": 3591, "text": "model = AdaBoostClassifier(n_estimators = num_trees, random_state = seed)\n" }, { "code": null, "e": 3710, "s": 3666, "text": "Calculate and print the result as follows −" }, { "code": null, "e": 3784, "s": 3710, "text": "results = cross_val_score(model, X, Y, cv = kfold)\nprint(results.mean())\n" }, { "code": null, "e": 3791, "s": 3784, "text": "Output" }, { "code": null, "e": 3811, "s": 3791, "text": "0.7539473684210527\n" }, { "code": null, "e": 3909, "s": 3811, "text": "The output above shows that we got around 75% accuracy of our AdaBoost classifier ensemble model." }, { "code": null, "e": 3946, "s": 3909, "text": "\n 168 Lectures \n 13.5 hours \n" }, { "code": null, "e": 3969, "s": 3946, "text": " Er. Himanshu Vasishta" }, { "code": null, "e": 4005, "s": 3969, "text": "\n 64 Lectures \n 10.5 hours \n" }, { "code": null, "e": 4033, "s": 4005, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 4067, "s": 4033, "text": "\n 91 Lectures \n 10 hours \n" }, { "code": null, "e": 4084, "s": 4067, "text": " Abhilash Nelson" }, { "code": null, "e": 4117, "s": 4084, "text": "\n 54 Lectures \n 6 hours \n" }, { "code": null, "e": 4139, "s": 4117, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 4172, "s": 4139, "text": "\n 49 Lectures \n 5 hours \n" }, { "code": null, "e": 4194, "s": 4172, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 4227, "s": 4194, "text": "\n 35 Lectures \n 4 hours \n" }, { "code": null, "e": 4249, "s": 4227, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 4256, "s": 4249, "text": " Print" }, { "code": null, "e": 4267, "s": 4256, "text": " Add Notes" } ]
AngularJS | date Filter - GeeksforGeeks
21 Jan, 2022 AngularJS date filter is used to convert a date into a specified format. When the date format is not specified, the default date format is ‘MMM d, yyyy’. Syntax: {{ date | date : format : timezone }} Parameter Values: The date filter contains format and timezone parameters which is optional.Some common values used in format are as follow: ‘yyyy’ – define year ex. 2019 ‘yy’ – define year ex. 19 ‘y’ – define year ex. 2019 ‘MMMM’ – define month ex. April ‘MMM’ – define month ex. Apr ‘MM’ – define month ex. 04 ‘dd’ – define day ex. 09 ‘d’ – define day ex. 9 ‘hh’ – define hour in AM/PM ‘h’ – define hour in AM/PM ‘mm’ – define minute ‘m’ – define minute ‘ss’ – define second ‘s’ – define second Some predefined values for format are as follow: “short” – equivalent to “M/d/yy h:mm a” “medium” – equivalent to “MMM d, y h:mm:ss a” “shortDate” – equivalent to “M/d/yy” (5/7/19) “mediumDate” – equivalent to “MMM d, y” (May 7, 2019) “longDate” – equivalent to “MMMM d, y” (May 7, 2019) “fullDate” – equivalent to “EEEE, MMMM d, y” (Tuesday, May 7, 2019) “shortTime” – equivalent to “h:mm a” (2:35 AM) “mediumTime” – equivalent to “h:mm:ss a” (2:35:05 AM) Example 1: This example display the date in given format. html <!DOCTYPE html><html> <head> <title>Date Filter</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> </script> </head> <body> <div ng-app="gfgApp" ng-controller="dateCntrl"> <p>{{ today | date : "dd.MM.y" }}</p> </div> <script> var app = angular.module('gfgApp', []); app.controller('dateCntrl', function($scope) { $scope.today = new Date(); }); </script> </body></html> Output: 07.05.2019 Example 2: This example display the time in specified format. html <!DOCTYPE html><html> <head> <title>Date Filter</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> </script> </head> <body> <div ng-app="gfgApp" ng-controller="dateCntrl"> <p>{{ today| date : 'mediumTime'}}</p> </div> <script> var app = angular.module('gfgApp', []); app.controller('dateCntrl', function($scope) { $scope.today = new Date(); }); </script> </body></html> Output: 2:37:23 AM Example 3: This example display the date in specified format. html <!DOCTYPE html><html> <head> <title>Date Filter</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> </script> </head> <body> <div ng-app="gfgApp" ng-controller="dateCntrl"> <p>{{ today| date }}</p> </div> <script> var app = angular.module('gfgApp', []); app.controller('dateCntrl', function($scope) { $scope.today = new Date(); }); </script> </body></html> Output: May 7, 2019 saurabh1990aror gpr1ys31mnq4doxe2jkbgw6ift0z44tvlp957x8h Picked Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Express.js express.Router() Function Installation of Node.js on Linux Convert a string to an integer in JavaScript How to set input type date in dd-mm-yyyy format using HTML ? How to set the default value for an HTML <select> element ? Installation of Node.js on Linux How to set the default value for an HTML <select> element ? How to insert spaces/tabs in text using HTML/CSS? How to Insert Form Data into Database using PHP ?
[ { "code": null, "e": 27857, "s": 27829, "text": "\n21 Jan, 2022" }, { "code": null, "e": 28021, "s": 27857, "text": "AngularJS date filter is used to convert a date into a specified format. When the date format is not specified, the default date format is ‘MMM d, yyyy’. Syntax: " }, { "code": null, "e": 28059, "s": 28021, "text": "{{ date | date : format : timezone }}" }, { "code": null, "e": 28202, "s": 28059, "text": "Parameter Values: The date filter contains format and timezone parameters which is optional.Some common values used in format are as follow: " }, { "code": null, "e": 28232, "s": 28202, "text": "‘yyyy’ – define year ex. 2019" }, { "code": null, "e": 28258, "s": 28232, "text": "‘yy’ – define year ex. 19" }, { "code": null, "e": 28285, "s": 28258, "text": "‘y’ – define year ex. 2019" }, { "code": null, "e": 28317, "s": 28285, "text": "‘MMMM’ – define month ex. April" }, { "code": null, "e": 28346, "s": 28317, "text": "‘MMM’ – define month ex. Apr" }, { "code": null, "e": 28373, "s": 28346, "text": "‘MM’ – define month ex. 04" }, { "code": null, "e": 28398, "s": 28373, "text": "‘dd’ – define day ex. 09" }, { "code": null, "e": 28421, "s": 28398, "text": "‘d’ – define day ex. 9" }, { "code": null, "e": 28449, "s": 28421, "text": "‘hh’ – define hour in AM/PM" }, { "code": null, "e": 28476, "s": 28449, "text": "‘h’ – define hour in AM/PM" }, { "code": null, "e": 28497, "s": 28476, "text": "‘mm’ – define minute" }, { "code": null, "e": 28517, "s": 28497, "text": "‘m’ – define minute" }, { "code": null, "e": 28538, "s": 28517, "text": "‘ss’ – define second" }, { "code": null, "e": 28558, "s": 28538, "text": "‘s’ – define second" }, { "code": null, "e": 28609, "s": 28558, "text": "Some predefined values for format are as follow: " }, { "code": null, "e": 28649, "s": 28609, "text": "“short” – equivalent to “M/d/yy h:mm a”" }, { "code": null, "e": 28695, "s": 28649, "text": "“medium” – equivalent to “MMM d, y h:mm:ss a”" }, { "code": null, "e": 28741, "s": 28695, "text": "“shortDate” – equivalent to “M/d/yy” (5/7/19)" }, { "code": null, "e": 28795, "s": 28741, "text": "“mediumDate” – equivalent to “MMM d, y” (May 7, 2019)" }, { "code": null, "e": 28848, "s": 28795, "text": "“longDate” – equivalent to “MMMM d, y” (May 7, 2019)" }, { "code": null, "e": 28916, "s": 28848, "text": "“fullDate” – equivalent to “EEEE, MMMM d, y” (Tuesday, May 7, 2019)" }, { "code": null, "e": 28963, "s": 28916, "text": "“shortTime” – equivalent to “h:mm a” (2:35 AM)" }, { "code": null, "e": 29017, "s": 28963, "text": "“mediumTime” – equivalent to “h:mm:ss a” (2:35:05 AM)" }, { "code": null, "e": 29077, "s": 29017, "text": "Example 1: This example display the date in given format. " }, { "code": null, "e": 29082, "s": 29077, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title>Date Filter</title> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js\"> </script> </head> <body> <div ng-app=\"gfgApp\" ng-controller=\"dateCntrl\"> <p>{{ today | date : \"dd.MM.y\" }}</p> </div> <script> var app = angular.module('gfgApp', []); app.controller('dateCntrl', function($scope) { $scope.today = new Date(); }); </script> </body></html>", "e": 29634, "s": 29082, "text": null }, { "code": null, "e": 29644, "s": 29634, "text": "Output: " }, { "code": null, "e": 29655, "s": 29644, "text": "07.05.2019" }, { "code": null, "e": 29719, "s": 29655, "text": "Example 2: This example display the time in specified format. " }, { "code": null, "e": 29724, "s": 29719, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title>Date Filter</title> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js\"> </script> </head> <body> <div ng-app=\"gfgApp\" ng-controller=\"dateCntrl\"> <p>{{ today| date : 'mediumTime'}}</p> </div> <script> var app = angular.module('gfgApp', []); app.controller('dateCntrl', function($scope) { $scope.today = new Date(); }); </script> </body></html>", "e": 30277, "s": 29724, "text": null }, { "code": null, "e": 30287, "s": 30277, "text": "Output: " }, { "code": null, "e": 30298, "s": 30287, "text": "2:37:23 AM" }, { "code": null, "e": 30361, "s": 30298, "text": "Example 3: This example display the date in specified format. " }, { "code": null, "e": 30366, "s": 30361, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title>Date Filter</title> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js\"> </script> </head> <body> <div ng-app=\"gfgApp\" ng-controller=\"dateCntrl\"> <p>{{ today| date }}</p> </div> <script> var app = angular.module('gfgApp', []); app.controller('dateCntrl', function($scope) { $scope.today = new Date(); }); </script> </body></html>", "e": 30905, "s": 30366, "text": null }, { "code": null, "e": 30914, "s": 30905, "text": "Output: " }, { "code": null, "e": 30926, "s": 30914, "text": "May 7, 2019" }, { "code": null, "e": 30944, "s": 30928, "text": "saurabh1990aror" }, { "code": null, "e": 30985, "s": 30944, "text": "gpr1ys31mnq4doxe2jkbgw6ift0z44tvlp957x8h" }, { "code": null, "e": 30992, "s": 30985, "text": "Picked" }, { "code": null, "e": 31009, "s": 30992, "text": "Web Technologies" }, { "code": null, "e": 31036, "s": 31009, "text": "Web technologies Questions" }, { "code": null, "e": 31134, "s": 31036, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31143, "s": 31134, "text": "Comments" }, { "code": null, "e": 31156, "s": 31143, "text": "Old Comments" }, { "code": null, "e": 31193, "s": 31156, "text": "Express.js express.Router() Function" }, { "code": null, "e": 31226, "s": 31193, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 31271, "s": 31226, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 31332, "s": 31271, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 31392, "s": 31332, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 31425, "s": 31392, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 31485, "s": 31425, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 31535, "s": 31485, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Python Program to Find the Second Largest Number in a List Using Bubble Sort
When it is required to find the second largest number in a list using bubble sort, a method named ‘bubble_sort’ is defined, that sorts the elements of the list. Once this is done, another method named ‘get_second_largest’ is defined that returns the second element from the end as output. Below is the demonstration of the same − Live Demo my_list = [] my_input = int(input("Enter the number of elements...")) for i in range(1,my_input+1): b=int(input("Enter the element...")) my_list.append(b) for i in range(0,len(my_list)): for j in range(0,len(my_list)-i-1): if(my_list[j]>my_list[j+1]): temp=my_list[j] my_list[j]=my_list[j+1] my_list[j+1]=temp print('The second largest element is:') print(my_list[my_input-2]) Enter the number of elements...5 Enter the element...1 Enter the element...4 Enter the element...9 Enter the element...11 Enter the element...0 The second largest element is: 9 An empty list is defined. An empty list is defined. The number of elements is taken by user. The number of elements is taken by user. The elements are entered by the user. The elements are entered by the user. The list is iterated over, and the elements are appended to the list. The list is iterated over, and the elements are appended to the list. The elements of the list are sorted using bubble sort. The elements of the list are sorted using bubble sort. The second element from the last is displayed as output on the console. The second element from the last is displayed as output on the console.
[ { "code": null, "e": 1351, "s": 1062, "text": "When it is required to find the second largest number in a list using bubble sort, a method named ‘bubble_sort’ is defined, that sorts the elements of the list. Once this is done, another method named ‘get_second_largest’ is defined that returns the second element from the end as output." }, { "code": null, "e": 1392, "s": 1351, "text": "Below is the demonstration of the same −" }, { "code": null, "e": 1403, "s": 1392, "text": " Live Demo" }, { "code": null, "e": 1822, "s": 1403, "text": "my_list = []\nmy_input = int(input(\"Enter the number of elements...\"))\nfor i in range(1,my_input+1):\n b=int(input(\"Enter the element...\"))\n my_list.append(b)\nfor i in range(0,len(my_list)):\n for j in range(0,len(my_list)-i-1):\n if(my_list[j]>my_list[j+1]):\n temp=my_list[j]\n my_list[j]=my_list[j+1]\n my_list[j+1]=temp\nprint('The second largest element is:')\nprint(my_list[my_input-2])" }, { "code": null, "e": 1999, "s": 1822, "text": "Enter the number of elements...5\nEnter the element...1\nEnter the element...4\nEnter the element...9\nEnter the element...11\nEnter the element...0\nThe second largest element is:\n9" }, { "code": null, "e": 2025, "s": 1999, "text": "An empty list is defined." }, { "code": null, "e": 2051, "s": 2025, "text": "An empty list is defined." }, { "code": null, "e": 2092, "s": 2051, "text": "The number of elements is taken by user." }, { "code": null, "e": 2133, "s": 2092, "text": "The number of elements is taken by user." }, { "code": null, "e": 2171, "s": 2133, "text": "The elements are entered by the user." }, { "code": null, "e": 2209, "s": 2171, "text": "The elements are entered by the user." }, { "code": null, "e": 2279, "s": 2209, "text": "The list is iterated over, and the elements are appended to the list." }, { "code": null, "e": 2349, "s": 2279, "text": "The list is iterated over, and the elements are appended to the list." }, { "code": null, "e": 2404, "s": 2349, "text": "The elements of the list are sorted using bubble sort." }, { "code": null, "e": 2459, "s": 2404, "text": "The elements of the list are sorted using bubble sort." }, { "code": null, "e": 2531, "s": 2459, "text": "The second element from the last is displayed as output on the console." }, { "code": null, "e": 2603, "s": 2531, "text": "The second element from the last is displayed as output on the console." } ]
SortedMap Interface in C#
Java has SortedMap Interface, whereas an equivalent of it in C# is SortedList. SortedList collection in C# use a key as well as an index to access the items in a list. A sorted list is a combination of an array and a hash table. It contains a list of items that can be accessed using a key or an index. If you access items using an index, it is an ArrayList, and if you access items using a key, it is a Hashtable. The collection of items is always sorted by the key value. Let us see an example to work with SortedList and display the keys − Live Demo using System; using System.Collections; namespace Demo { class Program { static void Main(string[] args) { SortedList sl = new SortedList(); sl.Add("ST0", "One"); sl.Add("ST1", "Two"); sl.Add("ST2", "Three"); ICollection key = sl.Keys; foreach(string k in key) { Console.WriteLine(k); } } } } ST0 ST1 ST2
[ { "code": null, "e": 1141, "s": 1062, "text": "Java has SortedMap Interface, whereas an equivalent of it in C# is SortedList." }, { "code": null, "e": 1230, "s": 1141, "text": "SortedList collection in C# use a key as well as an index to access the items in a list." }, { "code": null, "e": 1536, "s": 1230, "text": "A sorted list is a combination of an array and a hash table. It contains a list of items that can be accessed using a key or an index. If you access items using an index, it is an ArrayList, and if you access items using a key, it is a Hashtable. The collection of items is always sorted by the key value." }, { "code": null, "e": 1605, "s": 1536, "text": "Let us see an example to work with SortedList and display the keys −" }, { "code": null, "e": 1616, "s": 1605, "text": " Live Demo" }, { "code": null, "e": 2004, "s": 1616, "text": "using System;\nusing System.Collections;\n\nnamespace Demo {\n class Program {\n static void Main(string[] args) {\n SortedList sl = new SortedList();\n sl.Add(\"ST0\", \"One\");\n sl.Add(\"ST1\", \"Two\");\n sl.Add(\"ST2\", \"Three\");\n ICollection key = sl.Keys;\n\n foreach(string k in key) {\n Console.WriteLine(k);\n }\n }\n }\n}" }, { "code": null, "e": 2016, "s": 2004, "text": "ST0\nST1\nST2" } ]
C Program to count the Number of Characters in a File - GeeksforGeeks
29 May, 2019 Counting the number of characters is important because almost all the text boxes that rely on user input have certain limitations on the number of characters that can be inserted. For example, the character limit on a Facebook post is 63,206 characters. Whereas, for a tweet on Twitter the character limit is 140 characters and the character limit is 80 per post for Snapchat. Determining character limits become crucial when the tweet and Facebook post updates are being done through API’s. Note: This program would not run on online compilers. Please make a text (.txt) file on your system and give its path to run this program on your system. Approach: The characters can be counted easily by reading the characters in the file using getc() method. For each character read from the file, increment the counter by one. Below is the implementation of the above approach: Program: // C Program to count// the Number of Characters in a Text File #include <stdio.h>#define MAX_FILE_NAME 100 int main(){ FILE* fp; // Character counter (result) int count = 0; char filename[MAX_FILE_NAME]; // To store a character read from file char c; // Get file name from user. // The file should be either in current folder // or complete path should be provided printf("Enter file name: "); scanf("%s", filename); // Open the file fp = fopen(filename, "r"); // Check if file exists if (fp == NULL) { printf("Could not open file %s", filename); return 0; } // Extract characters from file // and store in character c for (c = getc(fp); c != EOF; c = getc(fp)) // Increment count for this character count = count + 1; // Close the file fclose(fp); // Print the count of characters printf("The file %s has %d characters\n ", filename, count); return 0;} Note: The text file used to run this code can be downloaded from here C-File Handling C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. TCP Server-Client implementation in C Exception Handling in C++ 'this' pointer in C++ Multithreading in C Arrow operator -> in C/C++ with Examples Multiple Inheritance in C++ Smart Pointers in C++ and How to Use Them Understanding "extern" keyword in C How to split a string in C/C++, Python and Java? UDP Server-Client implementation in C
[ { "code": null, "e": 24332, "s": 24304, "text": "\n29 May, 2019" }, { "code": null, "e": 24709, "s": 24332, "text": "Counting the number of characters is important because almost all the text boxes that rely on user input have certain limitations on the number of characters that can be inserted. For example, the character limit on a Facebook post is 63,206 characters. Whereas, for a tweet on Twitter the character limit is 140 characters and the character limit is 80 per post for Snapchat." }, { "code": null, "e": 24824, "s": 24709, "text": "Determining character limits become crucial when the tweet and Facebook post updates are being done through API’s." }, { "code": null, "e": 24978, "s": 24824, "text": "Note: This program would not run on online compilers. Please make a text (.txt) file on your system and give its path to run this program on your system." }, { "code": null, "e": 25153, "s": 24978, "text": "Approach: The characters can be counted easily by reading the characters in the file using getc() method. For each character read from the file, increment the counter by one." }, { "code": null, "e": 25204, "s": 25153, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 25213, "s": 25204, "text": "Program:" }, { "code": "// C Program to count// the Number of Characters in a Text File #include <stdio.h>#define MAX_FILE_NAME 100 int main(){ FILE* fp; // Character counter (result) int count = 0; char filename[MAX_FILE_NAME]; // To store a character read from file char c; // Get file name from user. // The file should be either in current folder // or complete path should be provided printf(\"Enter file name: \"); scanf(\"%s\", filename); // Open the file fp = fopen(filename, \"r\"); // Check if file exists if (fp == NULL) { printf(\"Could not open file %s\", filename); return 0; } // Extract characters from file // and store in character c for (c = getc(fp); c != EOF; c = getc(fp)) // Increment count for this character count = count + 1; // Close the file fclose(fp); // Print the count of characters printf(\"The file %s has %d characters\\n \", filename, count); return 0;}", "e": 26216, "s": 25213, "text": null }, { "code": null, "e": 26286, "s": 26216, "text": "Note: The text file used to run this code can be downloaded from here" }, { "code": null, "e": 26302, "s": 26286, "text": "C-File Handling" }, { "code": null, "e": 26313, "s": 26302, "text": "C Language" }, { "code": null, "e": 26411, "s": 26313, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26449, "s": 26411, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 26475, "s": 26449, "text": "Exception Handling in C++" }, { "code": null, "e": 26497, "s": 26475, "text": "'this' pointer in C++" }, { "code": null, "e": 26517, "s": 26497, "text": "Multithreading in C" }, { "code": null, "e": 26558, "s": 26517, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 26586, "s": 26558, "text": "Multiple Inheritance in C++" }, { "code": null, "e": 26628, "s": 26586, "text": "Smart Pointers in C++ and How to Use Them" }, { "code": null, "e": 26664, "s": 26628, "text": "Understanding \"extern\" keyword in C" }, { "code": null, "e": 26713, "s": 26664, "text": "How to split a string in C/C++, Python and Java?" } ]
How to Add Google Locations Autocomplete to your Angular Application ? - GeeksforGeeks
05 Jun, 2020 The task here is to Add Google Locations Autocomplete to your Angular Application. When user will enter some text for a location in the Textfield, he/she will get locations recommendations and can autocomplete the location. For achieving the target, we will use ngx-google-places-autocomplete angular package. This module is a wrapper for Google Places Autocomplete js library. It allows us to integrate locations autocomplete to our project. First install ngx-google-places-autocomplete to your angular project> For npm: npm install ngx-google-places-autocomplete For yarn: yarn add ngx-google-places-autocomplete Add library to your index.html in src of your project app. <script src=”https://maps.googleapis.com/maps/api/js?key=<Your API KEY>&libraries=places&language=en”></script> Generate an API Key and place that API Key in above script tag in place of <Your API KEY>. To Generate an API key follow the below steps:Go to https://developers.google.com/places/web-service/get-api-key and follow all the steps to create an API key.Enable Places API for your API Key.Make sure your API is enabled, to enable your API follow the steps from this link https://support.google.com/googleapi/answer/6158841?hl=en. Go to https://developers.google.com/places/web-service/get-api-key and follow all the steps to create an API key. Enable Places API for your API Key. Make sure your API is enabled, to enable your API follow the steps from this link https://support.google.com/googleapi/answer/6158841?hl=en. Do necessary imports of GooglePlaceModule in app.module.ts. import { GooglePlaceModule } from "ngx-google-places-autocomplete"; @NgModule({ imports: [ GooglePlaceModule ], In HTML file for appcomponent. Define code for input field, in that input field user defined function AddressChange() will be called by (onAddressChange) passing $event and options will take care of country set in country array of component.ts file. In component.ts file , user defined function take formatted_address from $event address which is then used to set address in input field by interpolation binding. Note: In country Array there is “AU” added for Australia, you can add any other country according to you. app.module.ts Javascript import { BrowserModule } from '@angular/platform-browser';import { NgModule } from '@angular/core';import { RouterModule } from '@angular/router';import { AppComponent } from './app.component';import '@angular/compiler';//import for GooglePlaceModuleimport { GooglePlaceModule } from "ngx-google-places-autocomplete"; @NgModule({ declarations: [ AppComponent, ], imports: [ BrowserModule, //Adding to imports GooglePlaceModule ], providers: [], bootstrap: [AppComponent]})export class AppModule { } app.component.html HTML <div class="container"> <h1>GeeksforGeeks</h1> <h2>Google Places Autocomplete</h2><input ngx-google-places-autocomplete [options]= 'options' (onAddressChange)="AddressChange($event)"/>{{ formattedaddress }}</div> app.component.ts Javascript import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent { title = 'rou'; //Local Variable defined formattedaddress=" "; options={ componentRestrictions:{ country:["AU"] } } public AddressChange(address: any) { //setting address from API to local variable this.formattedaddress=address.formatted_address}} Run development server using ng serve and write some location to input field to see Autocomplete locations. AngularJS-Misc TypeScript AngularJS Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Angular PrimeNG Dropdown Component Auth Guards in Angular 9/10/11 Angular PrimeNG Calendar Component Angular PrimeNG Messages Component How to bundle an Angular app for production? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 25880, "s": 25852, "text": "\n05 Jun, 2020" }, { "code": null, "e": 26190, "s": 25880, "text": "The task here is to Add Google Locations Autocomplete to your Angular Application. When user will enter some text for a location in the Textfield, he/she will get locations recommendations and can autocomplete the location. For achieving the target, we will use ngx-google-places-autocomplete angular package." }, { "code": null, "e": 26323, "s": 26190, "text": "This module is a wrapper for Google Places Autocomplete js library. It allows us to integrate locations autocomplete to our project." }, { "code": null, "e": 26393, "s": 26323, "text": "First install ngx-google-places-autocomplete to your angular project>" }, { "code": null, "e": 26402, "s": 26393, "text": "For npm:" }, { "code": null, "e": 26445, "s": 26402, "text": "npm install ngx-google-places-autocomplete" }, { "code": null, "e": 26455, "s": 26445, "text": "For yarn:" }, { "code": null, "e": 26495, "s": 26455, "text": "yarn add ngx-google-places-autocomplete" }, { "code": null, "e": 26554, "s": 26495, "text": "Add library to your index.html in src of your project app." }, { "code": null, "e": 26666, "s": 26554, "text": "<script src=”https://maps.googleapis.com/maps/api/js?key=<Your API KEY>&libraries=places&language=en”></script>" }, { "code": null, "e": 26757, "s": 26666, "text": "Generate an API Key and place that API Key in above script tag in place of <Your API KEY>." }, { "code": null, "e": 27092, "s": 26757, "text": "To Generate an API key follow the below steps:Go to https://developers.google.com/places/web-service/get-api-key and follow all the steps to create an API key.Enable Places API for your API Key.Make sure your API is enabled, to enable your API follow the steps from this link https://support.google.com/googleapi/answer/6158841?hl=en." }, { "code": null, "e": 27206, "s": 27092, "text": "Go to https://developers.google.com/places/web-service/get-api-key and follow all the steps to create an API key." }, { "code": null, "e": 27242, "s": 27206, "text": "Enable Places API for your API Key." }, { "code": null, "e": 27383, "s": 27242, "text": "Make sure your API is enabled, to enable your API follow the steps from this link https://support.google.com/googleapi/answer/6158841?hl=en." }, { "code": null, "e": 27443, "s": 27383, "text": "Do necessary imports of GooglePlaceModule in app.module.ts." }, { "code": null, "e": 27565, "s": 27443, "text": "import { GooglePlaceModule } from \"ngx-google-places-autocomplete\";\n\n@NgModule({\n\n imports: [\n GooglePlaceModule\n ]," }, { "code": null, "e": 27816, "s": 27565, "text": "In HTML file for appcomponent. Define code for input field, in that input field user defined function AddressChange() will be called by (onAddressChange) passing $event and options will take care of country set in country array of component.ts file." }, { "code": null, "e": 27980, "s": 27816, "text": "In component.ts file , user defined function take formatted_address from $event address which is then used to set address in input field by interpolation binding." }, { "code": null, "e": 28087, "s": 27980, "text": "Note: In country Array there is “AU” added for Australia, you can add any other country according to you. " }, { "code": null, "e": 28101, "s": 28087, "text": "app.module.ts" }, { "code": null, "e": 28112, "s": 28101, "text": "Javascript" }, { "code": "import { BrowserModule } from '@angular/platform-browser';import { NgModule } from '@angular/core';import { RouterModule } from '@angular/router';import { AppComponent } from './app.component';import '@angular/compiler';//import for GooglePlaceModuleimport { GooglePlaceModule } from \"ngx-google-places-autocomplete\"; @NgModule({ declarations: [ AppComponent, ], imports: [ BrowserModule, //Adding to imports GooglePlaceModule ], providers: [], bootstrap: [AppComponent]})export class AppModule { }", "e": 28630, "s": 28112, "text": null }, { "code": null, "e": 28649, "s": 28630, "text": "app.component.html" }, { "code": null, "e": 28654, "s": 28649, "text": "HTML" }, { "code": "<div class=\"container\"> <h1>GeeksforGeeks</h1> <h2>Google Places Autocomplete</h2><input ngx-google-places-autocomplete [options]= 'options' (onAddressChange)=\"AddressChange($event)\"/>{{ formattedaddress }}</div>", "e": 28876, "s": 28654, "text": null }, { "code": null, "e": 28893, "s": 28876, "text": "app.component.ts" }, { "code": null, "e": 28904, "s": 28893, "text": "Javascript" }, { "code": "import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent { title = 'rou'; //Local Variable defined formattedaddress=\" \"; options={ componentRestrictions:{ country:[\"AU\"] } } public AddressChange(address: any) { //setting address from API to local variable this.formattedaddress=address.formatted_address}}", "e": 29354, "s": 28904, "text": null }, { "code": null, "e": 29462, "s": 29354, "text": "Run development server using ng serve and write some location to input field to see Autocomplete locations." }, { "code": null, "e": 29477, "s": 29462, "text": "AngularJS-Misc" }, { "code": null, "e": 29488, "s": 29477, "text": "TypeScript" }, { "code": null, "e": 29498, "s": 29488, "text": "AngularJS" }, { "code": null, "e": 29515, "s": 29498, "text": "Web Technologies" }, { "code": null, "e": 29542, "s": 29515, "text": "Web technologies Questions" }, { "code": null, "e": 29640, "s": 29542, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29675, "s": 29640, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 29706, "s": 29675, "text": "Auth Guards in Angular 9/10/11" }, { "code": null, "e": 29741, "s": 29706, "text": "Angular PrimeNG Calendar Component" }, { "code": null, "e": 29776, "s": 29741, "text": "Angular PrimeNG Messages Component" }, { "code": null, "e": 29821, "s": 29776, "text": "How to bundle an Angular app for production?" }, { "code": null, "e": 29861, "s": 29821, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29894, "s": 29861, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29939, "s": 29894, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29982, "s": 29939, "text": "How to fetch data from an API in ReactJS ?" } ]